openadminjs 0.1.24 → 0.3.0-rc.1
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 +117 -81
- package/dist/adapt-package-manager.d.ts +3 -0
- package/dist/adapt-package-manager.js +118 -0
- package/dist/create-project.d.ts +77 -2
- package/dist/create-project.js +685 -224
- package/dist/db-commands.d.ts +20 -0
- package/dist/db-commands.js +75 -0
- package/dist/detect-package-manager.d.ts +8 -0
- package/dist/detect-package-manager.js +37 -0
- package/dist/doctor.d.ts +26 -0
- package/dist/doctor.js +232 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +476 -166
- package/dist/render-schema.d.ts +3 -0
- package/dist/render-schema.js +33 -0
- package/dist/resource-slug.d.ts +1 -0
- package/dist/resource-slug.js +7 -0
- package/dist/runtime-mode.d.ts +16 -0
- package/dist/runtime-mode.js +138 -0
- package/dist/secrets.d.ts +24 -0
- package/dist/secrets.js +93 -0
- package/dist/security.d.ts +13 -0
- package/dist/security.js +168 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/dist/validate-name.d.ts +33 -0
- package/dist/validate-name.js +206 -0
- package/package.json +39 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +23 -3
- package/template/apps/admin/app/api/auth/login/route.ts +9 -9
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
- package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
- package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
- package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
- package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
- package/template/apps/admin/app/api-tokens/page.tsx +39 -39
- package/template/apps/admin/app/assistant/page.tsx +11 -0
- package/template/apps/admin/app/dashboard/page.tsx +45 -462
- package/template/apps/admin/app/globals.css +52 -16
- package/template/apps/admin/app/layout.tsx +1 -1
- package/template/apps/admin/app/login/page.tsx +13 -145
- package/template/apps/admin/app/plugins/page.tsx +16 -402
- package/template/apps/admin/app/profile/page.tsx +5 -2
- package/template/apps/admin/app/settings/page.tsx +14 -265
- package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
- package/template/apps/admin/components/app-shell.tsx +25 -373
- package/template/apps/admin/components/auth-guard.tsx +8 -28
- package/template/apps/admin/components/logo.tsx +1 -30
- package/template/apps/admin/components/resource-form.tsx +3 -3
- package/template/apps/admin/components/resource-table.tsx +12 -8
- package/template/apps/admin/lib/api.ts +45 -107
- package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
- package/template/apps/admin/lib/server-api.ts +7 -0
- package/template/apps/admin/lib/tokens.ts +9 -81
- package/template/apps/admin/middleware.ts +9 -50
- package/template/apps/admin/next.config.mjs +4 -0
- package/template/apps/admin/package.json +2 -1
- package/template/apps/admin/public/brand/favicon.svg +4 -1
- package/template/apps/admin/tailwind.config.ts +9 -8
- package/template/apps/api/package.json +13 -6
- package/template/apps/api/src/access/catalog.ts +4 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
- package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
- package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
- package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
- package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
- package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
- package/template/apps/api/src/admin/admin.controller.ts +17 -4
- package/template/apps/api/src/admin/admin.module.ts +2 -2
- package/template/apps/api/src/admin/resource-policy.ts +1 -0
- package/template/apps/api/src/admin/resource-query.ts +1 -0
- package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
- package/template/apps/api/src/auth/auth.controller.ts +4 -2
- package/template/apps/api/src/auth/auth.service.ts +68 -83
- package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
- package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
- package/template/apps/api/src/common/api-exception.filter.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +66 -39
- package/template/apps/api/src/common/json-field-codec.ts +138 -0
- package/template/apps/api/src/common/prisma.service.ts +12 -7
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +14 -1
- package/template/apps/api/src/health/health.controller.ts +6 -0
- package/template/apps/api/src/main.ts +11 -2
- package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
- package/template/apps/api/src/resources/commerce.resource.ts +3 -34
- package/template/apps/api/src/resources/operations.resource.ts +1 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
- package/template/apps/api/src/store/payment/payment.module.ts +2 -3
- package/template/apps/api/src/store/payment/payment.service.ts +121 -227
- package/template/apps/api/webpack.config.cjs +2 -1
- package/template/apps/web/next.config.mjs +4 -0
- package/template/apps/web/public/brand/favicon.svg +4 -1
- package/template/compose.yaml +56 -0
- package/template/examples/crm-admin/README.md +31 -0
- package/template/examples/crm-admin/package.json +17 -0
- package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
- package/template/examples/crm-admin/src/index.ts +7 -0
- package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
- package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
- package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
- package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
- package/template/examples/crm-admin/tsconfig.json +7 -0
- package/template/package.json +8 -1
- package/template/packages/admin-client/package.json +18 -0
- package/template/packages/admin-client/src/contracts.ts +29 -0
- package/template/packages/admin-client/src/index.ts +2 -0
- package/template/packages/admin-client/src/preferences.ts +57 -0
- package/template/packages/admin-client/tsconfig.json +12 -0
- package/template/packages/auth/package.json +1 -1
- package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
- package/template/packages/brand/src/generate-assets.mjs +17 -186
- package/template/packages/core/package.json +1 -1
- package/template/packages/mail/package.json +1 -1
- package/template/packages/nest/package.json +22 -0
- package/template/packages/nest/src/api-exception.filter.ts +23 -0
- package/template/packages/nest/src/index.ts +3 -0
- package/template/packages/nest/src/resource-policy.ts +64 -0
- package/template/packages/nest/src/resource-query.ts +103 -0
- package/template/packages/nest/tsconfig.json +12 -0
- package/template/packages/notifications/package.json +1 -1
- package/template/packages/payments/package.json +1 -1
- package/template/packages/permissions/package.json +1 -1
- package/template/packages/permissions/src/index.ts +2 -2
- package/template/packages/plugin-sdk/package.json +1 -1
- package/template/packages/plugin-sdk/src/index.ts +2 -2
- package/template/packages/prisma/package.json +21 -0
- package/template/packages/prisma/schema/ai.prisma +36 -0
- package/template/packages/prisma/schema/audit.prisma +13 -0
- package/template/packages/prisma/schema/commerce.prisma +79 -0
- package/template/packages/prisma/schema/content.prisma +27 -0
- package/template/packages/prisma/schema/core.prisma +106 -0
- package/template/packages/prisma/schema/header.prisma +8 -0
- package/template/packages/prisma/schema/jobs.prisma +9 -0
- package/template/packages/prisma/schema/media.prisma +9 -0
- package/template/packages/prisma/schema/modules.json +47 -0
- package/template/packages/prisma/schema/notifications.prisma +9 -0
- package/template/packages/prisma/schema/settings.prisma +8 -0
- package/template/packages/prisma/schema/tokens.prisma +10 -0
- package/template/packages/prisma/src/index.d.ts +12 -0
- package/template/packages/prisma/src/index.mjs +138 -0
- package/template/packages/queue/package.json +1 -1
- package/template/packages/resource/package.json +1 -1
- package/template/packages/resource/src/index.ts +1 -0
- package/template/packages/storage/package.json +1 -1
- package/template/packages/storage/src/index.ts +37 -0
- package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
- package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
- package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
- package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
- package/template/prisma/schema.prisma +82 -54
- package/template/prisma/seed.ts +14 -38
- package/template/runtime-versions.json +15 -0
- package/template/scripts/db-init.mjs +33 -0
- package/template/scripts/install-crm.mjs +50 -0
- package/template/scripts/migrate-existing.mjs +65 -0
- package/template/scripts/schema.mjs +48 -0
- package/template/tsconfig.base.json +23 -5
- package/LICENSE +0 -21
- package/dist/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -99
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -7
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- package/template/apps/admin/.storybook/main.ts +0 -12
- package/template/apps/admin/.storybook/preview.ts +0 -10
- package/template/apps/admin/app/login/page.test.tsx +0 -18
- package/template/apps/admin/components/auth-guard.test.tsx +0 -55
- package/template/apps/admin/components/logo.stories.tsx +0 -24
- package/template/apps/admin/lib/api.test.ts +0 -118
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
- package/template/apps/admin/vitest.config.ts +0 -7
- package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
- package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
- package/template/apps/api/src/app.module.test.ts +0 -12
- package/template/apps/api/src/auth/auth.service.test.ts +0 -78
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
- package/template/apps/api/src/common/auth.guard.test.ts +0 -62
- package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
- package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
- package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
- package/template/apps/api/src/queue/queue.service.test.ts +0 -33
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
- package/template/apps/api/vitest.config.ts +0 -21
- package/template/apps/web/lib/seo.test.ts +0 -41
- package/template/apps/web/vitest.config.ts +0 -19
- package/template/packages/auth/src/index.test.ts +0 -10
- package/template/packages/brand/src/index.test.ts +0 -9
- package/template/packages/core/src/index.test.ts +0 -27
- package/template/packages/core/vitest.config.ts +0 -9
- package/template/packages/mail/src/index.test.ts +0 -23
- package/template/packages/notifications/src/index.test.ts +0 -9
- package/template/packages/permissions/src/blueprints.test.ts +0 -62
- package/template/packages/permissions/src/index.test.ts +0 -34
- package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
- package/template/packages/plugin-sdk/vitest.config.ts +0 -5
- package/template/packages/queue/src/index.test.ts +0 -12
- package/template/packages/resource/src/index.test.ts +0 -196
- package/template/packages/storage/src/index.test.ts +0 -10
package/dist/index.js
CHANGED
|
@@ -1,122 +1,118 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
2
|
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
5
6
|
import { cac } from "cac";
|
|
6
7
|
import pc from "picocolors";
|
|
7
|
-
import
|
|
8
|
+
import ts from "typescript";
|
|
9
|
+
import { pluralResourceSlug } from "./resource-slug.js";
|
|
10
|
+
import { createProjectInteractive, defaultTemplateDir } from "./create-project.js";
|
|
8
11
|
import { modelNameToResourceSlug } from "./resource-slug.js";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const result = spawnSync(cmd, args, { stdio: "inherit", cwd: process.cwd() });
|
|
24
|
-
if (result.status !== 0 || result.error) {
|
|
25
|
-
process.exitCode = result.status ?? 1;
|
|
12
|
+
import { assertInsideDir, toCamelCase, toKebabCase, toPascalCase, validateName, validatePluginId } from "./validate-name.js";
|
|
13
|
+
import { buildDbCommand, runInherit } from "./db-commands.js";
|
|
14
|
+
import { detectPackageManager } from "./detect-package-manager.js";
|
|
15
|
+
import { runDoctorChecks } from "./doctor.js";
|
|
16
|
+
import { migrateRuntime } from "./runtime-mode.js";
|
|
17
|
+
import { upgradeManaged } from "./upgrade.js";
|
|
18
|
+
import { runSecurityChecks } from "./security.js";
|
|
19
|
+
export { createProject, createProjectInteractive, databaseUrl, defaultTemplateDir, printNextSteps, printSecurityNotice, toPackageName } from "./create-project.js";
|
|
20
|
+
export { modelNameToResourceSlug } from "./resource-slug.js";
|
|
21
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
function readPackageVersion() {
|
|
23
|
+
try {
|
|
24
|
+
const pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8"));
|
|
25
|
+
return pkg.version ?? "0.0.0";
|
|
26
26
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const cwd = process.cwd();
|
|
30
|
-
const required = ["package.json", "pnpm-workspace.yaml", "prisma/schema.prisma"];
|
|
31
|
-
const missing = required.filter((file) => !existsSync(join(cwd, file)));
|
|
32
|
-
const hasEnvSample = existsSync(join(cwd, ".env.example")) || existsSync(join(cwd, "apps", "api", ".env"));
|
|
33
|
-
if (!hasEnvSample) {
|
|
34
|
-
missing.push("apps/api/.env (or .env.example at repo root)");
|
|
35
|
-
}
|
|
36
|
-
if (missing.length) {
|
|
37
|
-
console.error(pc.red("OpenAdminJS doctor found missing files:"));
|
|
38
|
-
for (const file of missing)
|
|
39
|
-
console.error(` - ${file}`);
|
|
40
|
-
process.exitCode = 1;
|
|
41
|
-
return;
|
|
27
|
+
catch {
|
|
28
|
+
return "0.0.0";
|
|
42
29
|
}
|
|
43
|
-
console.log(pc.green("OpenAdminJS doctor passed."));
|
|
44
30
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
findings.push("DATABASE_URL example should not point to production");
|
|
61
|
-
}
|
|
62
|
-
if (existsSync("apps/admin/app")) {
|
|
63
|
-
const login = existsSync("apps/admin/app/login/page.tsx");
|
|
64
|
-
if (!login)
|
|
65
|
-
findings.push("Admin login route is missing");
|
|
66
|
-
}
|
|
67
|
-
if (findings.length) {
|
|
68
|
-
console.error(pc.red("Security check failed:"));
|
|
69
|
-
for (const finding of findings)
|
|
70
|
-
console.error(` - ${finding}`);
|
|
71
|
-
process.exitCode = 1;
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
74
|
-
console.log(pc.green("Security check passed."));
|
|
75
|
-
}
|
|
76
|
-
function generateResource(modelName, options) {
|
|
77
|
-
const name = modelNameToResourceSlug(modelName);
|
|
78
|
-
const targetDir = join(process.cwd(), "apps/api/src/resources");
|
|
79
|
-
const target = join(targetDir, `${name}.resource.ts`);
|
|
31
|
+
const cli = cac("openadminjs");
|
|
32
|
+
// ── generators ──────────────────────────────────────────────────────────────
|
|
33
|
+
function generateResource(rawName, options) {
|
|
34
|
+
const validated = validateName(rawName, "resource name");
|
|
35
|
+
const model = toPascalCase(validated);
|
|
36
|
+
const slug = toKebabCase(validated);
|
|
37
|
+
const plural = options.slug ?? pluralResourceSlug(slug);
|
|
38
|
+
if (!/^[a-z][a-z0-9-]*$/.test(plural))
|
|
39
|
+
throw new Error("Invalid resource slug");
|
|
40
|
+
const icon = options.icon ?? "Database";
|
|
41
|
+
if (!/^[A-Za-z][A-Za-z0-9]*$/.test(icon))
|
|
42
|
+
throw new Error("Invalid icon name");
|
|
43
|
+
const projectRoot = process.cwd();
|
|
44
|
+
const targetDir = join(projectRoot, "apps/api/src/resources");
|
|
45
|
+
const target = assertInsideDir(targetDir, `${slug}.resource.ts`);
|
|
80
46
|
if (existsSync(target) && !options.force) {
|
|
81
47
|
console.error(pc.red(`${target} already exists. Use --force to overwrite.`));
|
|
82
48
|
process.exitCode = 1;
|
|
83
49
|
return;
|
|
84
50
|
}
|
|
51
|
+
const registryPath = join(targetDir, "registry.ts");
|
|
52
|
+
const registry = existsSync(registryPath) ? readFileSync(registryPath, "utf8") : undefined;
|
|
53
|
+
const schemaPath = join(projectRoot, "prisma", "schema.prisma");
|
|
54
|
+
const schema = existsSync(schemaPath) ? readFileSync(schemaPath, "utf8") : undefined;
|
|
55
|
+
const modelExists = Boolean(schema && new RegExp(`^\\s*model\\s+${model}\\s*\\{`, "m").test(schema));
|
|
56
|
+
const registered = registry && modelExists ? registerResourceImport(registry, slug, toCamelCase(model)) : undefined;
|
|
57
|
+
if (options.dryRun) {
|
|
58
|
+
console.log(`Would create ${target}${registered ? " and register resource" : ""}`);
|
|
59
|
+
if (!modelExists)
|
|
60
|
+
console.log(`Add model ${model} to prisma/schema.prisma before registering the resource.`);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
85
63
|
mkdirSync(targetDir, { recursive: true });
|
|
86
|
-
|
|
87
|
-
|
|
64
|
+
writeFileSync(target, `import { defineResource } from '@openadminjs/core';\n\nexport default defineResource({\n name: '${plural}',\n label: '${startCase(plural)}',\n model: '${toCamelCase(model)}',\n titleField: 'id',\n icon: '${icon}',\n permissions: {\n read: '${plural}.read',\n create: '${plural}.create',\n update: '${plural}.update',\n delete: '${plural}.delete',\n },\n fields: {\n id: { type: 'id', label: 'ID', create: false, edit: false },\n },\n});\n`);
|
|
65
|
+
if (registered !== undefined && registered !== registry)
|
|
66
|
+
writeFileSync(registryPath, registered);
|
|
67
|
+
if (!modelExists)
|
|
68
|
+
console.log(pc.yellow(`Add model ${model} { id String @id @default(cuid()) } to Prisma, migrate, then register this resource in registry.ts.`));
|
|
69
|
+
else
|
|
70
|
+
console.log(pc.dim("Run db:seed after migration to materialize resource permissions."));
|
|
88
71
|
console.log(pc.green(`Created ${target}`));
|
|
89
72
|
}
|
|
90
|
-
function generatePlugin(
|
|
91
|
-
const safeId =
|
|
92
|
-
const slug = safeId.replace(/\./g, "-");
|
|
93
|
-
const
|
|
94
|
-
const
|
|
73
|
+
function generatePlugin(rawId, options) {
|
|
74
|
+
const safeId = validatePluginId(rawId);
|
|
75
|
+
const slug = safeId.replace(/\./g, "-").toLowerCase();
|
|
76
|
+
const varName = slug.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
77
|
+
const projectRoot = process.cwd();
|
|
78
|
+
const targetDir = join(projectRoot, "apps/api/src/plugins/custom");
|
|
79
|
+
const target = assertInsideDir(targetDir, `${slug}.plugin.ts`);
|
|
95
80
|
if (existsSync(target) && !options.force) {
|
|
96
81
|
console.error(pc.red(`${target} already exists. Use --force to overwrite.`));
|
|
97
82
|
process.exitCode = 1;
|
|
98
83
|
return;
|
|
99
84
|
}
|
|
100
85
|
mkdirSync(targetDir, { recursive: true });
|
|
101
|
-
writeFileSync(target, `import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";\n\nexport const ${
|
|
86
|
+
writeFileSync(target, `import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";\n\nexport const ${varName}Plugin: OpenAdminPlugin = {\n id: ${JSON.stringify(safeId)},\n version: "0.1.0",\n register({ registerSurface }) {\n registerSurface({\n seo: {\n metadata({ resourceName, record }) {\n if (resourceName !== "posts") return {};\n return { title: record.title ?? "Untitled" };\n }\n }\n });\n }\n};\n`);
|
|
102
87
|
console.log(pc.green(`Created ${target}`));
|
|
103
88
|
}
|
|
104
89
|
function normalizeFieldType(raw) {
|
|
105
90
|
const t = raw.trim().toLowerCase();
|
|
106
|
-
if (["number", "int", "integer", "float"
|
|
91
|
+
if (["number", "int", "integer", "float"].includes(t))
|
|
107
92
|
return "number";
|
|
93
|
+
if (t === "decimal" || t === "money")
|
|
94
|
+
return "decimal";
|
|
108
95
|
if (["boolean", "bool"].includes(t))
|
|
109
96
|
return "boolean";
|
|
110
97
|
if (["datetime", "date", "timestamp"].includes(t))
|
|
111
98
|
return "date";
|
|
112
99
|
if (["json", "object"].includes(t))
|
|
113
100
|
return "json";
|
|
114
|
-
|
|
101
|
+
if (["text", "string"].includes(t))
|
|
102
|
+
return "text";
|
|
103
|
+
throw new Error(`Unsupported field type: ${raw}`);
|
|
115
104
|
}
|
|
116
105
|
function prismaFieldFragment(fieldName, fieldType, required) {
|
|
117
106
|
switch (fieldType) {
|
|
118
107
|
case "number":
|
|
119
|
-
|
|
108
|
+
case "int":
|
|
109
|
+
case "integer":
|
|
110
|
+
return `${fieldName} Int${required ? "" : "?"}`;
|
|
111
|
+
case "float":
|
|
112
|
+
return `${fieldName} Float${required ? "" : "?"}`;
|
|
113
|
+
case "decimal":
|
|
114
|
+
case "money":
|
|
115
|
+
return `${fieldName} Decimal${required ? "" : "?"}`;
|
|
120
116
|
case "boolean":
|
|
121
117
|
return `${fieldName} Boolean${required ? " @default(false)" : "?"}`;
|
|
122
118
|
case "date":
|
|
@@ -157,6 +153,8 @@ function startCase(input) {
|
|
|
157
153
|
return withSpaces ? withSpaces[0].toUpperCase() + withSpaces.slice(1) : input;
|
|
158
154
|
}
|
|
159
155
|
function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
156
|
+
// resourceArg is only used to resolve an existing file; validate to block traversal.
|
|
157
|
+
validateName(resourceArg.replace(/\.resource\.ts$/i, ""), "resource");
|
|
160
158
|
const target = resolveResourceFile(resourceArg);
|
|
161
159
|
if (!target) {
|
|
162
160
|
console.error(pc.red(`Could not find *.resource.ts for "${resourceArg}" under apps/api/src/resources`));
|
|
@@ -164,33 +162,12 @@ function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
|
164
162
|
return;
|
|
165
163
|
}
|
|
166
164
|
if (!/^[a-z][a-zA-Z0-9]*$/.test(fieldName)) {
|
|
167
|
-
console.error(pc.red("fieldName must be camelCase"));
|
|
165
|
+
console.error(pc.red("fieldName must be camelCase (e.g. publishedAt)."));
|
|
168
166
|
process.exitCode = 1;
|
|
169
167
|
return;
|
|
170
168
|
}
|
|
171
169
|
const fieldType = normalizeFieldType(fieldTypeRaw);
|
|
172
170
|
const content = readFileSync(target, "utf8");
|
|
173
|
-
if (new RegExp(`^\\s*${fieldName}\\s*:`, "m").test(content) && !options.force) {
|
|
174
|
-
console.error(pc.red(`Field "${fieldName}" already present. Use --force to add anyway.`));
|
|
175
|
-
process.exitCode = 1;
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
const fieldsBlock = content.match(/fields:\s*\{[\s\S]*?\n\s*\},\n\s*(permissions|actions|i18n|seo|listScope|hooks|})/m);
|
|
179
|
-
if (fieldsBlock?.index == null) {
|
|
180
|
-
console.error(pc.red('Could not locate fields block (`fields: { ... }`).'));
|
|
181
|
-
process.exitCode = 1;
|
|
182
|
-
return;
|
|
183
|
-
}
|
|
184
|
-
const fieldsStart = fieldsBlock.index;
|
|
185
|
-
const fieldsEnd = fieldsStart + fieldsBlock[0].length;
|
|
186
|
-
const head = content.slice(0, fieldsEnd - fieldsBlock[1].length - 1);
|
|
187
|
-
const tail = content.slice(fieldsEnd - fieldsBlock[1].length - 1);
|
|
188
|
-
const lb = head.lastIndexOf("},");
|
|
189
|
-
if (lb < 0) {
|
|
190
|
-
console.error(pc.red("Malformed resource file near fields."));
|
|
191
|
-
process.exitCode = 1;
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
171
|
const labelJson = JSON.stringify(options.label?.trim() || startCase(fieldName));
|
|
195
172
|
const attributes = [
|
|
196
173
|
`type: '${fieldType}'`,
|
|
@@ -201,90 +178,423 @@ function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
|
201
178
|
options.filterable ? "filterable: true" : "",
|
|
202
179
|
options.searchable ? "searchable: true" : ""
|
|
203
180
|
].filter(Boolean);
|
|
204
|
-
const snippet =
|
|
205
|
-
|
|
181
|
+
const snippet = `${fieldName}: { ${attributes.join(", ")} }`;
|
|
182
|
+
const next = insertResourceField(content, fieldName, snippet, Boolean(options.force));
|
|
183
|
+
if (!options.dryRun)
|
|
184
|
+
writeFileSync(target, next);
|
|
185
|
+
else
|
|
186
|
+
console.log(pc.dim("Dry run — no files written"));
|
|
206
187
|
console.log(pc.green(`Updated ${target}`));
|
|
207
|
-
console.log(pc.dim("// Prisma model fragment — merge into schema.prisma, then
|
|
208
|
-
console.log(pc.dim(`// ${prismaFieldFragment(fieldName, fieldType, Boolean(options.required))}`));
|
|
188
|
+
console.log(pc.dim("// Prisma model fragment — merge into schema.prisma, then run: openadminjs db migrate dev"));
|
|
189
|
+
console.log(pc.dim(`// ${prismaFieldFragment(fieldName, ["float", "decimal", "money"].includes(fieldTypeRaw.trim().toLowerCase()) ? fieldTypeRaw.trim().toLowerCase() : fieldType, Boolean(options.required))}`));
|
|
209
190
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
191
|
+
function readSource(content) {
|
|
192
|
+
return ts.createSourceFile("resource.ts", content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
193
|
+
}
|
|
194
|
+
function propertyName(node) {
|
|
195
|
+
return node && (ts.isIdentifier(node) || ts.isStringLiteral(node)) ? node.text : undefined;
|
|
196
|
+
}
|
|
197
|
+
export function insertResourceField(content, name, snippet, force = false) {
|
|
198
|
+
const source = readSource(content);
|
|
199
|
+
const matches = [];
|
|
200
|
+
function visit(node) {
|
|
201
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "defineResource") {
|
|
202
|
+
const arg = node.arguments[0];
|
|
203
|
+
if (arg && ts.isObjectLiteralExpression(arg)) {
|
|
204
|
+
const fields = arg.properties.find(p => propertyName(p.name) === "fields");
|
|
205
|
+
if (fields && ts.isPropertyAssignment(fields) && ts.isObjectLiteralExpression(fields.initializer))
|
|
206
|
+
matches.push(fields.initializer);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
ts.forEachChild(node, visit);
|
|
214
210
|
}
|
|
215
|
-
|
|
216
|
-
|
|
211
|
+
visit(source);
|
|
212
|
+
if (matches.length !== 1)
|
|
213
|
+
throw new Error("Expected exactly one literal defineResource fields object");
|
|
214
|
+
const fields = matches[0];
|
|
215
|
+
if (fields.properties.some(p => ts.isSpreadAssignment(p) || p.name && ts.isComputedPropertyName(p.name)))
|
|
216
|
+
throw new Error("Cannot safely edit dynamic resource fields");
|
|
217
|
+
const existing = fields.properties.find(p => propertyName(p.name) === name);
|
|
218
|
+
if (existing) {
|
|
219
|
+
if (!force)
|
|
220
|
+
throw new Error("Field already exists. Use --force to replace it.");
|
|
221
|
+
return content.slice(0, existing.getStart(source)) + snippet + content.slice(existing.getEnd());
|
|
222
|
+
}
|
|
223
|
+
const close = fields.getEnd() - 1;
|
|
224
|
+
const last = fields.properties[fields.properties.length - 1];
|
|
225
|
+
if (last && !fields.properties.hasTrailingComma)
|
|
226
|
+
return content.slice(0, last.getEnd()) + "," + content.slice(last.getEnd(), close) + "\n " + snippet + ",\n " + content.slice(close);
|
|
227
|
+
return content.slice(0, close) + "\n " + snippet + ",\n " + content.slice(close);
|
|
228
|
+
}
|
|
229
|
+
function registerResourceImport(content, slug, name) {
|
|
230
|
+
const source = readSource(content);
|
|
231
|
+
const modulePath = "./" + slug + ".resource";
|
|
232
|
+
if (source.statements.some(node => ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text === modulePath))
|
|
233
|
+
return content;
|
|
234
|
+
const localName = name + "GeneratedResource";
|
|
235
|
+
if (new RegExp("\\b" + localName + "\\b").test(content))
|
|
236
|
+
throw new Error("Resource import name conflict");
|
|
237
|
+
let array;
|
|
238
|
+
for (const statement of source.statements) {
|
|
239
|
+
if (!ts.isVariableStatement(statement))
|
|
240
|
+
continue;
|
|
241
|
+
for (const decl of statement.declarationList.declarations) {
|
|
242
|
+
if (!ts.isIdentifier(decl.name) || decl.name.text !== "resources")
|
|
243
|
+
continue;
|
|
244
|
+
let init = decl.initializer;
|
|
245
|
+
while (init && (ts.isSatisfiesExpression(init) || ts.isAsExpression(init)))
|
|
246
|
+
init = init.expression;
|
|
247
|
+
if (init && ts.isArrayLiteralExpression(init))
|
|
248
|
+
array = init;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (!array)
|
|
252
|
+
throw new Error("Cannot safely locate resource registry array");
|
|
253
|
+
const last = array.elements[array.elements.length - 1];
|
|
254
|
+
const insertion = last ? last.getEnd() : array.getEnd() - 1;
|
|
255
|
+
return 'import ' + localName + ' from "' + modulePath + '";\n' + content.slice(0, insertion) + (last ? ",\n " : "") + localName + content.slice(insertion);
|
|
256
|
+
}
|
|
257
|
+
// ── doctor / security ─────────────────────────────────────────────────────────
|
|
258
|
+
async function doctor(options) {
|
|
259
|
+
const report = await runDoctorChecks(process.cwd(), { skipNetwork: options.skipNetwork });
|
|
260
|
+
if (options.json) {
|
|
261
|
+
console.log(JSON.stringify(report, null, 2));
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
console.log(pc.bold("OpenAdminJS doctor"));
|
|
265
|
+
for (const r of report.results)
|
|
266
|
+
printCheck(r);
|
|
267
|
+
console.log(report.ok ? pc.green("\nDoctor: no blocking issues.") : pc.red("\nDoctor: failed checks found."));
|
|
268
|
+
}
|
|
269
|
+
if (!report.ok)
|
|
217
270
|
process.exitCode = 1;
|
|
271
|
+
}
|
|
272
|
+
function printCheck(r) {
|
|
273
|
+
const icon = r.status === "pass" ? pc.green("PASS") : r.status === "warn" ? pc.yellow("WARN") : pc.red("FAIL");
|
|
274
|
+
console.log(` [${icon}] ${r.name}: ${r.message}`);
|
|
275
|
+
}
|
|
276
|
+
function securityCheck(options) {
|
|
277
|
+
const report = runSecurityChecks(process.cwd(), { skipNetwork: options.skipNetwork });
|
|
278
|
+
if (options.json) {
|
|
279
|
+
console.log(JSON.stringify(report, null, 2));
|
|
218
280
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
.action((action) => {
|
|
225
|
-
switch (action) {
|
|
226
|
-
case "migrate":
|
|
227
|
-
console.log("Run: pnpm --filter @openadminjs/api prisma migrate dev");
|
|
228
|
-
return;
|
|
229
|
-
case "seed":
|
|
230
|
-
console.log("Run: pnpm --filter @openadminjs/api prisma db seed");
|
|
231
|
-
return;
|
|
232
|
-
case "studio":
|
|
233
|
-
console.log("Run: pnpm --filter @openadminjs/api prisma studio");
|
|
234
|
-
return;
|
|
235
|
-
default:
|
|
236
|
-
console.error(pc.red("Unknown db action. Use: migrate, seed, studio."));
|
|
237
|
-
process.exitCode = 1;
|
|
281
|
+
else {
|
|
282
|
+
console.log(pc.bold("OpenAdminJS security check"));
|
|
283
|
+
for (const f of report.findings)
|
|
284
|
+
printFinding(f);
|
|
285
|
+
console.log(report.ok ? pc.green("\nSecurity: no critical issues.") : pc.red("\nSecurity: critical issues found."));
|
|
238
286
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
287
|
+
if (!report.ok)
|
|
288
|
+
process.exitCode = 1;
|
|
289
|
+
}
|
|
290
|
+
function printFinding(f) {
|
|
291
|
+
const sev = f.severity === "critical" ? pc.red("CRIT") : f.severity === "warning" ? pc.yellow("WARN") : pc.cyan("INFO");
|
|
292
|
+
console.log(` [${sev}] ${f.id}: ${f.message}`);
|
|
293
|
+
}
|
|
294
|
+
// ── db commands ────────────────────────────────────────────────────────────
|
|
295
|
+
async function dbCommand(action, mode, options) {
|
|
296
|
+
if (!action) {
|
|
297
|
+
console.error(pc.red("Usage: openadminjs db <migrate [dev|deploy]|seed|studio|reset> [--dry-run]"));
|
|
298
|
+
process.exitCode = 1;
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
const cwd = process.cwd();
|
|
302
|
+
const pm = detectPackageManager(cwd);
|
|
303
|
+
let command;
|
|
304
|
+
try {
|
|
305
|
+
command = buildDbCommand(action, mode, pm);
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
console.error(pc.red(error instanceof Error ? error.message : "Invalid db command."));
|
|
243
309
|
process.exitCode = 1;
|
|
244
310
|
return;
|
|
245
311
|
}
|
|
246
|
-
if (
|
|
247
|
-
|
|
312
|
+
if (options.dryRun) {
|
|
313
|
+
console.log(command.label);
|
|
248
314
|
return;
|
|
249
315
|
}
|
|
250
|
-
if (
|
|
251
|
-
|
|
316
|
+
if (command.destructive && !options.yes) {
|
|
317
|
+
console.error(pc.red(`"${command.label}" is destructive and will drop data. Re-run with --yes to confirm.`));
|
|
318
|
+
process.exitCode = 1;
|
|
252
319
|
return;
|
|
253
320
|
}
|
|
254
|
-
|
|
255
|
-
|
|
321
|
+
const code = await runInherit(command.cmd, command.args, cwd);
|
|
322
|
+
if (code !== 0)
|
|
323
|
+
process.exitCode = code;
|
|
324
|
+
}
|
|
325
|
+
function normalizeDatabase(value) {
|
|
326
|
+
if (!value)
|
|
327
|
+
return undefined;
|
|
328
|
+
const v = value.trim().toLowerCase();
|
|
329
|
+
if (v === "postgres" || v === "postgresql" || v === "pg")
|
|
330
|
+
return "postgresql";
|
|
331
|
+
if (v === "mysql" || v === "mariadb")
|
|
332
|
+
return "mysql";
|
|
333
|
+
if (v === "sqlite" || v === "sqlite3")
|
|
334
|
+
return "sqlite";
|
|
335
|
+
throw new Error(`Unknown database "${value}". Use postgresql, mysql, or sqlite.`);
|
|
336
|
+
}
|
|
337
|
+
function normalizePackageManager(value) {
|
|
338
|
+
if (!value)
|
|
339
|
+
return undefined;
|
|
340
|
+
const v = value.trim().toLowerCase();
|
|
341
|
+
if (v === "pnpm" || v === "npm" || v === "yarn")
|
|
342
|
+
return v;
|
|
343
|
+
throw new Error(`Unknown package manager "${value}". Use pnpm, npm, or yarn.`);
|
|
344
|
+
}
|
|
345
|
+
/** Resolves the admin password from flags/env WITHOUT exposing it in argv where avoidable. */
|
|
346
|
+
function resolveAdminPassword(flags) {
|
|
347
|
+
if (flags.adminPasswordEnv) {
|
|
348
|
+
const value = process.env[flags.adminPasswordEnv];
|
|
349
|
+
if (!value) {
|
|
350
|
+
throw new Error(`--admin-password-env ${flags.adminPasswordEnv} is set but the environment variable is empty or unset.`);
|
|
351
|
+
}
|
|
352
|
+
return value;
|
|
353
|
+
}
|
|
354
|
+
if (flags.adminPassword) {
|
|
355
|
+
console.error(pc.yellow("Warning: --admin-password exposes the password in your shell history. Prefer --admin-password-env <VAR>."));
|
|
356
|
+
return flags.adminPassword;
|
|
357
|
+
}
|
|
358
|
+
if (process.env.OPENADMIN_ADMIN_PASSWORD)
|
|
359
|
+
return process.env.OPENADMIN_ADMIN_PASSWORD;
|
|
360
|
+
return undefined;
|
|
256
361
|
}
|
|
257
362
|
cli
|
|
258
|
-
.command("
|
|
259
|
-
.option("--
|
|
363
|
+
.command("create [projectName]", "Create a new OpenAdminJS project")
|
|
364
|
+
.option("--package-manager <pm>", "Package manager: pnpm, npm, or yarn")
|
|
365
|
+
.option("--pm <pm>", "Alias for --package-manager")
|
|
366
|
+
.option("--database <db>", "Database: postgresql, mysql, or sqlite")
|
|
367
|
+
.option("--db <db>", "Alias for --database")
|
|
368
|
+
.option("--admin-email <email>", "Superadmin email")
|
|
369
|
+
.option("--admin-password <password>", "Superadmin password (discouraged — prefer --admin-password-env)")
|
|
370
|
+
.option("--admin-password-env <var>", "Read the superadmin password from this environment variable")
|
|
371
|
+
.option("--db-url <url>", "DATABASE_URL override")
|
|
372
|
+
.option("--redis-url <url>", "REDIS_URL (blank/omit disables background job queues)")
|
|
373
|
+
.option("--skip-redis", "Disable Redis-backed queues")
|
|
374
|
+
.option("--api-port <port>", "API port (default 4000)")
|
|
375
|
+
.option("--admin-origin <origin>", "Admin origin for CORS (default http://localhost:3000)")
|
|
376
|
+
.option("--runtime <mode>", "Runtime mode: source (default) or registry (after packages are published)")
|
|
377
|
+
.option("--no-install", "Skip dependency install and DB setup")
|
|
378
|
+
.option("--no-git", "Skip git initialization")
|
|
379
|
+
.option("--non-interactive", "Do not prompt; use flags and safe defaults")
|
|
380
|
+
.option("-y, --yes", "Accept defaults without prompting (implies --non-interactive)")
|
|
381
|
+
.action(async (projectName, flags) => {
|
|
382
|
+
try {
|
|
383
|
+
const nonInteractive = Boolean(flags.yes || flags.nonInteractive) || !process.stdin.isTTY;
|
|
384
|
+
await createProjectInteractive({
|
|
385
|
+
projectName,
|
|
386
|
+
runtimeMode: flags.runtime === undefined || flags.runtime === 'source' ? 'source' : flags.runtime === 'registry' ? 'registry' : (() => { throw Error('Invalid runtime mode'); })(),
|
|
387
|
+
packageManager: normalizePackageManager(flags.packageManager ?? flags.pm),
|
|
388
|
+
database: normalizeDatabase(flags.database ?? flags.db),
|
|
389
|
+
superadminEmail: flags.adminEmail,
|
|
390
|
+
superadminPassword: resolveAdminPassword(flags),
|
|
391
|
+
databaseUrl: flags.dbUrl,
|
|
392
|
+
redisUrl: flags.skipRedis ? undefined : flags.redisUrl,
|
|
393
|
+
skipRedis: flags.skipRedis,
|
|
394
|
+
apiPort: flags.apiPort,
|
|
395
|
+
adminOrigin: flags.adminOrigin,
|
|
396
|
+
install: flags.install,
|
|
397
|
+
git: flags.git,
|
|
398
|
+
nonInteractive
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
console.error(pc.red(error instanceof Error ? error.message : "Failed to create project."));
|
|
403
|
+
process.exitCode = 1;
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
cli
|
|
407
|
+
.command("db <action> [mode]", "Database commands: migrate [dev|deploy], seed, studio, reset")
|
|
408
|
+
.option("--dry-run", "Print the command without executing it")
|
|
409
|
+
.option("--yes", "Confirm destructive commands (e.g. reset)")
|
|
410
|
+
.action((action, mode, options) => dbCommand(action, mode, options));
|
|
411
|
+
cli
|
|
412
|
+
.command("generate <kind> [name] [fieldName]", "Generate a resource, plugin, or field")
|
|
413
|
+
.option("--type <type>", "Field type for `generate field` (text, number, boolean, date, json)", { default: "text" })
|
|
414
|
+
.option("--label <label>", "Field label override (generate field)")
|
|
415
|
+
.option("--required", "Mark field as required (generate field)")
|
|
416
|
+
.option("--list", "Show field in list views (generate field)")
|
|
417
|
+
.option("--sortable", "Mark field as sortable (generate field)")
|
|
418
|
+
.option("--filterable", "Mark field as filterable (generate field)")
|
|
419
|
+
.option("--searchable", "Mark field as searchable (generate field)")
|
|
420
|
+
.option("--force", "Replace existing resource or field")
|
|
421
|
+
.option("--dry-run", "Print generation plan without writing")
|
|
422
|
+
.option("--slug <slug>", "Resource route slug")
|
|
423
|
+
.option("--icon <icon>", "Resource icon")
|
|
424
|
+
.action(runGenerate);
|
|
425
|
+
cli
|
|
426
|
+
.command("make <kind> [name] [fieldName]", "Alias for generate")
|
|
427
|
+
.option("--type <type>", "Field type for `make field`", { default: "text" })
|
|
260
428
|
.option("--label <label>", "Field label override")
|
|
261
429
|
.option("--required", "Mark field as required")
|
|
262
430
|
.option("--list", "Show field in list views")
|
|
263
431
|
.option("--sortable", "Mark field as sortable")
|
|
264
432
|
.option("--filterable", "Mark field as filterable")
|
|
265
433
|
.option("--searchable", "Mark field as searchable")
|
|
266
|
-
.option("--force", "
|
|
267
|
-
.
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
434
|
+
.option("--force", "Replace existing resource or field")
|
|
435
|
+
.option("--dry-run", "Print generation plan without writing")
|
|
436
|
+
.option("--slug <slug>", "Resource route slug")
|
|
437
|
+
.option("--icon <icon>", "Resource icon")
|
|
438
|
+
.action(runGenerate);
|
|
439
|
+
function runGenerate(kind, name, fieldName, options) {
|
|
440
|
+
try {
|
|
441
|
+
switch (kind) {
|
|
442
|
+
case "resource":
|
|
443
|
+
if (!name)
|
|
444
|
+
return usageError("openadminjs generate resource <Model> [--force]");
|
|
445
|
+
if (fieldName)
|
|
446
|
+
return usageError("openadminjs generate resource <Model> [--slug <slug>] [--icon <icon>] [--dry-run]");
|
|
447
|
+
generateResource(name, options);
|
|
448
|
+
return;
|
|
449
|
+
case "plugin":
|
|
450
|
+
if (!name)
|
|
451
|
+
return usageError("openadminjs generate plugin <plugin.id> [--force]");
|
|
452
|
+
if (options.dryRun) {
|
|
453
|
+
console.log(`Would generate plugin ${validatePluginId(name)}`);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
generatePlugin(name, { force: options.force });
|
|
457
|
+
return;
|
|
458
|
+
case "field":
|
|
459
|
+
if (!name || !fieldName) {
|
|
460
|
+
return usageError("openadminjs generate field <resource> <fieldName> [--type <type>] [--required] ...");
|
|
461
|
+
}
|
|
462
|
+
generateResourceField(name, fieldName, options.type ?? "text", {
|
|
463
|
+
force: options.force,
|
|
464
|
+
required: options.required,
|
|
465
|
+
list: options.list,
|
|
466
|
+
sortable: options.sortable,
|
|
467
|
+
filterable: options.filterable,
|
|
468
|
+
searchable: options.searchable,
|
|
469
|
+
label: options.label,
|
|
470
|
+
dryRun: options.dryRun
|
|
471
|
+
});
|
|
472
|
+
return;
|
|
473
|
+
default:
|
|
474
|
+
console.error(pc.red(`Unknown generate kind "${kind ?? ""}". Use: resource, plugin, or field.`));
|
|
475
|
+
process.exitCode = 1;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
console.error(pc.red(error instanceof Error ? error.message : "Generation failed."));
|
|
480
|
+
process.exitCode = 1;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
function usageError(usage) {
|
|
484
|
+
console.error(pc.red(`Usage: ${usage}`));
|
|
485
|
+
process.exitCode = 1;
|
|
486
|
+
}
|
|
487
|
+
cli
|
|
488
|
+
.command("schema <action>", "Compose/adopt schema modules or plan an existing database upgrade")
|
|
489
|
+
.option("--out <directory>", "New migration review directory (upgrade-plan)")
|
|
490
|
+
.option("--write", "Explicitly write the composed schema")
|
|
491
|
+
.option("--replace-generated", "Acknowledge overwriting a known generated schema")
|
|
492
|
+
.action((action, flags) => {
|
|
493
|
+
let script, args;
|
|
494
|
+
if (action === "upgrade-plan") {
|
|
495
|
+
if (!flags.out)
|
|
496
|
+
throw Error("Use schema upgrade-plan --out <new-directory>");
|
|
497
|
+
script = "migrate-existing.mjs";
|
|
498
|
+
args = ["--out", flags.out];
|
|
499
|
+
}
|
|
500
|
+
else if (["check", "adopt", "compose"].includes(action)) {
|
|
501
|
+
script = "schema.mjs";
|
|
502
|
+
args = [action, ...(flags.write ? ["--write"] : []), ...(flags.replaceGenerated ? ["--replace-generated"] : [])];
|
|
503
|
+
}
|
|
504
|
+
else
|
|
505
|
+
throw Error("Use schema check, adopt, compose, or upgrade-plan");
|
|
506
|
+
const result = spawnSync(process.execPath, [join(defaultTemplateDir(), "scripts", script), ...args], { cwd: process.cwd(), stdio: "inherit" });
|
|
507
|
+
if (result.error || result.status !== 0)
|
|
508
|
+
process.exitCode = result.status ?? 1;
|
|
509
|
+
});
|
|
510
|
+
cli
|
|
511
|
+
.command("runtime", "Plan migration from copied runtime sources to versioned packages")
|
|
512
|
+
.option("--apply", "Switch package manifests and preserve old runtime sources in a backup")
|
|
513
|
+
.option("--archives <dir>", "Use verified candidate tarballs instead of registry packages (pnpm only)")
|
|
514
|
+
.option("--accept-local-runtime", "Acknowledge customized or untracked runtime source; preserve it in the backup")
|
|
515
|
+
.action((flags) => {
|
|
516
|
+
const result = migrateRuntime(process.cwd(), defaultTemplateDir(), flags);
|
|
517
|
+
console.log(JSON.stringify(result, null, 2));
|
|
518
|
+
if (result.conflicts.length && flags.apply && !flags.acceptLocalRuntime)
|
|
519
|
+
process.exitCode = 1;
|
|
277
520
|
});
|
|
278
521
|
cli
|
|
279
|
-
.command("
|
|
280
|
-
.option("--
|
|
281
|
-
.
|
|
522
|
+
.command("upgrade", "Plan a conservative framework source patch (does not migrate the database)")
|
|
523
|
+
.option("--apply", "Apply only unmodified managed files; abort on conflicts")
|
|
524
|
+
.option("--rollback", "Restore the last managed patch if its files are still unchanged")
|
|
525
|
+
.option("--json", "Machine-readable plan")
|
|
526
|
+
.action((flags) => {
|
|
527
|
+
const plan = upgradeManaged(process.cwd(), defaultTemplateDir(), flags);
|
|
528
|
+
console.log(flags.json ? JSON.stringify(plan, null, 2) : plan.map(p => p.status + " " + p.path).join("\n") || "No managed changes");
|
|
529
|
+
if (plan.some(p => p.status === "conflict"))
|
|
530
|
+
process.exitCode = 1;
|
|
531
|
+
});
|
|
282
532
|
cli
|
|
283
|
-
.command("
|
|
284
|
-
.option("--
|
|
285
|
-
.
|
|
286
|
-
|
|
287
|
-
cli
|
|
288
|
-
|
|
533
|
+
.command("doctor", "Check generated project health")
|
|
534
|
+
.option("--json", "Output machine-readable JSON")
|
|
535
|
+
.option("--skip-network", "Skip network-dependent checks (db/redis/pm)")
|
|
536
|
+
.action((options) => doctor(options));
|
|
537
|
+
cli
|
|
538
|
+
.command("security [check]", "Run the security checklist")
|
|
539
|
+
.option("--json", "Output machine-readable JSON")
|
|
540
|
+
.option("--skip-network", "Skip network-dependent checks (npm audit)")
|
|
541
|
+
.action((_sub, options) => securityCheck(options));
|
|
542
|
+
// NOTE: we intentionally do NOT call cli.version() — cac's built-in prints a
|
|
543
|
+
// "name/version platform node" line. We handle --version/-v manually below to
|
|
544
|
+
// output the exact "openadminjs <version>" format.
|
|
289
545
|
cli.help();
|
|
290
|
-
|
|
546
|
+
async function main() {
|
|
547
|
+
const argv = process.argv;
|
|
548
|
+
let parsed;
|
|
549
|
+
try {
|
|
550
|
+
parsed = cli.parse(argv, { run: false });
|
|
551
|
+
}
|
|
552
|
+
catch (error) {
|
|
553
|
+
console.error(pc.red(error instanceof Error ? error.message : String(error)));
|
|
554
|
+
console.error(pc.dim("Run `openadminjs --help` for usage."));
|
|
555
|
+
process.exit(1);
|
|
556
|
+
}
|
|
557
|
+
if (parsed.options.version || parsed.options.v) {
|
|
558
|
+
console.log(`openadminjs ${readPackageVersion()}`);
|
|
559
|
+
process.exit(0);
|
|
560
|
+
}
|
|
561
|
+
// NOTE: cac's parse() already prints help once when --help/-h is present
|
|
562
|
+
// (showHelpOnExit). Do NOT call outputHelp() again here or it prints twice.
|
|
563
|
+
if (parsed.options.help || parsed.options.h) {
|
|
564
|
+
process.exit(0);
|
|
565
|
+
}
|
|
566
|
+
if (!cli.matchedCommand) {
|
|
567
|
+
const requested = parsed.args[0];
|
|
568
|
+
if (requested) {
|
|
569
|
+
console.error(pc.red(`Unknown command: ${requested}`));
|
|
570
|
+
console.error(pc.dim("Run `openadminjs --help` to see available commands."));
|
|
571
|
+
process.exit(1);
|
|
572
|
+
}
|
|
573
|
+
cli.outputHelp();
|
|
574
|
+
process.exit(0);
|
|
575
|
+
}
|
|
576
|
+
try {
|
|
577
|
+
await cli.runMatchedCommand();
|
|
578
|
+
}
|
|
579
|
+
catch (error) {
|
|
580
|
+
console.error(pc.red(error instanceof Error ? error.message : String(error)));
|
|
581
|
+
process.exit(1);
|
|
582
|
+
}
|
|
583
|
+
if (process.exitCode && process.exitCode !== 0)
|
|
584
|
+
process.exit(process.exitCode);
|
|
585
|
+
}
|
|
586
|
+
function isCliEntry() {
|
|
587
|
+
const entry = process.argv[1];
|
|
588
|
+
if (!entry)
|
|
589
|
+
return false;
|
|
590
|
+
const modulePath = fileURLToPath(import.meta.url);
|
|
591
|
+
try {
|
|
592
|
+
return realpathSync(resolve(entry)) === realpathSync(modulePath);
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
return resolve(entry) === modulePath;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
if (isCliEntry()) {
|
|
599
|
+
void main();
|
|
600
|
+
}
|