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
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { lstat, mkdir, open, unlink } from "node:fs/promises";
|
|
3
|
+
import { resolve, join } from "node:path";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
1
5
|
export type FileValidation = {
|
|
2
6
|
maxSizeBytes: number;
|
|
3
7
|
mimeTypes: string[];
|
|
@@ -21,3 +25,36 @@ export const defaultFileValidation: FileValidation = {
|
|
|
21
25
|
mimeTypes: ["image/png", "image/jpeg", "image/webp", "application/pdf", "text/plain"],
|
|
22
26
|
extensions: [".png", ".jpg", ".jpeg", ".webp", ".pdf", ".txt"]
|
|
23
27
|
};
|
|
28
|
+
|
|
29
|
+
/** Local private storage; only opaque generated keys are accepted. */
|
|
30
|
+
export class LocalStorage implements StorageDriver {
|
|
31
|
+
constructor(private readonly root = resolve(process.env.UPLOADS_ROOT || "uploads")) {}
|
|
32
|
+
private async location(path: string) {
|
|
33
|
+
if (!/^uploads\/[a-f0-9]{48}$/.test(path)) throw new Error("Invalid storage key");
|
|
34
|
+
await mkdir(this.root, {recursive:true,mode:0o700});
|
|
35
|
+
const stat = await lstat(this.root);
|
|
36
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Invalid storage root");
|
|
37
|
+
return join(this.root,path.slice(8));
|
|
38
|
+
}
|
|
39
|
+
async put(file: Buffer, meta: StoredFile): Promise<StoredFile> {
|
|
40
|
+
if (file.length > defaultFileValidation.maxSizeBytes) throw new Error("File too large");
|
|
41
|
+
const path = "uploads/" + randomBytes(24).toString("hex");
|
|
42
|
+
const target = await this.location(path);
|
|
43
|
+
const handle = await open(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
44
|
+
try { await handle.writeFile(file); } catch(e) { await handle.close(); await unlink(target).catch(()=>undefined); throw e; }
|
|
45
|
+
await handle.close();
|
|
46
|
+
return {...meta,path,size:file.length};
|
|
47
|
+
}
|
|
48
|
+
async read(path: string): Promise<Buffer> {
|
|
49
|
+
const handle = await open(await this.location(path), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
50
|
+
try {
|
|
51
|
+
const stat = await handle.stat();
|
|
52
|
+
if (!stat.isFile() || stat.size > defaultFileValidation.maxSizeBytes) throw new Error("Invalid stored object");
|
|
53
|
+
return await handle.readFile();
|
|
54
|
+
} finally { await handle.close(); }
|
|
55
|
+
}
|
|
56
|
+
async delete(path: string): Promise<void> {
|
|
57
|
+
const target = await this.location(path);
|
|
58
|
+
await unlink(target).catch(e=>{if(e.code!=="ENOENT") throw e;});
|
|
59
|
+
}
|
|
60
|
+
}
|
package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
-- AlterTable
|
|
2
|
+
ALTER TABLE "User" ADD COLUMN "oidcKey" TEXT;
|
|
3
|
+
|
|
4
|
+
-- AlterTable
|
|
5
|
+
ALTER TABLE "Category" ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0;
|
|
6
|
+
|
|
7
|
+
-- CreateIndex
|
|
8
|
+
CREATE UNIQUE INDEX "User_oidcKey_key" ON "User"("oidcKey");
|
|
9
|
+
|
|
10
|
+
-- CreateIndex
|
|
11
|
+
CREATE INDEX "Category_order_idx" ON "Category"("order");
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
-- Legacy refresh tokens and access JWTs without sid become invalid.
|
|
2
|
+
UPDATE "User" SET "refreshTokenHash" = NULL;
|
|
3
|
+
CREATE TABLE "Session" (
|
|
4
|
+
"id" TEXT NOT NULL,
|
|
5
|
+
"userId" TEXT NOT NULL,
|
|
6
|
+
"realm" TEXT NOT NULL,
|
|
7
|
+
"expiresAt" TIMESTAMP(3) NOT NULL,
|
|
8
|
+
"revokedAt" TIMESTAMP(3),
|
|
9
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
10
|
+
"lastUsedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
11
|
+
CONSTRAINT "Session_pkey" PRIMARY KEY ("id"),
|
|
12
|
+
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
|
13
|
+
);
|
|
14
|
+
CREATE TABLE "SessionToken" (
|
|
15
|
+
"id" TEXT NOT NULL,
|
|
16
|
+
"sessionId" TEXT NOT NULL,
|
|
17
|
+
"tokenHash" TEXT NOT NULL,
|
|
18
|
+
"usedAt" TIMESTAMP(3),
|
|
19
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
20
|
+
CONSTRAINT "SessionToken_pkey" PRIMARY KEY ("id"),
|
|
21
|
+
CONSTRAINT "SessionToken_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "Session"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
|
22
|
+
);
|
|
23
|
+
CREATE INDEX "Session_userId_realm_idx" ON "Session"("userId", "realm");
|
|
24
|
+
CREATE INDEX "Session_expiresAt_idx" ON "Session"("expiresAt");
|
|
25
|
+
CREATE UNIQUE INDEX "SessionToken_tokenHash_key" ON "SessionToken"("tokenHash");
|
|
26
|
+
CREATE INDEX "SessionToken_sessionId_idx" ON "SessionToken"("sessionId");
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
ALTER TABLE "Order" ADD COLUMN "checkoutKey" TEXT, ADD COLUMN "checkoutRequestHash" TEXT, ADD COLUMN "checkoutSessionId" TEXT, ADD COLUMN "paymentIntentId" TEXT;
|
|
2
|
+
ALTER TABLE "WebhookLog" ADD COLUMN "providerEventId" TEXT;
|
|
3
|
+
CREATE UNIQUE INDEX "Order_checkoutKey_key" ON "Order"("checkoutKey");
|
|
4
|
+
CREATE UNIQUE INDEX "Order_checkoutSessionId_key" ON "Order"("checkoutSessionId");
|
|
5
|
+
CREATE UNIQUE INDEX "Order_paymentIntentId_key" ON "Order"("paymentIntentId");
|
|
6
|
+
CREATE UNIQUE INDEX "WebhookLog_providerEventId_key" ON "WebhookLog"("providerEventId");
|
|
@@ -13,7 +13,9 @@ model User {
|
|
|
13
13
|
passwordHash String
|
|
14
14
|
/** Stable IdP subject, format `issuerNormalized::sub` — set when user signs in via OIDC. */
|
|
15
15
|
oidcKey String? @unique
|
|
16
|
+
/// Legacy refresh hash; invalidated by session migration.
|
|
16
17
|
refreshTokenHash String?
|
|
18
|
+
sessions Session[]
|
|
17
19
|
name String?
|
|
18
20
|
avatarUrl String?
|
|
19
21
|
status String @default("active")
|
|
@@ -68,42 +70,48 @@ model RolePermission {
|
|
|
68
70
|
@@id([roleId, permissionId])
|
|
69
71
|
}
|
|
70
72
|
|
|
71
|
-
model
|
|
73
|
+
model PasswordResetToken {
|
|
72
74
|
id String @id @default(cuid())
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
75
|
+
tokenHash String
|
|
76
|
+
expiresAt DateTime
|
|
77
|
+
usedAt DateTime?
|
|
78
|
+
userId String
|
|
79
|
+
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
80
|
+
}
|
|
79
81
|
|
|
80
|
-
|
|
82
|
+
model EmailVerificationToken {
|
|
83
|
+
id String @id @default(cuid())
|
|
84
|
+
tokenHash String
|
|
85
|
+
expiresAt DateTime
|
|
86
|
+
usedAt DateTime?
|
|
87
|
+
userId String
|
|
88
|
+
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
81
89
|
}
|
|
82
90
|
|
|
83
|
-
model
|
|
84
|
-
id
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
author User? @relation(fields: [authorId], references: [id])
|
|
91
|
+
model Session {
|
|
92
|
+
id String @id @default(cuid())
|
|
93
|
+
userId String
|
|
94
|
+
realm String
|
|
95
|
+
expiresAt DateTime
|
|
96
|
+
revokedAt DateTime?
|
|
97
|
+
createdAt DateTime @default(now())
|
|
98
|
+
lastUsedAt DateTime @default(now())
|
|
99
|
+
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
100
|
+
tokens SessionToken[]
|
|
101
|
+
|
|
102
|
+
@@index([userId, realm])
|
|
103
|
+
@@index([expiresAt])
|
|
97
104
|
}
|
|
98
105
|
|
|
99
|
-
model
|
|
100
|
-
id
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
106
|
+
model SessionToken {
|
|
107
|
+
id String @id @default(cuid())
|
|
108
|
+
sessionId String
|
|
109
|
+
tokenHash String @unique
|
|
110
|
+
usedAt DateTime?
|
|
111
|
+
createdAt DateTime @default(now())
|
|
112
|
+
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
|
113
|
+
|
|
114
|
+
@@index([sessionId])
|
|
107
115
|
}
|
|
108
116
|
|
|
109
117
|
model AuditLog {
|
|
@@ -129,10 +137,48 @@ model Setting {
|
|
|
129
137
|
updatedAt DateTime @updatedAt
|
|
130
138
|
}
|
|
131
139
|
|
|
140
|
+
model FileAsset {
|
|
141
|
+
id String @id @default(cuid())
|
|
142
|
+
filename String
|
|
143
|
+
path String
|
|
144
|
+
mimeType String
|
|
145
|
+
size Int
|
|
146
|
+
createdAt DateTime @default(now())
|
|
147
|
+
posts Post[]
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
model Category {
|
|
151
|
+
id String @id @default(cuid())
|
|
152
|
+
name String
|
|
153
|
+
slug String @unique
|
|
154
|
+
order Int @default(0)
|
|
155
|
+
createdAt DateTime @default(now())
|
|
156
|
+
updatedAt DateTime @updatedAt
|
|
157
|
+
posts Post[]
|
|
158
|
+
|
|
159
|
+
@@index([order])
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
model Post {
|
|
163
|
+
id String @id @default(cuid())
|
|
164
|
+
title String
|
|
165
|
+
slug String @unique
|
|
166
|
+
status String @default("draft")
|
|
167
|
+
content String?
|
|
168
|
+
categoryId String?
|
|
169
|
+
coverImageId String?
|
|
170
|
+
authorId String?
|
|
171
|
+
createdAt DateTime @default(now())
|
|
172
|
+
updatedAt DateTime @updatedAt
|
|
173
|
+
category Category? @relation(fields: [categoryId], references: [id])
|
|
174
|
+
coverImage FileAsset? @relation(fields: [coverImageId], references: [id])
|
|
175
|
+
author User? @relation(fields: [authorId], references: [id])
|
|
176
|
+
}
|
|
177
|
+
|
|
132
178
|
model ApiToken {
|
|
133
179
|
id String @id @default(cuid())
|
|
134
180
|
name String
|
|
135
|
-
tokenHash String
|
|
181
|
+
tokenHash String @unique
|
|
136
182
|
scopes String[]
|
|
137
183
|
revokedAt DateTime?
|
|
138
184
|
createdAt DateTime @default(now())
|
|
@@ -160,28 +206,6 @@ model JobLog {
|
|
|
160
206
|
updatedAt DateTime @updatedAt
|
|
161
207
|
}
|
|
162
208
|
|
|
163
|
-
model PasswordResetToken {
|
|
164
|
-
id String @id @default(cuid())
|
|
165
|
-
tokenHash String
|
|
166
|
-
expiresAt DateTime
|
|
167
|
-
usedAt DateTime?
|
|
168
|
-
userId String
|
|
169
|
-
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
model EmailVerificationToken {
|
|
173
|
-
id String @id @default(cuid())
|
|
174
|
-
tokenHash String
|
|
175
|
-
expiresAt DateTime
|
|
176
|
-
usedAt DateTime?
|
|
177
|
-
userId String
|
|
178
|
-
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// ──────────────────────────────────────────────
|
|
182
|
-
// Commerce / Payments
|
|
183
|
-
// ──────────────────────────────────────────────
|
|
184
|
-
|
|
185
209
|
model Product {
|
|
186
210
|
id String @id @default(cuid())
|
|
187
211
|
name String
|
|
@@ -209,6 +233,10 @@ model Order {
|
|
|
209
233
|
/** Total in smallest currency unit */
|
|
210
234
|
total Int
|
|
211
235
|
notes String?
|
|
236
|
+
checkoutKey String? @unique
|
|
237
|
+
checkoutRequestHash String?
|
|
238
|
+
checkoutSessionId String? @unique
|
|
239
|
+
paymentIntentId String? @unique
|
|
212
240
|
metadata Json?
|
|
213
241
|
createdAt DateTime @default(now())
|
|
214
242
|
updatedAt DateTime @updatedAt
|
|
@@ -250,6 +278,7 @@ model WebhookLog {
|
|
|
250
278
|
id String @id @default(cuid())
|
|
251
279
|
provider String
|
|
252
280
|
eventType String
|
|
281
|
+
providerEventId String? @unique
|
|
253
282
|
payload Json
|
|
254
283
|
/** pending | processed | failed */
|
|
255
284
|
status String @default("pending")
|
|
@@ -293,4 +322,3 @@ model AiArtifact {
|
|
|
293
322
|
|
|
294
323
|
@@index([userId, createdAt])
|
|
295
324
|
}
|
|
296
|
-
|
package/template/prisma/seed.ts
CHANGED
|
@@ -85,6 +85,7 @@ async function askForSuperadminCredentials(): Promise<SeedCredentials> {
|
|
|
85
85
|
|
|
86
86
|
async function main() {
|
|
87
87
|
const superadmin = await askForSuperadminCredentials();
|
|
88
|
+
if (["viewer@example.com", "shopper@example.com"].includes(superadmin.email.toLowerCase()) || superadmin.password.length < 12) throw new Error("Use a non-demo administrator email and a password of at least 12 characters");
|
|
88
89
|
|
|
89
90
|
const mergedCatalog: { name: string; label: { en: string; ru: string } }[] = [...permissionCatalog];
|
|
90
91
|
for (const p of publicPermissionCatalog) {
|
|
@@ -144,10 +145,7 @@ async function main() {
|
|
|
144
145
|
|
|
145
146
|
const user = await prisma.user.upsert({
|
|
146
147
|
where: { email: superadmin.email },
|
|
147
|
-
update: {
|
|
148
|
-
name: "Admin",
|
|
149
|
-
passwordHash: await bcrypt.hash(superadmin.password, 12)
|
|
150
|
-
},
|
|
148
|
+
update: {},
|
|
151
149
|
create: {
|
|
152
150
|
email: superadmin.email,
|
|
153
151
|
name: "Admin",
|
|
@@ -167,41 +165,18 @@ async function main() {
|
|
|
167
165
|
create: { userId: user.id, roleId: publicMemberRole.id }
|
|
168
166
|
});
|
|
169
167
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
email: "viewer@example.com",
|
|
179
|
-
name: "Viewer",
|
|
180
|
-
passwordHash: await bcrypt.hash("password", 12)
|
|
181
|
-
}
|
|
182
|
-
});
|
|
183
|
-
await prisma.userRole.upsert({
|
|
184
|
-
where: { userId_roleId: { userId: viewerUser.id, roleId: viewerRole.id } },
|
|
185
|
-
update: {},
|
|
186
|
-
create: { userId: viewerUser.id, roleId: viewerRole.id }
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const shopper = await prisma.user.upsert({
|
|
191
|
-
where: { email: "shopper@example.com" },
|
|
192
|
-
update: {},
|
|
193
|
-
create: {
|
|
194
|
-
email: "shopper@example.com",
|
|
195
|
-
name: "Shopper",
|
|
196
|
-
passwordHash: await bcrypt.hash("password", 12)
|
|
168
|
+
// Previous releases seeded known credentials. Disable only unchanged demo accounts.
|
|
169
|
+
for (const email of ["viewer@example.com", "shopper@example.com"]) {
|
|
170
|
+
const legacy = await prisma.user.findUnique({ where: { email } });
|
|
171
|
+
if (legacy && await bcrypt.compare("password", legacy.passwordHash)) {
|
|
172
|
+
await prisma.$transaction(async tx => {
|
|
173
|
+
const updated = await tx.user.updateMany({ where: { id: legacy.id, passwordHash: legacy.passwordHash }, data: { status: "blocked", refreshTokenHash: null } });
|
|
174
|
+
if (updated.count) await tx.session.updateMany({ where: { userId: legacy.id, revokedAt: null }, data: { revokedAt: new Date() } });
|
|
175
|
+
});
|
|
197
176
|
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
update: {},
|
|
202
|
-
create: { userId: shopper.id, roleId: publicMemberRole.id }
|
|
203
|
-
});
|
|
204
|
-
|
|
177
|
+
}
|
|
178
|
+
// No fixed demo accounts are created by normal seed.
|
|
179
|
+
if (process.env.NODE_ENV !== "production" && process.env.SEED_DEMO_DATA === "1") {
|
|
205
180
|
const category = await prisma.category.upsert({
|
|
206
181
|
where: { slug: "announcements" },
|
|
207
182
|
update: {},
|
|
@@ -241,6 +216,7 @@ async function main() {
|
|
|
241
216
|
create: { ...product, active: true }
|
|
242
217
|
});
|
|
243
218
|
}
|
|
219
|
+
}
|
|
244
220
|
}
|
|
245
221
|
|
|
246
222
|
main().finally(async () => prisma.$disconnect());
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"@openadminjs/resource": "0.2.0-rc.1",
|
|
3
|
+
"@openadminjs/core": "0.2.0-rc.1",
|
|
4
|
+
"@openadminjs/auth": "0.2.0-rc.1",
|
|
5
|
+
"@openadminjs/permissions": "0.2.0-rc.1",
|
|
6
|
+
"@openadminjs/plugin-sdk": "0.2.0-rc.1",
|
|
7
|
+
"@openadminjs/storage": "0.2.0-rc.1",
|
|
8
|
+
"@openadminjs/queue": "0.2.0-rc.1",
|
|
9
|
+
"@openadminjs/notifications": "0.2.0-rc.1",
|
|
10
|
+
"@openadminjs/mail": "0.2.0-rc.1",
|
|
11
|
+
"@openadminjs/payments": "0.2.0-rc.1",
|
|
12
|
+
"@openadminjs/nest": "0.2.0-rc.1",
|
|
13
|
+
"@openadminjs/admin-client": "0.2.0-rc.1",
|
|
14
|
+
"@openadminjs/prisma": "0.2.0-rc.1"
|
|
15
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {readFileSync,existsSync,readdirSync} from "node:fs";
|
|
2
|
+
import {join,resolve} from "node:path";
|
|
3
|
+
import {spawnSync} from "node:child_process";
|
|
4
|
+
import {createRequire} from "node:module";
|
|
5
|
+
const root=process.cwd();
|
|
6
|
+
const {schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
|
|
7
|
+
const schema=join(root,"prisma/schema.prisma"),provider=schemaProvider(readFileSync(schema,"utf8"));
|
|
8
|
+
const history=join(root,"prisma/migrations");
|
|
9
|
+
const hasHistory=existsSync(history)&&readdirSync(history,{withFileTypes:true}).some(e=>e.isDirectory());
|
|
10
|
+
const cli=resolve("node_modules/prisma/build/index.js");
|
|
11
|
+
if(!existsSync(cli))throw Error("Install dependencies first");
|
|
12
|
+
if(!process.env.DATABASE_URL){
|
|
13
|
+
const envFile=[join(root,".env"),join(root,"apps/api/.env")].find(existsSync);
|
|
14
|
+
if(envFile){
|
|
15
|
+
const dotenv=createRequire(join(root,"apps/api/package.json"))("dotenv");
|
|
16
|
+
dotenv.config({path:envFile});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
if(!process.env.DATABASE_URL)throw Error("Set DATABASE_URL for this project");
|
|
20
|
+
const url=process.env.DATABASE_URL;
|
|
21
|
+
if(provider==="sqlite"?!url.startsWith("file:"):provider==="mysql"?!url.startsWith("mysql:"):!/^postgres(?:ql)?:/.test(url))throw Error("Database URL and schema provider mismatch");
|
|
22
|
+
if(provider==="postgresql"&&!hasHistory)throw Error("PostgreSQL requires reviewed migration history");
|
|
23
|
+
if(!hasHistory&&process.env.NODE_ENV==="production")throw Error("Production requires reviewed migration history; schema push is disabled");
|
|
24
|
+
if(hasHistory){
|
|
25
|
+
const lock=readFileSync(join(history,"migration_lock.toml"),"utf8");
|
|
26
|
+
if(!lock.includes('provider = "'+provider+'"'))throw Error("Migration provider mismatch");
|
|
27
|
+
}
|
|
28
|
+
const run=args=>{
|
|
29
|
+
const result=spawnSync(process.execPath,[cli,...args,"--schema",schema],{stdio:"inherit"});
|
|
30
|
+
if(result.error||result.status!==0)process.exit(result.status??1);
|
|
31
|
+
};
|
|
32
|
+
run(hasHistory?["migrate","deploy"]:["db","push","--skip-generate"]);
|
|
33
|
+
run(["generate"]);
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import {readFileSync,writeFileSync,existsSync,mkdirSync,rmSync,readdirSync} from "node:fs";
|
|
2
|
+
import {resolve,join} from "node:path";
|
|
3
|
+
import {fileURLToPath} from "node:url";
|
|
4
|
+
import {createHash} from "node:crypto";
|
|
5
|
+
const root=process.cwd();
|
|
6
|
+
const example=fileURLToPath(new URL("../examples/crm-admin/",import.meta.url));
|
|
7
|
+
const schemaPath=join(root,"prisma/schema.prisma");
|
|
8
|
+
const registryPath=join(root,"apps/api/src/resources/registry.ts");
|
|
9
|
+
const args=process.argv.slice(2);
|
|
10
|
+
if(args.length!==1||!["--dry-run","--apply"].includes(args[0]))throw Error("Usage: node scripts/install-crm.mjs --dry-run|--apply");
|
|
11
|
+
const schema=readFileSync(schemaPath,"utf8"),registry=readFileSync(registryPath,"utf8");
|
|
12
|
+
const names=["companies","contacts","deals","activities"];
|
|
13
|
+
const fragment=readFileSync(join(example,"prisma/models.fragment.prisma"),"utf8");
|
|
14
|
+
for(const name of ["Contact","Company","Deal","Activity"])if(new RegExp("\\bmodel\\s+"+name+"\\s*\\{").test(schema))throw Error("Existing model: "+name);
|
|
15
|
+
const resourceDir=join(root,"apps/api/src/resources/crm");
|
|
16
|
+
if(existsSync(resourceDir))throw Error("CRM directory already exists");
|
|
17
|
+
const marker="export const resources = [";
|
|
18
|
+
if(registry.split(marker).length!==2)throw Error("Registry changed; merge the example manually");
|
|
19
|
+
for(const name of names)if(registry.includes("crm/"+name+".resource"))throw Error("Already registered");
|
|
20
|
+
const source=names.map(name=>[name,readFileSync(join(example,"src/resources/"+name+".resource.ts"),"utf8")]);
|
|
21
|
+
const imports=names.map(name=>"import crm_"+name+" from \"./crm/"+name+".resource\";").join("\n");
|
|
22
|
+
const nextRegistry=imports+"\n"+registry.replace(marker,marker+"\n "+names.map(n=>"crm_"+n).join(",\n ")+",");
|
|
23
|
+
console.log("Plan: add a CRM schema module, add 4 resource modules, register 4 resources. No database commands.");
|
|
24
|
+
if(args[0]==="--dry-run")process.exit(0);
|
|
25
|
+
const moduleDir=join(root,"prisma/modules"),manifestPath=join(moduleDir,"manifest.json"),moduleFile=join(moduleDir,"crm.prisma");
|
|
26
|
+
const originalManifest=existsSync(manifestPath)?readFileSync(manifestPath,"utf8"):undefined;
|
|
27
|
+
const manifest=originalManifest?JSON.parse(originalManifest):null;
|
|
28
|
+
const sha=s=>createHash("sha256").update(s).digest("hex");
|
|
29
|
+
if(existsSync(moduleFile))throw Error("CRM schema module already exists");
|
|
30
|
+
const {composeSchema,schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
|
|
31
|
+
const provider=schemaProvider(schema);
|
|
32
|
+
let nextSchema;
|
|
33
|
+
if(manifest){
|
|
34
|
+
if(manifest.lastSchemaHash!==sha(schema))throw Error("Adopted schema has drift; reconcile first");
|
|
35
|
+
nextSchema=schema+"\n"+fragment+"\n";
|
|
36
|
+
}else{
|
|
37
|
+
const custom=existsSync(moduleDir)?readdirSync(moduleDir).filter(n=>n.endsWith(".prisma")).sort().map(n=>[n,readFileSync(join(moduleDir,n),"utf8")]):[];
|
|
38
|
+
if(composeSchema({provider,customFragments:custom.map(x=>x[1])})!==schema)throw Error("Schema has local edits; run schema adopt before installing CRM");
|
|
39
|
+
nextSchema=composeSchema({provider,customFragments:[...custom,["crm.prisma",fragment]].sort((a,b)=>a[0].localeCompare(b[0])).map(x=>x[1])});
|
|
40
|
+
}
|
|
41
|
+
try{
|
|
42
|
+
mkdirSync(resourceDir);
|
|
43
|
+
for(const [name,body] of source)writeFileSync(join(resourceDir,name+".resource.ts"),body,{flag:"wx"});
|
|
44
|
+
mkdirSync(moduleDir,{recursive:true});
|
|
45
|
+
writeFileSync(moduleFile,manifest?"\n"+fragment+"\n":fragment,{flag:"wx"});
|
|
46
|
+
writeFileSync(schemaPath,nextSchema);
|
|
47
|
+
if(manifest){manifest.files.push("crm.prisma");manifest.lastSchemaHash=sha(nextSchema);writeFileSync(manifestPath,JSON.stringify(manifest,null,2)+"\n");}
|
|
48
|
+
writeFileSync(registryPath,nextRegistry);
|
|
49
|
+
}catch(error){rmSync(moduleFile,{force:true});if(originalManifest)writeFileSync(manifestPath,originalManifest);writeFileSync(schemaPath,schema);writeFileSync(registryPath,registry);rmSync(resourceDir,{recursive:true,force:true});throw error;}
|
|
50
|
+
console.log("CRM installed. Review schema, create a migration and seed permissions before starting.");
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plan a same-provider upgrade of a V1 project. Does not apply SQL, mark
|
|
3
|
+
* migrations as applied, change source files, or write credentials.
|
|
4
|
+
*/
|
|
5
|
+
import {readFileSync,writeFileSync,mkdirSync,existsSync,readdirSync} from "node:fs";
|
|
6
|
+
import {resolve,join} from "node:path";
|
|
7
|
+
import {spawnSync} from "node:child_process";
|
|
8
|
+
import {createHash} from "node:crypto";
|
|
9
|
+
const {mergeLegacySchema,providers,schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
|
|
10
|
+
const args=process.argv.slice(2);
|
|
11
|
+
if(args.length!==2||args[0]!=="--out")throw Error("Usage: node scripts/migrate-existing.mjs --out <new-directory> (DATABASE_URL must point to a staging copy)");
|
|
12
|
+
const root=process.cwd(),source=join(root,"prisma/schema.prisma"),out=resolve(args[1]);
|
|
13
|
+
if(existsSync(out))throw Error("Output directory already exists");
|
|
14
|
+
if(!process.env.DATABASE_URL)throw Error("Set DATABASE_URL explicitly to an isolated staging database");
|
|
15
|
+
const original=readFileSync(source,"utf8"),provider=schemaProvider(original);
|
|
16
|
+
if(!providers.includes(provider))throw Error("Unsupported provider");
|
|
17
|
+
const url=process.env.DATABASE_URL;
|
|
18
|
+
if(provider==="sqlite"?!url.startsWith("file:"):provider==="mysql"?!url.startsWith("mysql:"):!/^postgres(?:ql)?:/.test(url))throw Error("DATABASE_URL provider mismatch");
|
|
19
|
+
const plan=mergeLegacySchema(original,provider);
|
|
20
|
+
const prisma=join(root,"node_modules/prisma/build/index.js");
|
|
21
|
+
if(!existsSync(prisma))throw Error("Install this project's Prisma 6 CLI first");
|
|
22
|
+
function run(args,allowed=[0]){
|
|
23
|
+
const r=spawnSync(process.execPath,[prisma,...args],{cwd:root,env:process.env,encoding:"utf8",maxBuffer:20*1024*1024});
|
|
24
|
+
if(!allowed.includes(r.status))throw Error("Prisma command failed: "+args[0]+" "+args[1]+" (exit "+r.status+"). Validate schema/connection in staging.");
|
|
25
|
+
return {status:r.status,stdout:r.stdout||""};
|
|
26
|
+
}
|
|
27
|
+
// Refuse a plan based on a stale datamodel. Never introspect and overwrite source.
|
|
28
|
+
const drift=run(["migrate","diff","--from-schema-datasource",source,"--to-schema-datamodel",source,"--exit-code"],[0,2]);
|
|
29
|
+
if(drift.status===2)throw Error("Live staging database differs from the supplied source schema; reconcile drift before planning");
|
|
30
|
+
mkdirSync(out,{recursive:false,mode:0o700});
|
|
31
|
+
const write=(name,value)=>writeFileSync(join(out,name),value,{flag:"wx",mode:0o600});
|
|
32
|
+
const target=join(out,"target.prisma");
|
|
33
|
+
write("target.prisma",plan.schema);
|
|
34
|
+
write("source.prisma",original);
|
|
35
|
+
run(["validate","--schema",target]);
|
|
36
|
+
const sql=run(["migrate","diff","--from-schema-datamodel",source,"--to-schema-datamodel",target,"--script"]).stdout;
|
|
37
|
+
const quote=name=>provider==="mysql"?"\x60"+name+"\x60":'"'+name+'"';
|
|
38
|
+
const cleanup=[];
|
|
39
|
+
if(provider==="sqlite")for(const {table,field} of plan.normalizations){const t=quote(table),f=quote(field);cleanup.push("UPDATE "+t+" SET "+f+" = json_quote("+f+") WHERE "+f+" IS NOT NULL AND NOT json_valid("+f+");");}
|
|
40
|
+
if(plan.clearLegacyRefresh&&/\brefreshTokenHash\s+String\?/.test(original))cleanup.push("UPDATE "+quote("User")+" SET "+quote("refreshTokenHash")+" = NULL;");
|
|
41
|
+
if(plan.revokeLegacyKeys&&/^model ApiToken\s*\{/m.test(original))cleanup.push("UPDATE "+quote("ApiToken")+" SET "+quote("revokedAt")+" = CURRENT_TIMESTAMP WHERE "+quote("revokedAt")+" IS NULL;");
|
|
42
|
+
const upgrade=(cleanup.length?"-- Preserve legacy JSON semantics and invalidate obsolete credentials.\n"+cleanup.join("\n")+"\n\n":"")+sql;
|
|
43
|
+
write("upgrade.sql",upgrade);
|
|
44
|
+
const history=join(root,"prisma/migrations");
|
|
45
|
+
const hasHistory=existsSync(history)&&readdirSync(history,{withFileTypes:true}).some(e=>e.isDirectory());
|
|
46
|
+
if(!hasHistory){
|
|
47
|
+
const baseline=run(["migrate","diff","--from-empty","--to-schema-datamodel",source,"--script"]).stdout;
|
|
48
|
+
write("baseline.sql",baseline);
|
|
49
|
+
write("migration_lock.toml",'provider = "'+provider+'"\n');
|
|
50
|
+
}
|
|
51
|
+
const flags=upgrade.split("\n").filter(l=>/\bDROP\b|\bTRUNCATE\b|\bDELETE\s+FROM\b|ALTER\s+COLUMN|MODIFY\s+COLUMN|NOT NULL/i.test(l)).map(l=>l.trim()).slice(0,100);
|
|
52
|
+
// These are file integrity checksums, not credential hashes. The files contain schema/DDL, not rows.
|
|
53
|
+
const fileChecksum=name=>createHash("sha256").update(readFileSync(join(out,name))).digest("hex");
|
|
54
|
+
write("plan.json",JSON.stringify({provider,sourceSha256:fileChecksum("source.prisma"),targetSha256:fileChecksum("target.prisma"),upgradeSha256:fileChecksum("upgrade.sql"),hasMigrationHistory:hasHistory,changes:plan.changes,reviewRequired:flags},null,2)+"\n");
|
|
55
|
+
write("README.md",[
|
|
56
|
+
"# Reviewed migration plan — never apply blindly",
|
|
57
|
+
"",
|
|
58
|
+
"Generated against a staging database whose schema matched the source datamodel. Source schema and database were not modified.",
|
|
59
|
+
"Back up the database and files; stop writers. Review target.prisma, upgrade.sql and plan.json, including all table rebuilds and constraints. Check row counts, foreign keys, JSON values and legacy credential revocation after applying to a disposable copy.",
|
|
60
|
+
hasHistory?"Existing migration history detected: do not create a duplicate baseline. For PostgreSQL projects with the original OpenAdminJS history, use the unchanged shipped migrations; do not apply this equivalent SQL on top. For customized histories, add reviewed SQL as a new migration only after checking the deployed migration history.":"No local migration history: confirm the database truly has no applied migration records. Copy baseline.sql into prisma/migrations/00000000000000_existing_baseline/migration.sql, copy migration_lock.toml, then mark that baseline applied with prisma migrate resolve --applied 00000000000000_existing_baseline --schema prisma/schema.prisma. Never execute baseline.sql against the existing database. Add upgrade.sql as a new timestamped migration.",
|
|
61
|
+
"Replace schema.prisma with reviewed target.prisma, then run prisma migrate deploy and prisma generate in staging; run schema adopt to split the updated project without losing custom models.",
|
|
62
|
+
"No automatic SQL application or rollback is provided. Restore the pre-migration database + application snapshot if staging fails. MySQL DDL is not generally transactional; SQLite table rebuilds require sufficient disk space.",
|
|
63
|
+
"For SQLite legacy JSON, valid JSON text stays JSON; invalid text is converted to a JSON string. Review malformed scope values separately; obsolete API keys are revoked.",
|
|
64
|
+
].join("\n")+"\n");
|
|
65
|
+
console.log("Migration plan written to "+out+"; database unchanged. Review before applying.");
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import {existsSync,readFileSync,writeFileSync,mkdirSync,readdirSync,lstatSync,renameSync} from "node:fs";
|
|
2
|
+
import {join,resolve} from "node:path";
|
|
3
|
+
import {createHash} from "node:crypto";
|
|
4
|
+
const {composeSchema,splitSchema,moduleNames,providers,schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
|
|
5
|
+
const root=process.cwd(),schema=join(root,"prisma/schema.prisma"),dir=join(root,"prisma/modules"),manifest=join(dir,"manifest.json");
|
|
6
|
+
const [command,...args]=process.argv.slice(2);
|
|
7
|
+
const hash=text=>createHash("sha256").update(text).digest("hex");
|
|
8
|
+
const read=path=>readFileSync(path,"utf8");
|
|
9
|
+
function readLocal(path){if(lstatSync(path).isSymbolicLink())throw Error("Symbolic links not allowed in schema modules");return read(path);}
|
|
10
|
+
function providerOf(text){const p=schemaProvider(text);if(!providers.includes(p))throw Error("Unknown schema provider");return p;}
|
|
11
|
+
const current=read(schema);
|
|
12
|
+
if(command==="adopt"){
|
|
13
|
+
if(existsSync(dir))throw Error("prisma/modules already exists; refusing overwrite");
|
|
14
|
+
const chunks=splitSchema(current);
|
|
15
|
+
mkdirSync(dir,{recursive:false});
|
|
16
|
+
for(const chunk of chunks)writeFileSync(join(dir,chunk.name+".prisma"),chunk.content,{flag:"wx"});
|
|
17
|
+
writeFileSync(manifest,JSON.stringify({mode:"adopted",provider:providerOf(current),files:chunks.map(c=>c.name+".prisma"),lastSchemaHash:hash(current)},null,2)+"\n",{flag:"wx"});
|
|
18
|
+
console.log("Adopted existing schema losslessly. Database and migrations unchanged.");
|
|
19
|
+
}else if(command==="check"||command==="compose"){
|
|
20
|
+
let next,config;
|
|
21
|
+
if(existsSync(manifest)){
|
|
22
|
+
if(lstatSync(dir).isSymbolicLink())throw Error("Symlinked schema module directory");
|
|
23
|
+
config=JSON.parse(readLocal(manifest));
|
|
24
|
+
if(config.mode!=="adopted"||!Array.isArray(config.files)||new Set(config.files).size!==config.files.length)throw Error("Invalid adoption manifest");
|
|
25
|
+
for(const file of config.files)if(!/^[a-zA-Z0-9_-]+\.prisma$/.test(file))throw Error("Invalid module filename");
|
|
26
|
+
next=config.files.map(file=>readLocal(join(dir,file))).join("");
|
|
27
|
+
if(providerOf(next)!==config.provider)throw Error("Provider changes require a separate migration");
|
|
28
|
+
}else{
|
|
29
|
+
const custom=existsSync(dir)?readdirSync(dir).filter(x=>x.endsWith(".prisma")).sort().map(x=>readLocal(join(dir,x))):[];
|
|
30
|
+
next=composeSchema({provider:providerOf(current),customFragments:custom});
|
|
31
|
+
}
|
|
32
|
+
if(command==="check"){if(current!==next)throw Error("Schema drift: review modules and compose; do not edit generated schema directly");console.log("Schema matches modules");}
|
|
33
|
+
else{
|
|
34
|
+
if(!args.includes("--write")){process.stdout.write(next);process.exit(0);}
|
|
35
|
+
if(current===next){console.log("Schema already current");process.exit(0);}
|
|
36
|
+
if(config&&config.lastSchemaHash!==hash(current))throw Error("Generated schema changed since adoption; merge your edits first");
|
|
37
|
+
if(!config&&!args.includes("--replace-generated"))throw Error("Review output first; use --write --replace-generated only for a known generated schema, or adopt existing schema");
|
|
38
|
+
const backup=schema+".before-compose";
|
|
39
|
+
if(existsSync(backup))throw Error("Preserve or remove previous schema backup before composing again");
|
|
40
|
+
writeFileSync(backup,current,{flag:"wx"});
|
|
41
|
+
const temp=schema+".tmp";writeFileSync(temp,next,{flag:"wx"});renameSync(temp,schema);
|
|
42
|
+
if(config){config.lastSchemaHash=hash(next);writeFileSync(manifest,JSON.stringify(config,null,2)+"\n");}
|
|
43
|
+
console.log("Schema composed. Database unchanged; validate and create a reviewed migration.");
|
|
44
|
+
}
|
|
45
|
+
}else if(command==="profile"){
|
|
46
|
+
const provider=args[0],modules=args.slice(1);
|
|
47
|
+
process.stdout.write(composeSchema({provider,modules:modules.length?modules:moduleNames}));
|
|
48
|
+
}else throw Error("Usage: schema.mjs check | adopt | compose [--write] | profile <provider> [modules...]");
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
3
|
"target": "ES2022",
|
|
4
|
-
"lib": [
|
|
4
|
+
"lib": [
|
|
5
|
+
"ES2022",
|
|
6
|
+
"DOM",
|
|
7
|
+
"DOM.Iterable"
|
|
8
|
+
],
|
|
5
9
|
"module": "ESNext",
|
|
6
10
|
"moduleResolution": "Bundler",
|
|
7
11
|
"strict": true,
|
|
@@ -14,10 +18,24 @@
|
|
|
14
18
|
"forceConsistentCasingInFileNames": true,
|
|
15
19
|
"baseUrl": ".",
|
|
16
20
|
"paths": {
|
|
17
|
-
"@openadminjs/core": [
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"@openadminjs/
|
|
21
|
+
"@openadminjs/core": [
|
|
22
|
+
"packages/core/src/index.ts"
|
|
23
|
+
],
|
|
24
|
+
"@openadminjs/resource": [
|
|
25
|
+
"packages/resource/src/index.ts"
|
|
26
|
+
],
|
|
27
|
+
"@openadminjs/auth": [
|
|
28
|
+
"packages/auth/src/index.ts"
|
|
29
|
+
],
|
|
30
|
+
"@openadminjs/permissions": [
|
|
31
|
+
"packages/permissions/src/index.ts"
|
|
32
|
+
],
|
|
33
|
+
"@openadminjs/nest": [
|
|
34
|
+
"packages/nest/src/index.ts"
|
|
35
|
+
],
|
|
36
|
+
"@openadminjs/admin-client": [
|
|
37
|
+
"packages/admin-client/src/index.ts"
|
|
38
|
+
]
|
|
21
39
|
}
|
|
22
40
|
}
|
|
23
41
|
}
|