@colveor/create-admin 0.5.2 → 0.5.3

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 ADDED
@@ -0,0 +1,184 @@
1
+ # @colveor/create-admin
2
+
3
+ Creates the admin panel for an API built on **colveor-go**: a Next.js app
4
+ with sign-in, user and role management, settings, the audit log and the
5
+ rest of the framework's admin pages, ready to run, plus a place for your
6
+ own pages.
7
+
8
+ ```sh
9
+ npm create @colveor/admin@latest my-admin
10
+ cd my-admin
11
+ cp .env.example .env.local # set COLVEOR_API_URL
12
+ npm run dev # http://localhost:3000
13
+ ```
14
+
15
+ You need Node 20 or later and a running colveor-go API. Go is not needed:
16
+ the panel is a plain Node project, so a frontend team can own it.
17
+
18
+ ## What the command does
19
+
20
+ 1. Copies the template into `my-admin`. It stops if the folder exists and
21
+ isn't empty.
22
+ 2. Names the app after the folder: `acme` becomes `acme` in
23
+ `package.json` and "Acme Admin" in `admin.config.ts` and the README.
24
+ Change the name in `admin.config.ts`.
25
+ 3. Installs [`@colveor/admin`](https://www.npmjs.com/package/@colveor/admin)
26
+ at this command's release line (`~0.5.2` for create-admin 0.5.2), with
27
+ Next, React and Tailwind.
28
+ 4. Prints the next steps.
29
+
30
+ Options, after `--`:
31
+
32
+ | Option | What it does |
33
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
34
+ | `--no-install` | Copy and name only; run `npm install` yourself. |
35
+ | `--admin <path>` | Install a local `@colveor/admin` (a tarball from `npm pack`) instead of the published one. For testing a colveor-go change before it is released. |
36
+
37
+ ```sh
38
+ npm create @colveor/admin@latest my-admin -- --no-install
39
+ ```
40
+
41
+ ## Setting it up
42
+
43
+ **`.env.local`**
44
+
45
+ | Variable | |
46
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------- |
47
+ | `COLVEOR_API_URL` | The colveor-go API, such as `http://localhost:8080`. Read by the panel's server only; the browser never calls the API directly. |
48
+
49
+ **On the API**, add the panel server's address to `SERVER_TRUSTED_PROXIES`.
50
+ Every call reaches the API from the panel server, so without it every admin
51
+ shares one IP: one admin's failed sign-ins can then lock out the others,
52
+ and the audit log shows the server's IP instead of the admin's.
53
+
54
+ **Signing in:** any user of the API who holds an admin permission can sign
55
+ in. Pages are shown only to users holding their permission, so give your
56
+ admins a role with the permissions they need (the Roles page, once a super
57
+ admin is in).
58
+
59
+ ## What you get
60
+
61
+ ```
62
+ my-admin/
63
+ ├── admin.config.ts # the panel's name, logo and your menu items
64
+ ├── app/
65
+ │ ├── (admin)/ # every page inside the menu and header
66
+ │ │ ├── page.tsx # the home page
67
+ │ │ ├── account/ # the signed-in admin's own account
68
+ │ │ ├── (colveor)/ # the framework's pages: one-line re-exports
69
+ │ │ └── (project)/ # your pages
70
+ │ ├── api/colveor/[...path]/route.ts # the proxy to the API
71
+ │ ├── login/, forgot-password/ # sign-in pages
72
+ │ ├── layout.tsx # <html>, the font, globals.css
73
+ │ ├── providers.tsx # light and dark mode, and the admin shell
74
+ │ └── globals.css # the theme (brand colours, animations)
75
+ ├── instrumentation.ts # the banner at server start (remove for a quiet start)
76
+ ├── components/
77
+ │ ├── frame.tsx # the menu and header
78
+ │ └── theme.tsx # light and dark mode
79
+ └── .env.example
80
+ ```
81
+
82
+ The framework's pages: Users, Roles, Teams, Support access, Settings,
83
+ Audit log, Webhook events, System status and Ledger, with sign-in (password
84
+ or emailed code, then two-step verification), forgot password, and the
85
+ admin's own account (profile, password, two-step, devices, their data). A
86
+ page for an API module that is off is hidden.
87
+
88
+ ### Yours to change
89
+
90
+ Everything copied into your project is yours: the layout, `frame.tsx`
91
+ (menu and header), the theme in `globals.css`, the font, the home page and
92
+ `admin.config.ts`. These never get framework updates, so change them
93
+ freely.
94
+
95
+ ### Updated for you
96
+
97
+ Each file in `app/(admin)/(colveor)/` holds one line:
98
+
99
+ ```ts
100
+ export { default } from "@colveor/admin/pages/users";
101
+ ```
102
+
103
+ So `npm update @colveor/admin` brings fixes and new features to those
104
+ pages without touching your code. To replace one of our pages, replace that
105
+ one file.
106
+
107
+ ## Adding your own page
108
+
109
+ 1. Add `app/(admin)/(project)/invoices/page.tsx`, a normal Next page built
110
+ with `@colveor/admin`'s pieces, so it looks and behaves like ours:
111
+
112
+ ```tsx
113
+ "use client";
114
+
115
+ import { DataTable, PageHeader, RequirePermission, formatDate } from "@colveor/admin";
116
+
117
+ type Invoice = { id: string; number: string; total: number; created_at: string };
118
+
119
+ export default function InvoicesPage() {
120
+ return (
121
+ <RequirePermission keys={["invoices.read"]}>
122
+ <PageHeader title="Invoices" />
123
+ <DataTable<Invoice>
124
+ title="Invoices"
125
+ path="/v1/invoices"
126
+ download="invoices"
127
+ columns={[
128
+ { header: "Number", cell: (i) => i.number },
129
+ { header: "Total", cell: (i) => i.total },
130
+ { header: "Date", cell: (i) => formatDate(i.created_at) },
131
+ ]}
132
+ />
133
+ </RequirePermission>
134
+ );
135
+ }
136
+ ```
137
+
138
+ 2. Add it to the menu in `admin.config.ts`:
139
+
140
+ ```ts
141
+ export default defineConfig({
142
+ name: "Acme Admin",
143
+ logo: "/logo.svg",
144
+ nav: [
145
+ { label: "Invoices", href: "/invoices", permission: "invoices.read", group: "Sales" },
146
+ ],
147
+ });
148
+ ```
149
+
150
+ An item is shown only to admins holding its permission.
151
+
152
+ See [`@colveor/admin`](https://www.npmjs.com/package/@colveor/admin) for
153
+ every building block: the API client, tables, cards, dialogs, actions that
154
+ ask for a reason or re-authentication, and the generated API types.
155
+
156
+ ## Updating
157
+
158
+ ```sh
159
+ npm update @colveor/admin
160
+ ```
161
+
162
+ The panel follows colveor-go's versions: `@colveor/admin` 0.5.x works with
163
+ a colveor-go 0.5.x API. The System status page warns when they don't match.
164
+ To move to a new minor, install it with the API's version
165
+ (`npm install @colveor/admin@~0.6.0`) and read the changelog's **Breaking**
166
+ section for changes to your own pages.
167
+
168
+ ## Running in production
169
+
170
+ ```sh
171
+ npm run build
172
+ npm start
173
+ ```
174
+
175
+ Run **one** panel server, or route each admin's session to the same one.
176
+ The proxy keeps the API's tokens in `httpOnly` cookies and refreshes them
177
+ in the server's memory. A refresh token works once, so two servers
178
+ refreshing the same session would sign the admin out.
179
+
180
+ ## License
181
+
182
+ Proprietary: see `LICENSE.md`. The template's look comes from TailAdmin
183
+ and TailwindAdmin, both MIT (`TAILADMIN-LICENSE`, `TAILWINDADMIN-LICENSE`
184
+ in the created project).
package/index.js CHANGED
@@ -11,6 +11,7 @@ import { spawnSync } from "node:child_process";
11
11
  import { cpSync, existsSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12
12
  import { basename, dirname, join, relative, resolve } from "node:path";
13
13
  import { fileURLToPath } from "node:url";
14
+ import { accent, banner, bold, cyan, dim, step } from "./look.js";
14
15
 
15
16
  const here = dirname(fileURLToPath(import.meta.url));
16
17
  const { version } = JSON.parse(readFileSync(join(here, "package.json"), "utf8"));
@@ -25,15 +26,17 @@ const noInstall = flag("--no-install") !== undefined;
25
26
  const [target] = args;
26
27
 
27
28
  if (target === undefined || target.startsWith("-") || args.length > 1) {
28
- console.error("usage: npm create @colveor/admin <dir> [-- --admin <path>] [--no-install]");
29
+ step.fail(`usage: npm create @colveor/admin ${cyan("<dir>")} [-- --admin <path>] [--no-install]`);
29
30
  process.exit(2);
30
31
  }
31
32
  const dir = resolve(target);
32
33
  if (existsSync(dir) && readdirSync(dir).length > 0) {
33
- console.error(`${target} exists and is not empty`);
34
+ step.fail(`${bold(target)} exists and is not empty: choose a new folder`);
34
35
  process.exit(1);
35
36
  }
36
37
 
38
+ console.log(`\n ${accent("◆")} ${bold("Creating a Colveor admin panel")} in ${cyan(target)}\n`);
39
+
37
40
  cpSync(join(here, "template"), dir, { recursive: true });
38
41
  // npm leaves these out of a published package under their real names.
39
42
  renameSync(join(dir, "gitignore"), join(dir, ".gitignore"));
@@ -60,18 +63,43 @@ for (const file of ["package.json", "admin.config.ts", "README.md"]) {
60
63
  );
61
64
  }
62
65
 
63
- if (!noInstall) {
66
+ step.done("Copied the template");
67
+ step.done(`Named it ${bold(`${title} Admin`)} ${dim("(admin.config.ts)")}`);
68
+
69
+ if (noInstall) {
70
+ step.done(`Left the install to you ${dim("(--no-install)")}`);
71
+ } else {
72
+ step.work(`Installing ${bold("@colveor/admin")} ${dim(admin)}, Next and React…\n`);
64
73
  const npm = process.platform === "win32" ? "npm.cmd" : "npm";
65
74
  const res = spawnSync(npm, ["install"], { cwd: dir, stdio: "inherit" });
66
75
  if (res.status !== 0) {
67
- console.error("npm install failed: run it again in the new folder");
76
+ step.fail(`npm install failed: run it again in ${bold(target)}`);
68
77
  process.exit(1);
69
78
  }
79
+ console.log();
80
+ step.done("Installed");
70
81
  }
71
82
 
72
- console.log(`
73
- Created ${target}. Next:
74
- cd ${target}
75
- cp .env.example .env.local # COLVEOR_API_URL: the API
76
- npm run dev
77
- `);
83
+ // The next commands, their notes lined up in a column.
84
+ const next = [
85
+ [`cd ${target}`, ""],
86
+ ...(noInstall ? [["npm install", ""]] : []),
87
+ ["cp .env.example .env.local", "set COLVEOR_API_URL"],
88
+ ["npm run dev", "http://localhost:3000"],
89
+ ];
90
+ const column = Math.max(...next.filter(([, n]) => n).map(([c]) => c.length)) + 2;
91
+ console.log(banner(version));
92
+ console.log(` ${bold("Ready.")} Next:\n`);
93
+ console.log(
94
+ next
95
+ .map(
96
+ ([cmd, note]) => ` ${accent("$")} ${note ? cmd.padEnd(column) + dim(`# ${note}`) : cmd}`,
97
+ )
98
+ .join("\n"),
99
+ );
100
+ console.log(
101
+ `\n ${dim("Your pages go in")} app/(admin)/(project)/${dim(", your menu in")} admin.config.ts${dim(".")}`,
102
+ );
103
+ console.log(
104
+ ` ${dim("Docs:")} README.md ${dim("·")} ${cyan("npmjs.com/package/@colveor/admin")}\n`,
105
+ );
package/look.js ADDED
@@ -0,0 +1,68 @@
1
+ // The command's look in the terminal: colours, step lines and the
2
+ // COLVEOR banner, in the panel's brand colours (the template's brand-500,
3
+ // #465FFF, into violet). No dependency: ANSI codes, off for NO_COLOR, a
4
+ // pipe or a CI log, and 16 colours where a terminal has no true colour.
5
+
6
+ const out = process.stdout;
7
+ const colour =
8
+ !("NO_COLOR" in process.env) &&
9
+ (("FORCE_COLOR" in process.env && process.env.FORCE_COLOR !== "0") ||
10
+ (out.isTTY === true && process.env.TERM !== "dumb"));
11
+ const truecolour = colour && /truecolor|24bit/i.test(process.env.COLORTERM ?? "");
12
+
13
+ const sgr = (open, close) => (s) => (colour ? `\x1b[${open}m${s}\x1b[${close}m` : s);
14
+
15
+ export const bold = sgr("1", "22");
16
+ export const dim = sgr("2", "22");
17
+ export const green = sgr("32", "39");
18
+ export const red = sgr("31", "39");
19
+ export const cyan = sgr("36", "39");
20
+
21
+ const BLUE = [70, 95, 255]; // brand-500
22
+ const VIOLET = [158, 119, 237];
23
+
24
+ /** The brand colour at t (0: blue, 1: violet). */
25
+ function brand(t, s) {
26
+ if (!colour) {
27
+ return s;
28
+ }
29
+ if (!truecolour) {
30
+ return `\x1b[${t < 0.5 ? 94 : 95}m${s}\x1b[39m`;
31
+ }
32
+ const [r, g, b] = BLUE.map((c, i) => Math.round(c + (VIOLET[i] - c) * t));
33
+ return `\x1b[38;2;${r};${g};${b}m${s}\x1b[39m`;
34
+ }
35
+
36
+ export const accent = (s) => brand(0, s);
37
+
38
+ /** A step: done (✔), working (◇), or failed (✖). */
39
+ export const step = {
40
+ done: (s) => console.log(` ${green("✔")} ${s}`),
41
+ work: (s) => console.log(` ${accent("◇")} ${s}`),
42
+ fail: (s) => console.error(` ${red("✖")} ${s}`),
43
+ };
44
+
45
+ // "ANSI Shadow", one letter at a time.
46
+ const LETTERS = {
47
+ C: [" ██████╗", "██╔════╝", "██║ ", "██║ ", "╚██████╗", " ╚═════╝"],
48
+ O: [" ██████╗ ", "██╔═══██╗", "██║ ██║", "██║ ██║", "╚██████╔╝", " ╚═════╝ "],
49
+ L: ["██╗ ", "██║ ", "██║ ", "██║ ", "███████╗", "╚══════╝"],
50
+ V: ["██╗ ██╗", "██║ ██║", "██║ ██║", "╚██╗ ██╔╝", " ╚████╔╝ ", " ╚═══╝ "],
51
+ E: ["███████╗", "██╔════╝", "█████╗ ", "██╔══╝ ", "███████╗", "╚══════╝"],
52
+ R: ["██████╗ ", "██╔══██╗", "██████╔╝", "██╔══██╗", "██║ ██║", "╚═╝ ╚═╝"],
53
+ };
54
+
55
+ /** COLVEOR in the brand gradient, with ADMIN and the version under it. */
56
+ export function banner(version) {
57
+ const rows = [0, 1, 2, 3, 4, 5].map((r) => [..."COLVEOR"].map((ch) => LETTERS[ch][r]).join(""));
58
+ const width = rows[0].length;
59
+ const lines = rows.map(
60
+ (row) =>
61
+ ` ${[...row].map((ch, i) => (ch === " " ? ch : brand(i / (width - 1), ch))).join("")}`,
62
+ );
63
+ const label = "A D M I N";
64
+ const tag = `v${version}`;
65
+ const gap = " ".repeat(Math.max(1, width - label.length - tag.length));
66
+ lines.push(` ${bold(brand(1, label))}${gap}${dim(tag)}`);
67
+ return `\n${lines.join("\n")}\n`;
68
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colveor/create-admin",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "Creates an admin panel for an app built on colveor-go.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "type": "module",
@@ -9,6 +9,7 @@
9
9
  },
10
10
  "files": [
11
11
  "index.js",
12
+ "look.js",
12
13
  "template",
13
14
  "LICENSE.md"
14
15
  ],
@@ -0,0 +1,9 @@
1
+ // Runs once as the panel's server starts (npm run dev, npm start): the
2
+ // COLVEOR ADMIN banner, with the API it talks to. Remove it for a quiet
3
+ // start.
4
+ export async function register() {
5
+ if (process.env.NEXT_RUNTIME === "nodejs") {
6
+ const { printBanner } = await import("@colveor/admin/banner");
7
+ printBanner();
8
+ }
9
+ }