openadminjs 0.1.10 → 0.1.12

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 CHANGED
@@ -20,25 +20,26 @@ During scaffolding, you can choose the database driver from a list (PostgreSQL,
20
20
 
21
21
  ### 2. Configure environment
22
22
 
23
- The scaffold wizard asks for database access and key env values (`DATABASE_URL`, `REDIS_URL`, JWT secrets) and writes ready-to-use values into `apps/api/.env`.
23
+ The scaffold wizard asks for database access and key env values (`DATABASE_URL`, `REDIS_URL`, JWT secrets) and writes ready-to-use values into `apps/api/.env` (including `SUPERADMIN_EMAIL` / `SUPERADMIN_PASSWORD` for non-interactive seed).
24
24
  `ADMIN_ORIGIN` and `API_PORT` are prefilled with defaults (`http://localhost:3000` and `4000`) and can be changed manually if needed.
25
- `.env.example` is left as a reference template.
25
+ New projects do **not** include a root `.env.example` or root `.env`—use `apps/api/.env` as the source of truth (you can add your own `.env.example` for your team if you want).
26
26
 
27
- Minimal `.env` example:
27
+ Typical `apps/api/.env` keys (after create, edit as needed):
28
28
 
29
29
  ```env
30
- NODE_ENV=development
31
30
  DATABASE_URL=postgresql://USER:PASSWORD@localhost:5432/openadminjs?schema=public
32
- API_PORT=4000
31
+ REDIS_URL=redis://localhost:6379
33
32
  JWT_SECRET=replace-with-a-long-random-string-at-least-32-chars
34
33
  JWT_REFRESH_SECRET=another-long-random-string
35
34
  ADMIN_ORIGIN=http://localhost:3000
35
+ API_PORT=4000
36
+ SUPERADMIN_EMAIL=admin@localhost.dev
37
+ SUPERADMIN_PASSWORD=your-secure-password
36
38
  ```
37
39
 
38
- Optional:
40
+ Optional (elsewhere / advanced):
39
41
 
40
42
  ```env
41
- REDIS_URL=redis://localhost:6379
42
43
  OPENADMIN_PLUGIN_PNPM_INSTALL=0
43
44
  ```
44
45
 
@@ -102,9 +103,9 @@ Generate a starter plugin:
102
103
  pnpm exec openadminjs generate plugin com.example.my-plugin
103
104
  ```
104
105
 
105
- ### Optional queue setup
106
+ ### Queue setup
106
107
 
107
- Set `REDIS_URL` in your environment to enable queue processing (example: `redis://localhost:6379`).
108
+ Set `REDIS_URL` in your environment to run queue processing (example: `redis://localhost:6379`).
108
109
 
109
110
  ## Partners
110
111
 
@@ -26,6 +26,7 @@ export type CreateProjectResult = {
26
26
  superadminEmail: string;
27
27
  git: boolean;
28
28
  install: boolean;
29
+ dbInitialized: boolean;
29
30
  };
30
31
  export declare function toPackageName(input: string): string;
31
32
  export declare function defaultTemplateDir(): string;
@@ -1,4 +1,5 @@
1
1
  import { existsSync, mkdirSync, readdirSync } from "node:fs";
2
+ import net from "node:net";
2
3
  import { dirname, extname, join, relative, resolve, sep } from "node:path";
3
4
  import { spawnSync } from "node:child_process";
4
5
  import { fileURLToPath } from "node:url";
@@ -19,6 +20,92 @@ export function toPackageName(input) {
19
20
  export function defaultTemplateDir() {
20
21
  return resolve(__dirname, "../template");
21
22
  }
23
+ function parseUrlHostPort(input) {
24
+ try {
25
+ const url = new URL(input);
26
+ if (!url.hostname)
27
+ return undefined;
28
+ const port = url.port ? Number(url.port) : undefined;
29
+ if (port !== undefined && (!Number.isFinite(port) || port <= 0))
30
+ return undefined;
31
+ return { host: url.hostname, port: port ?? 0 };
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ async function checkTcpConnection(host, port, timeoutMs = 1500) {
38
+ await new Promise((resolve, reject) => {
39
+ const socket = net.createConnection({ host, port });
40
+ const onError = (err) => {
41
+ socket.destroy();
42
+ reject(err);
43
+ };
44
+ socket.setTimeout(timeoutMs, () => onError(new Error("timeout")));
45
+ socket.once("error", onError);
46
+ socket.once("connect", () => {
47
+ socket.end();
48
+ resolve();
49
+ });
50
+ });
51
+ }
52
+ async function pingRedis(urlInput, timeoutMs = 1500) {
53
+ const parsed = parseUrlHostPort(urlInput);
54
+ if (!parsed)
55
+ throw new Error("Invalid Redis URL");
56
+ const port = parsed.port || 6379;
57
+ await new Promise((resolve, reject) => {
58
+ const socket = net.createConnection({ host: parsed.host, port });
59
+ const onError = (err) => {
60
+ socket.destroy();
61
+ reject(err);
62
+ };
63
+ socket.setTimeout(timeoutMs, () => onError(new Error("timeout")));
64
+ socket.once("error", onError);
65
+ socket.once("connect", () => {
66
+ socket.write("*1\r\n$4\r\nPING\r\n");
67
+ });
68
+ let buffer = "";
69
+ socket.on("data", (chunk) => {
70
+ buffer += chunk.toString("utf8");
71
+ if (buffer.includes("+PONG")) {
72
+ socket.end();
73
+ resolve();
74
+ }
75
+ if (buffer.includes("-ERR")) {
76
+ onError(new Error("redis error"));
77
+ }
78
+ });
79
+ });
80
+ }
81
+ async function validateDbConnectivity(database, databaseUrlInput) {
82
+ if (database === "sqlite")
83
+ return undefined;
84
+ const parsed = parseUrlHostPort(databaseUrlInput);
85
+ if (!parsed)
86
+ return "Invalid database URL.";
87
+ const port = parsed.port || (database === "postgresql" ? 5432 : 3306);
88
+ try {
89
+ await checkTcpConnection(parsed.host, port);
90
+ return undefined;
91
+ }
92
+ catch {
93
+ return `Cannot connect to ${parsed.host}:${port}.`;
94
+ }
95
+ }
96
+ async function validateRedisConnectivity(redisUrlInput) {
97
+ try {
98
+ await pingRedis(redisUrlInput);
99
+ return undefined;
100
+ }
101
+ catch {
102
+ const parsed = parseUrlHostPort(redisUrlInput);
103
+ if (!parsed)
104
+ return "Invalid Redis URL.";
105
+ const port = parsed.port || 6379;
106
+ return `Cannot connect to Redis at ${parsed.host}:${port}.`;
107
+ }
108
+ }
22
109
  function databaseUrl(packageName, database) {
23
110
  if (database === "postgresql") {
24
111
  return `postgresql://openadminjs:openadminjs@localhost:5432/${packageName}?schema=public`;
@@ -51,6 +138,15 @@ function renderTemplateFiles(targetDir, replacements) {
51
138
  }
52
139
  }
53
140
  }
141
+ function runPackageManagerScript(packageManager, script, cwd) {
142
+ const command = packageManager === "npm" ? "npm" : packageManager;
143
+ const args = packageManager === "npm" ? ["run", script] : [script];
144
+ const result = spawnSync(command, args, { cwd, stdio: "inherit" });
145
+ if (result.status !== 0 || result.error) {
146
+ const displayCommand = packageManager === "npm" ? `npm run ${script}` : `${packageManager} ${script}`;
147
+ throw new Error(`Failed to run "${displayCommand}" in ${cwd}.`);
148
+ }
149
+ }
54
150
  export function createProject(options) {
55
151
  const appName = options.projectName;
56
152
  const packageName = toPackageName(appName);
@@ -65,7 +161,7 @@ export function createProject(options) {
65
161
  errorOnExist: true,
66
162
  filter: (source) => {
67
163
  const segments = relative(options.templateDir, source).split(sep);
68
- return !segments.some((segment) => segment === "node_modules" || segment === ".next" || segment === "dist");
164
+ return !segments.some((segment) => segment === "node_modules" || segment === ".next" || segment === "dist" || segment === ".env.example");
69
165
  }
70
166
  });
71
167
  if (!existsSync(join(targetDir, "package.json"))) {
@@ -111,6 +207,8 @@ export function createProject(options) {
111
207
  if (installResult.status !== 0 || installResult.error) {
112
208
  throw new Error(`Dependency installation failed. Run "${options.packageManager} ${installArgs.join(" ")}" inside ${targetDir}.`);
113
209
  }
210
+ runPackageManagerScript(options.packageManager, "db:migrate", targetDir);
211
+ runPackageManagerScript(options.packageManager, "db:seed", targetDir);
114
212
  }
115
213
  return {
116
214
  appName,
@@ -120,13 +218,15 @@ export function createProject(options) {
120
218
  database: options.database,
121
219
  superadminEmail: options.superadminEmail,
122
220
  git: options.git,
123
- install: options.install
221
+ install: options.install,
222
+ dbInitialized: options.install
124
223
  };
125
224
  }
126
225
  export function printNextSteps(result) {
127
226
  const pm = result.packageManager;
128
- const installStep = result.install ? "" : `\n ${pm} install`;
129
- outro(`${pc.green("Project created.")}\n\nNext steps:\n cd ${result.appName}${installStep}\n ${pm} db:migrate\n ${pm} db:seed\n ${pm} dev\n\nAdmin: http://localhost:3000\nAPI: http://localhost:4000\nSwagger: http://localhost:4000/api/docs\nWeb: http://localhost:3001\n\nSuperadmin: ${result.superadminEmail} / <your password>`);
227
+ const installStep = result.install ? "" : `\n ${pm} install\n ${pm} db:migrate\n ${pm} db:seed`;
228
+ const dbStepNote = result.dbInitialized ? "\nDatabase initialized: migrations + seed completed automatically." : "";
229
+ outro(`${pc.green("Project created.")}\n\nNext steps:\n cd ${result.appName}${installStep}\n ${pm} dev${dbStepNote}\n\nAdmin: http://localhost:3000\nAPI: http://localhost:4000\nSwagger: http://localhost:4000/api/docs\nWeb: http://localhost:3001\n\nSuperadmin: ${result.superadminEmail} / <your password>`);
130
230
  }
131
231
  export async function createProjectInteractive(options = {}) {
132
232
  intro(pc.green("Create OpenAdminJS"));
@@ -202,14 +302,70 @@ export async function createProjectInteractive(options = {}) {
202
302
  cancel("Cancelled");
203
303
  return undefined;
204
304
  }
205
- const redisUrl = options.redisUrl ??
206
- (await text({
207
- message: "Redis URL (optional for queues)",
208
- defaultValue: "redis://localhost:6379"
209
- }));
210
- if (isCancel(redisUrl)) {
211
- cancel("Cancelled");
212
- return undefined;
305
+ let checkedDatabaseUrl = String(selectedDatabaseUrl).trim();
306
+ while (true) {
307
+ const dbError = await validateDbConnectivity(database, checkedDatabaseUrl);
308
+ if (!dbError)
309
+ break;
310
+ const retry = await confirm({
311
+ message: `${dbError} Retry entering DATABASE_URL?`,
312
+ initialValue: true
313
+ });
314
+ if (isCancel(retry)) {
315
+ cancel("Cancelled");
316
+ return undefined;
317
+ }
318
+ if (!retry)
319
+ break;
320
+ const next = await text({
321
+ message: "Database URL",
322
+ defaultValue: checkedDatabaseUrl
323
+ });
324
+ if (isCancel(next)) {
325
+ cancel("Cancelled");
326
+ return undefined;
327
+ }
328
+ checkedDatabaseUrl = String(next).trim();
329
+ }
330
+ let checkedRedisUrl = (options.redisUrl ?? "").trim();
331
+ while (!checkedRedisUrl) {
332
+ const entered = options.redisUrl ??
333
+ (await text({
334
+ message: "Redis URL",
335
+ defaultValue: "redis://localhost:6379",
336
+ validate(value) {
337
+ return value.trim().length > 0 ? undefined : "Redis URL is required.";
338
+ }
339
+ }));
340
+ if (isCancel(entered)) {
341
+ cancel("Cancelled");
342
+ return undefined;
343
+ }
344
+ checkedRedisUrl = String(entered).trim();
345
+ }
346
+ while (true) {
347
+ const redisError = await validateRedisConnectivity(checkedRedisUrl);
348
+ if (!redisError)
349
+ break;
350
+ const retry = await confirm({
351
+ message: `${redisError} Retry entering REDIS_URL?`,
352
+ initialValue: true
353
+ });
354
+ if (isCancel(retry)) {
355
+ cancel("Cancelled");
356
+ return undefined;
357
+ }
358
+ if (!retry)
359
+ break;
360
+ const next = await text({
361
+ message: "Redis URL",
362
+ defaultValue: checkedRedisUrl
363
+ });
364
+ if (isCancel(next)) {
365
+ cancel("Cancelled");
366
+ return undefined;
367
+ }
368
+ checkedRedisUrl = String(next).trim();
213
369
  }
214
370
  const jwtSecret = options.jwtSecret ??
215
371
  (await text({
@@ -246,8 +402,8 @@ export async function createProjectInteractive(options = {}) {
246
402
  database,
247
403
  superadminEmail: String(superadminEmail),
248
404
  superadminPassword: String(superadminPassword),
249
- databaseUrl: String(selectedDatabaseUrl),
250
- redisUrl: String(redisUrl),
405
+ databaseUrl: checkedDatabaseUrl,
406
+ redisUrl: checkedRedisUrl,
251
407
  jwtSecret: String(jwtSecret),
252
408
  jwtRefreshSecret: String(jwtRefreshSecret),
253
409
  adminOrigin: String(adminOrigin),
@@ -24,17 +24,13 @@ describe("create project", () => {
24
24
  expect(envExample, `missing placeholder ${key}`).toContain(key);
25
25
  }
26
26
  });
27
- it("creates project with rendered .env.example values", () => {
27
+ it("does not scaffold root .env.example or .env files", () => {
28
28
  const cwd = mkdtempSync(join(tmpdir(), "openadminjs-cli-test-"));
29
29
  try {
30
30
  const result = createProject({ ...BASE_OPTIONS, projectName: "my-app", cwd, templateDir: defaultTemplateDir() });
31
- const envExample = readFileSync(join(result.targetDir, ".env.example"), "utf8");
32
- expect(envExample).toContain("DATABASE_URL=postgresql://localhost:5432/my-app?schema=public");
33
- expect(envExample).toContain("REDIS_URL=redis://localhost:6379");
34
- expect(envExample).toContain("JWT_SECRET=test-jwt-secret");
35
- expect(envExample).toContain("JWT_REFRESH_SECRET=test-jwt-refresh-secret");
36
- expect(envExample).toContain("ADMIN_ORIGIN=http://localhost:3000");
37
- expect(envExample).toContain("API_PORT=4000");
31
+ expect(existsSync(join(result.targetDir, ".env.example"))).toBe(false);
32
+ expect(existsSync(join(result.targetDir, ".env"))).toBe(false);
33
+ expect(existsSync(join(result.targetDir, "tsconfig.base.json"))).toBe(true);
38
34
  }
39
35
  finally {
40
36
  rmSync(cwd, { recursive: true, force: true });
package/dist/index.js CHANGED
@@ -26,8 +26,13 @@ function runScript(name) {
26
26
  }
27
27
  }
28
28
  function doctor() {
29
- const required = ["package.json", "pnpm-workspace.yaml", ".env.example", "prisma/schema.prisma"];
30
- const missing = required.filter((file) => !existsSync(join(process.cwd(), file)));
29
+ const cwd = process.cwd();
30
+ const required = ["package.json", "pnpm-workspace.yaml", "prisma/schema.prisma"];
31
+ const missing = required.filter((file) => !existsSync(join(cwd, file)));
32
+ const hasEnvSample = existsSync(join(cwd, ".env.example")) || existsSync(join(cwd, "apps", "api", ".env"));
33
+ if (!hasEnvSample) {
34
+ missing.push("apps/api/.env (or .env.example at repo root)");
35
+ }
31
36
  if (missing.length) {
32
37
  console.error(pc.red("OpenAdminJS doctor found missing files:"));
33
38
  for (const file of missing)
@@ -38,11 +43,20 @@ function doctor() {
38
43
  console.log(pc.green("OpenAdminJS doctor passed."));
39
44
  }
40
45
  function securityCheck() {
41
- const envExample = existsSync(".env.example") ? readFileSync(".env.example", "utf8") : "";
46
+ const cwd = process.cwd();
47
+ const envSample = existsSync(join(cwd, ".env.example"))
48
+ ? readFileSync(join(cwd, ".env.example"), "utf8")
49
+ : existsSync(join(cwd, "apps", "api", ".env"))
50
+ ? readFileSync(join(cwd, "apps", "api", ".env"), "utf8")
51
+ : "";
42
52
  const findings = [];
43
- if (!envExample.includes("JWT_SECRET"))
44
- findings.push("JWT_SECRET is missing from .env.example");
45
- if (envExample.includes("DATABASE_URL=postgresql://") && !envExample.includes("localhost")) {
53
+ if (!envSample) {
54
+ findings.push("No .env.example or apps/api/.env found for security checklist");
55
+ }
56
+ else if (!envSample.includes("JWT_SECRET")) {
57
+ findings.push("JWT_SECRET is missing from env sample (.env.example or apps/api/.env)");
58
+ }
59
+ if (envSample.includes("DATABASE_URL=postgresql://") && !envSample.includes("localhost")) {
46
60
  findings.push("DATABASE_URL example should not point to production");
47
61
  }
48
62
  if (existsSync("apps/admin/app")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openadminjs",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "openadminjs": "dist/index.js"
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "scripts": {
29
29
  "sync-template": "node ../../scripts/sync-template.mjs",
30
- "prepack": "node ../../scripts/sync-template.mjs",
30
+ "prepack": "pnpm run build",
31
31
  "build": "node ../../scripts/sync-template.mjs && tsc -p tsconfig.json && node ../../scripts/make-executable.mjs dist/index.js",
32
32
  "lint": "tsc -p tsconfig.json --noEmit",
33
33
  "typecheck": "tsc -p tsconfig.json --noEmit",
@@ -90,7 +90,7 @@ export class AdminPluginsService {
90
90
  enabled?: boolean;
91
91
  config?: Record<string, unknown>;
92
92
  trustMode?: "trusted" | "sandboxed";
93
- capabilities?: string[];
93
+ capabilities?: PluginManifestEntry["capabilities"];
94
94
  runPnpmInstall?: boolean;
95
95
  }) {
96
96
  const hasBundled = Boolean(dto.bundled);
@@ -156,7 +156,15 @@ export class AdminPluginsService {
156
156
  };
157
157
  }
158
158
 
159
- async patch(id: string, dto: { enabled?: boolean; config?: Record<string, unknown>; trustMode?: "trusted" | "sandboxed"; capabilities?: string[] }) {
159
+ async patch(
160
+ id: string,
161
+ dto: {
162
+ enabled?: boolean;
163
+ config?: Record<string, unknown>;
164
+ trustMode?: "trusted" | "sandboxed";
165
+ capabilities?: PluginManifestEntry["capabilities"];
166
+ }
167
+ ) {
160
168
  const manifest = this.readManifestOrEmpty();
161
169
  const idx = manifest.plugins.findIndex((p) => p.id === id);
162
170
  if (idx === -1) {
@@ -1,5 +1,19 @@
1
1
  import { IsArray, IsBoolean, IsIn, IsObject, IsOptional, IsString } from "class-validator";
2
2
 
3
+ const PLUGIN_CAPABILITIES = [
4
+ "db.read",
5
+ "db.write",
6
+ "resource.hooks",
7
+ "api.hooks",
8
+ "api.routes",
9
+ "media.pipeline",
10
+ "seo.extend",
11
+ "jobs.run",
12
+ "admin.ui.extend"
13
+ ] as const;
14
+
15
+ type PluginCapability = (typeof PLUGIN_CAPABILITIES)[number];
16
+
3
17
  export class AddPluginDto {
4
18
  @IsString()
5
19
  id!: string;
@@ -26,8 +40,8 @@ export class AddPluginDto {
26
40
 
27
41
  @IsOptional()
28
42
  @IsArray()
29
- @IsString({ each: true })
30
- capabilities?: string[];
43
+ @IsIn(PLUGIN_CAPABILITIES, { each: true })
44
+ capabilities?: PluginCapability[];
31
45
 
32
46
  /** When true and `package` is set, runs `pnpm add <package> --filter @openadminjs/api` (dev / non-production only). */
33
47
  @IsOptional()
@@ -50,6 +64,6 @@ export class PatchPluginDto {
50
64
 
51
65
  @IsOptional()
52
66
  @IsArray()
53
- @IsString({ each: true })
54
- capabilities?: string[];
67
+ @IsIn(PLUGIN_CAPABILITIES, { each: true })
68
+ capabilities?: PluginCapability[];
55
69
  }
@@ -3,12 +3,13 @@ import { ConfigModule, ConfigService } from "@nestjs/config";
3
3
  import { JwtModule } from "@nestjs/jwt";
4
4
  import { AuthGuard } from "../common/auth.guard";
5
5
  import { PrismaService } from "../common/prisma.service";
6
- import { MailService } from "../mail/mail.service";
6
+ import { MailModule } from "../mail/mail.module";
7
7
  import { AuthController } from "./auth.controller";
8
8
  import { AuthService } from "./auth.service";
9
9
 
10
10
  @Module({
11
11
  imports: [
12
+ MailModule,
12
13
  JwtModule.registerAsync({
13
14
  imports: [ConfigModule],
14
15
  inject: [ConfigService],
@@ -24,7 +25,7 @@ import { AuthService } from "./auth.service";
24
25
  })
25
26
  ],
26
27
  controllers: [AuthController],
27
- providers: [AuthService, PrismaService, AuthGuard, MailService],
28
+ providers: [AuthService, PrismaService, AuthGuard],
28
29
  exports: [AuthService, AuthGuard]
29
30
  })
30
31
  export class AuthModule {}