openadminjs 0.2.0 → 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 +106 -151
- package/dist/adapt-package-manager.js +4 -1
- package/dist/create-project.d.ts +46 -0
- package/dist/create-project.js +417 -150
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +35 -6
- package/dist/index.d.ts +1 -0
- package/dist/index.js +257 -39
- package/dist/render-schema.d.ts +0 -17
- package/dist/render-schema.js +25 -29
- 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/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/package.json +14 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +4 -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 +10 -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 +12 -13
- package/template/apps/api/src/common/prisma.service.ts +9 -17
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +5 -4
- 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 +6 -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/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/adapt-package-manager.test.d.ts +0 -1
- package/dist/adapt-package-manager.test.js +0 -76
- package/dist/cli.e2e.test.d.ts +0 -1
- package/dist/cli.e2e.test.js +0 -87
- package/dist/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -275
- package/dist/database-providers.integration.test.d.ts +0 -1
- package/dist/database-providers.integration.test.js +0 -64
- package/dist/db-commands.test.d.ts +0 -1
- package/dist/db-commands.test.js +0 -27
- package/dist/doctor.test.d.ts +0 -1
- package/dist/doctor.test.js +0 -102
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -11
- package/dist/render-schema.test.d.ts +0 -1
- package/dist/render-schema.test.js +0 -57
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- package/dist/secrets.test.d.ts +0 -1
- package/dist/secrets.test.js +0 -36
- package/dist/security.test.d.ts +0 -1
- package/dist/security.test.js +0 -54
- package/dist/validate-name.test.d.ts +0 -1
- package/dist/validate-name.test.js +0 -63
- 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/json-field-codec.test.ts +0 -76
- package/template/apps/api/src/common/prisma.service.test.ts +0 -19
- 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-apollo-config.test.ts +0 -26
- 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/doctor.d.ts
CHANGED
|
@@ -8,6 +8,19 @@ export type DoctorReport = {
|
|
|
8
8
|
results: CheckResult[];
|
|
9
9
|
ok: boolean;
|
|
10
10
|
};
|
|
11
|
+
/**
|
|
12
|
+
* Verifies the Prisma Client is genuinely usable — not just that the
|
|
13
|
+
* `@prisma/client` package exists on disk. The un-generated package ships a
|
|
14
|
+
* stub that throws "did not initialize yet" at require time, so we actually
|
|
15
|
+
* load it in a child process. This distinguishes:
|
|
16
|
+
* - fail: package missing (deps not installed)
|
|
17
|
+
* - warn: package present but not generated (recoverable: run prisma generate)
|
|
18
|
+
* - pass: generated client loads and exposes PrismaClient
|
|
19
|
+
*/
|
|
20
|
+
export declare function checkPrismaClientUsable(cwd: string, pm: string): {
|
|
21
|
+
status: CheckStatus;
|
|
22
|
+
message: string;
|
|
23
|
+
};
|
|
11
24
|
export declare function runDoctorChecks(cwd: string, opts?: {
|
|
12
25
|
skipNetwork?: boolean;
|
|
13
26
|
}): Promise<DoctorReport>;
|
package/dist/doctor.js
CHANGED
|
@@ -43,6 +43,39 @@ async function tcpReachable(host, port, timeoutMs = 1200) {
|
|
|
43
43
|
socket.once("connect", () => done(true));
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Verifies the Prisma Client is genuinely usable — not just that the
|
|
48
|
+
* `@prisma/client` package exists on disk. The un-generated package ships a
|
|
49
|
+
* stub that throws "did not initialize yet" at require time, so we actually
|
|
50
|
+
* load it in a child process. This distinguishes:
|
|
51
|
+
* - fail: package missing (deps not installed)
|
|
52
|
+
* - warn: package present but not generated (recoverable: run prisma generate)
|
|
53
|
+
* - pass: generated client loads and exposes PrismaClient
|
|
54
|
+
*/
|
|
55
|
+
export function checkPrismaClientUsable(cwd, pm) {
|
|
56
|
+
const pkgDir = join(cwd, "node_modules", "@prisma", "client");
|
|
57
|
+
if (!existsSync(pkgDir)) {
|
|
58
|
+
// Recoverable and already surfaced by the node-modules check; keep as warn.
|
|
59
|
+
return { status: "warn", message: `@prisma/client is not installed — run "${pm} install".` };
|
|
60
|
+
}
|
|
61
|
+
const probe = spawnSync(process.execPath, ["-e", "const m=require('@prisma/client'); if(typeof m.PrismaClient!=='function'){process.exit(3);}"], { cwd, encoding: "utf8", timeout: 20000 });
|
|
62
|
+
if (probe.status === 0) {
|
|
63
|
+
return { status: "pass", message: "Prisma Client is generated and loads successfully." };
|
|
64
|
+
}
|
|
65
|
+
const stderr = (probe.stderr || "").trim();
|
|
66
|
+
const notGenerated = /did not initialize yet|prisma generate/i.test(stderr) || probe.status === 3;
|
|
67
|
+
if (notGenerated) {
|
|
68
|
+
return {
|
|
69
|
+
status: "warn",
|
|
70
|
+
message: `Prisma Client is not generated — run "${pm} db:migrate" or "prisma generate".`
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
// Present, generated, but genuinely fails to load — a blocking error.
|
|
74
|
+
return {
|
|
75
|
+
status: "fail",
|
|
76
|
+
message: `Prisma Client failed to load: ${stderr.split("\n").pop() ?? "unknown error"}`
|
|
77
|
+
};
|
|
78
|
+
}
|
|
46
79
|
export async function runDoctorChecks(cwd, opts = {}) {
|
|
47
80
|
const results = [];
|
|
48
81
|
const add = (name, status, message) => results.push({ name, status, message });
|
|
@@ -87,12 +120,8 @@ export async function runDoctorChecks(cwd, opts = {}) {
|
|
|
87
120
|
else
|
|
88
121
|
add("env-vars", "fail", `Missing env vars: ${missingEnv.join(", ")}.`);
|
|
89
122
|
}
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
if (prismaClient)
|
|
93
|
-
add("prisma-client", "pass", "Prisma Client is available.");
|
|
94
|
-
else
|
|
95
|
-
add("prisma-client", "warn", `Prisma Client not generated — run "${pm} db:migrate" or prisma generate.`);
|
|
123
|
+
const clientCheck = checkPrismaClientUsable(cwd, pm);
|
|
124
|
+
add("prisma-client", clientCheck.status, clientCheck.message);
|
|
96
125
|
// prisma validate (best-effort; only when deps + a local prisma binary exist)
|
|
97
126
|
const prismaBin = join(cwd, "node_modules", ".bin", process.platform === "win32" ? "prisma.cmd" : "prisma");
|
|
98
127
|
if (schema && existsSync(prismaBin)) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
export { createProject, createProjectInteractive, databaseUrl, defaultTemplateDir, printNextSteps, printSecurityNotice, toPackageName, type CreateProjectOptions, type CreateProjectResult, type DatabaseDriver, type PackageManager } from "./create-project.js";
|
|
3
3
|
export { modelNameToResourceSlug } from "./resource-slug.js";
|
|
4
|
+
export declare function insertResourceField(content: string, name: string, snippet: string, force?: boolean): string;
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
2
3
|
import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
3
4
|
import { dirname, join, resolve } from "node:path";
|
|
4
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
|
-
import { assertInsideDir, toKebabCase, toPascalCase, validateName, validatePluginId } from "./validate-name.js";
|
|
12
|
+
import { assertInsideDir, toCamelCase, toKebabCase, toPascalCase, validateName, validatePluginId } from "./validate-name.js";
|
|
10
13
|
import { buildDbCommand, runInherit } from "./db-commands.js";
|
|
11
14
|
import { detectPackageManager } from "./detect-package-manager.js";
|
|
12
15
|
import { runDoctorChecks } from "./doctor.js";
|
|
16
|
+
import { migrateRuntime } from "./runtime-mode.js";
|
|
17
|
+
import { upgradeManaged } from "./upgrade.js";
|
|
13
18
|
import { runSecurityChecks } from "./security.js";
|
|
14
19
|
export { createProject, createProjectInteractive, databaseUrl, defaultTemplateDir, printNextSteps, printSecurityNotice, toPackageName } from "./create-project.js";
|
|
15
20
|
export { modelNameToResourceSlug } from "./resource-slug.js";
|
|
@@ -29,7 +34,12 @@ function generateResource(rawName, options) {
|
|
|
29
34
|
const validated = validateName(rawName, "resource name");
|
|
30
35
|
const model = toPascalCase(validated);
|
|
31
36
|
const slug = toKebabCase(validated);
|
|
32
|
-
const plural =
|
|
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");
|
|
33
43
|
const projectRoot = process.cwd();
|
|
34
44
|
const targetDir = join(projectRoot, "apps/api/src/resources");
|
|
35
45
|
const target = assertInsideDir(targetDir, `${slug}.resource.ts`);
|
|
@@ -38,8 +48,26 @@ function generateResource(rawName, options) {
|
|
|
38
48
|
process.exitCode = 1;
|
|
39
49
|
return;
|
|
40
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
|
+
}
|
|
41
63
|
mkdirSync(targetDir, { recursive: true });
|
|
42
|
-
writeFileSync(target, `import { defineResource } from '@openadminjs/core';\n\nexport default defineResource({\n name: '${plural}',\n label: '${
|
|
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."));
|
|
43
71
|
console.log(pc.green(`Created ${target}`));
|
|
44
72
|
}
|
|
45
73
|
function generatePlugin(rawId, options) {
|
|
@@ -60,20 +88,31 @@ function generatePlugin(rawId, options) {
|
|
|
60
88
|
}
|
|
61
89
|
function normalizeFieldType(raw) {
|
|
62
90
|
const t = raw.trim().toLowerCase();
|
|
63
|
-
if (["number", "int", "integer", "float"
|
|
91
|
+
if (["number", "int", "integer", "float"].includes(t))
|
|
64
92
|
return "number";
|
|
93
|
+
if (t === "decimal" || t === "money")
|
|
94
|
+
return "decimal";
|
|
65
95
|
if (["boolean", "bool"].includes(t))
|
|
66
96
|
return "boolean";
|
|
67
97
|
if (["datetime", "date", "timestamp"].includes(t))
|
|
68
98
|
return "date";
|
|
69
99
|
if (["json", "object"].includes(t))
|
|
70
100
|
return "json";
|
|
71
|
-
|
|
101
|
+
if (["text", "string"].includes(t))
|
|
102
|
+
return "text";
|
|
103
|
+
throw new Error(`Unsupported field type: ${raw}`);
|
|
72
104
|
}
|
|
73
105
|
function prismaFieldFragment(fieldName, fieldType, required) {
|
|
74
106
|
switch (fieldType) {
|
|
75
107
|
case "number":
|
|
76
|
-
|
|
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 ? "" : "?"}`;
|
|
77
116
|
case "boolean":
|
|
78
117
|
return `${fieldName} Boolean${required ? " @default(false)" : "?"}`;
|
|
79
118
|
case "date":
|
|
@@ -129,27 +168,6 @@ function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
|
129
168
|
}
|
|
130
169
|
const fieldType = normalizeFieldType(fieldTypeRaw);
|
|
131
170
|
const content = readFileSync(target, "utf8");
|
|
132
|
-
if (new RegExp(`^\\s*${fieldName}\\s*:`, "m").test(content) && !options.force) {
|
|
133
|
-
console.error(pc.red(`Field "${fieldName}" already present. Use --force to add anyway.`));
|
|
134
|
-
process.exitCode = 1;
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
const fieldsBlock = content.match(/fields:\s*\{[\s\S]*?\n\s*\},\n\s*(permissions|actions|i18n|seo|listScope|hooks|})/m);
|
|
138
|
-
if (fieldsBlock?.index == null) {
|
|
139
|
-
console.error(pc.red("Could not locate fields block (`fields: { ... }`)."));
|
|
140
|
-
process.exitCode = 1;
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
const fieldsStart = fieldsBlock.index;
|
|
144
|
-
const fieldsEnd = fieldsStart + fieldsBlock[0].length;
|
|
145
|
-
const head = content.slice(0, fieldsEnd - fieldsBlock[1].length - 1);
|
|
146
|
-
const tail = content.slice(fieldsEnd - fieldsBlock[1].length - 1);
|
|
147
|
-
const lb = head.lastIndexOf("},");
|
|
148
|
-
if (lb < 0) {
|
|
149
|
-
console.error(pc.red("Malformed resource file near fields."));
|
|
150
|
-
process.exitCode = 1;
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
171
|
const labelJson = JSON.stringify(options.label?.trim() || startCase(fieldName));
|
|
154
172
|
const attributes = [
|
|
155
173
|
`type: '${fieldType}'`,
|
|
@@ -160,11 +178,81 @@ function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
|
160
178
|
options.filterable ? "filterable: true" : "",
|
|
161
179
|
options.searchable ? "searchable: true" : ""
|
|
162
180
|
].filter(Boolean);
|
|
163
|
-
const snippet =
|
|
164
|
-
|
|
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"));
|
|
165
187
|
console.log(pc.green(`Updated ${target}`));
|
|
166
188
|
console.log(pc.dim("// Prisma model fragment — merge into schema.prisma, then run: openadminjs db migrate dev"));
|
|
167
|
-
console.log(pc.dim(`// ${prismaFieldFragment(fieldName, fieldType, Boolean(options.required))}`));
|
|
189
|
+
console.log(pc.dim(`// ${prismaFieldFragment(fieldName, ["float", "decimal", "money"].includes(fieldTypeRaw.trim().toLowerCase()) ? fieldTypeRaw.trim().toLowerCase() : fieldType, Boolean(options.required))}`));
|
|
190
|
+
}
|
|
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);
|
|
210
|
+
}
|
|
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);
|
|
168
256
|
}
|
|
169
257
|
// ── doctor / security ─────────────────────────────────────────────────────────
|
|
170
258
|
async function doctor(options) {
|
|
@@ -234,10 +322,81 @@ async function dbCommand(action, mode, options) {
|
|
|
234
322
|
if (code !== 0)
|
|
235
323
|
process.exitCode = code;
|
|
236
324
|
}
|
|
237
|
-
|
|
238
|
-
|
|
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;
|
|
361
|
+
}
|
|
362
|
+
cli
|
|
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) => {
|
|
239
382
|
try {
|
|
240
|
-
|
|
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
|
+
});
|
|
241
400
|
}
|
|
242
401
|
catch (error) {
|
|
243
402
|
console.error(pc.red(error instanceof Error ? error.message : "Failed to create project."));
|
|
@@ -258,7 +417,10 @@ cli
|
|
|
258
417
|
.option("--sortable", "Mark field as sortable (generate field)")
|
|
259
418
|
.option("--filterable", "Mark field as filterable (generate field)")
|
|
260
419
|
.option("--searchable", "Mark field as searchable (generate field)")
|
|
261
|
-
.option("--force", "
|
|
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")
|
|
262
424
|
.action(runGenerate);
|
|
263
425
|
cli
|
|
264
426
|
.command("make <kind> [name] [fieldName]", "Alias for generate")
|
|
@@ -269,7 +431,10 @@ cli
|
|
|
269
431
|
.option("--sortable", "Mark field as sortable")
|
|
270
432
|
.option("--filterable", "Mark field as filterable")
|
|
271
433
|
.option("--searchable", "Mark field as searchable")
|
|
272
|
-
.option("--force", "
|
|
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")
|
|
273
438
|
.action(runGenerate);
|
|
274
439
|
function runGenerate(kind, name, fieldName, options) {
|
|
275
440
|
try {
|
|
@@ -277,11 +442,17 @@ function runGenerate(kind, name, fieldName, options) {
|
|
|
277
442
|
case "resource":
|
|
278
443
|
if (!name)
|
|
279
444
|
return usageError("openadminjs generate resource <Model> [--force]");
|
|
280
|
-
|
|
445
|
+
if (fieldName)
|
|
446
|
+
return usageError("openadminjs generate resource <Model> [--slug <slug>] [--icon <icon>] [--dry-run]");
|
|
447
|
+
generateResource(name, options);
|
|
281
448
|
return;
|
|
282
449
|
case "plugin":
|
|
283
450
|
if (!name)
|
|
284
451
|
return usageError("openadminjs generate plugin <plugin.id> [--force]");
|
|
452
|
+
if (options.dryRun) {
|
|
453
|
+
console.log(`Would generate plugin ${validatePluginId(name)}`);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
285
456
|
generatePlugin(name, { force: options.force });
|
|
286
457
|
return;
|
|
287
458
|
case "field":
|
|
@@ -295,7 +466,8 @@ function runGenerate(kind, name, fieldName, options) {
|
|
|
295
466
|
sortable: options.sortable,
|
|
296
467
|
filterable: options.filterable,
|
|
297
468
|
searchable: options.searchable,
|
|
298
|
-
label: options.label
|
|
469
|
+
label: options.label,
|
|
470
|
+
dryRun: options.dryRun
|
|
299
471
|
});
|
|
300
472
|
return;
|
|
301
473
|
default:
|
|
@@ -312,6 +484,51 @@ function usageError(usage) {
|
|
|
312
484
|
console.error(pc.red(`Usage: ${usage}`));
|
|
313
485
|
process.exitCode = 1;
|
|
314
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;
|
|
520
|
+
});
|
|
521
|
+
cli
|
|
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
|
+
});
|
|
315
532
|
cli
|
|
316
533
|
.command("doctor", "Check generated project health")
|
|
317
534
|
.option("--json", "Output machine-readable JSON")
|
|
@@ -341,8 +558,9 @@ async function main() {
|
|
|
341
558
|
console.log(`openadminjs ${readPackageVersion()}`);
|
|
342
559
|
process.exit(0);
|
|
343
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.
|
|
344
563
|
if (parsed.options.help || parsed.options.h) {
|
|
345
|
-
cli.outputHelp();
|
|
346
564
|
process.exit(0);
|
|
347
565
|
}
|
|
348
566
|
if (!cli.matchedCommand) {
|
package/dist/render-schema.d.ts
CHANGED
|
@@ -1,20 +1,3 @@
|
|
|
1
1
|
import type { DatabaseDriver } from "./create-project.js";
|
|
2
|
-
/**
|
|
3
|
-
* Transforms the (PostgreSQL-authored) Prisma schema so it is valid for the
|
|
4
|
-
* selected database provider.
|
|
5
|
-
*
|
|
6
|
-
* PostgreSQL: returned unchanged.
|
|
7
|
-
* MySQL: scalar lists (e.g. `String[]`) are unsupported, so they are stored as
|
|
8
|
-
* `Json` arrays instead. Relation lists (e.g. `Post[]`) are left intact
|
|
9
|
-
* because those reference models, not scalars.
|
|
10
|
-
* SQLite: has neither scalar lists NOR a `Json` type. Both scalar lists and
|
|
11
|
-
* `Json`/`Json?` columns become `String`/`String?`; the API's PrismaService
|
|
12
|
-
* transparently JSON-encodes/decodes those columns at runtime for SQLite
|
|
13
|
-
* (see apps/api/src/common/json-field-codec.ts).
|
|
14
|
-
*/
|
|
15
2
|
export declare function renderSchemaForProvider(schema: string, provider: DatabaseDriver): string;
|
|
16
|
-
/**
|
|
17
|
-
* Returns the datasource provider currently declared in a Prisma schema string,
|
|
18
|
-
* or undefined when it cannot be determined.
|
|
19
|
-
*/
|
|
20
3
|
export declare function schemaDatasourceProvider(schema: string): string | undefined;
|
package/dist/render-schema.js
CHANGED
|
@@ -1,37 +1,33 @@
|
|
|
1
|
-
/** Prisma
|
|
2
|
-
|
|
3
|
-
const SCALAR_LIST_RE = new RegExp(`\\b(${SCALAR_TYPES.join("|")})\\[\\]`, "g");
|
|
4
|
-
/**
|
|
5
|
-
* Transforms the (PostgreSQL-authored) Prisma schema so it is valid for the
|
|
6
|
-
* selected database provider.
|
|
7
|
-
*
|
|
8
|
-
* PostgreSQL: returned unchanged.
|
|
9
|
-
* MySQL: scalar lists (e.g. `String[]`) are unsupported, so they are stored as
|
|
10
|
-
* `Json` arrays instead. Relation lists (e.g. `Post[]`) are left intact
|
|
11
|
-
* because those reference models, not scalars.
|
|
12
|
-
* SQLite: has neither scalar lists NOR a `Json` type. Both scalar lists and
|
|
13
|
-
* `Json`/`Json?` columns become `String`/`String?`; the API's PrismaService
|
|
14
|
-
* transparently JSON-encodes/decodes those columns at runtime for SQLite
|
|
15
|
-
* (see apps/api/src/common/json-field-codec.ts).
|
|
1
|
+
/** SQLite (Prisma 6.2+) and MySQL support native JSON, but not scalar lists.
|
|
2
|
+
* Transform only model field type tokens, never values, comments or relations.
|
|
16
3
|
*/
|
|
4
|
+
const SCALAR_TYPES = new Set(["String", "Boolean", "Int", "BigInt", "Float", "Decimal", "DateTime", "Bytes", "Json"]);
|
|
17
5
|
export function renderSchemaForProvider(schema, provider) {
|
|
18
6
|
if (provider === "postgresql")
|
|
19
7
|
return schema;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
8
|
+
let model = false;
|
|
9
|
+
let blockComment = false;
|
|
10
|
+
return schema.split(/(\r?\n)/).map(line => {
|
|
11
|
+
if (/^\s*\/\*/.test(line))
|
|
12
|
+
blockComment = true;
|
|
13
|
+
if (blockComment) {
|
|
14
|
+
if (line.includes("*/"))
|
|
15
|
+
blockComment = false;
|
|
16
|
+
return line;
|
|
17
|
+
}
|
|
18
|
+
if (/^\s*(?:model|type)\s+\w+\s*\{/.test(line)) {
|
|
19
|
+
model = true;
|
|
20
|
+
return line;
|
|
21
|
+
}
|
|
22
|
+
if (/^\s*}\s*(?:\/\/.*)?$/.test(line)) {
|
|
23
|
+
model = false;
|
|
24
|
+
return line;
|
|
25
|
+
}
|
|
26
|
+
if (!model)
|
|
27
|
+
return line;
|
|
28
|
+
return line.replace(/^(\s*[A-Za-z_]\w*\s+)([A-Za-z_]\w*)\[\](?=\s|$)/, (match, prefix, type) => SCALAR_TYPES.has(type) ? prefix + "Json" : match);
|
|
29
|
+
}).join("");
|
|
30
30
|
}
|
|
31
|
-
/**
|
|
32
|
-
* Returns the datasource provider currently declared in a Prisma schema string,
|
|
33
|
-
* or undefined when it cannot be determined.
|
|
34
|
-
*/
|
|
35
31
|
export function schemaDatasourceProvider(schema) {
|
|
36
32
|
return schema.match(/datasource\s+\w+\s*\{[^}]*?provider\s*=\s*"([^"]+)"/m)?.[1];
|
|
37
33
|
}
|
package/dist/resource-slug.d.ts
CHANGED
package/dist/resource-slug.js
CHANGED
|
@@ -2,3 +2,10 @@
|
|
|
2
2
|
export function modelNameToResourceSlug(modelName) {
|
|
3
3
|
return modelName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
4
4
|
}
|
|
5
|
+
export function pluralResourceSlug(slug) {
|
|
6
|
+
if (/(?:[^aeiou])y$/i.test(slug))
|
|
7
|
+
return slug.slice(0, -1) + "ies";
|
|
8
|
+
if (/(s|x|z|ch|sh)$/i.test(slug))
|
|
9
|
+
return slug + "es";
|
|
10
|
+
return slug + "s";
|
|
11
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type Versions = Record<string, string>;
|
|
2
|
+
type Flags = {
|
|
3
|
+
apply?: boolean;
|
|
4
|
+
archives?: string;
|
|
5
|
+
acceptLocalRuntime?: boolean;
|
|
6
|
+
initial?: boolean;
|
|
7
|
+
};
|
|
8
|
+
export declare function migrateRuntime(root: string, template: string, flags?: Flags): {
|
|
9
|
+
mode: string;
|
|
10
|
+
versions: Versions;
|
|
11
|
+
conflicts: string[];
|
|
12
|
+
plannedManifests: string[];
|
|
13
|
+
backup: string;
|
|
14
|
+
applied: boolean;
|
|
15
|
+
};
|
|
16
|
+
export {};
|