create-erxes 0.0.0-stage → 0.1.0
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 +23 -2
- package/dist/index.js +481 -0
- package/dist/templates/base/.agents/skills/endpoint/SKILL.md +21 -0
- package/dist/templates/base/.agents/skills/schema-change/SKILL.md +28 -0
- package/dist/templates/base/.agents/skills/verify/SKILL.md +24 -0
- package/dist/templates/base/.github/workflows/ci.yml +44 -0
- package/dist/templates/base/AGENTS.md +60 -0
- package/dist/templates/base/CLAUDE.md +1 -0
- package/dist/templates/base/Dockerfile +13 -0
- package/dist/templates/base/_dockerignore +4 -0
- package/dist/templates/base/_env.example +15 -0
- package/dist/templates/base/_gitignore +11 -0
- package/dist/templates/base/_node-version +1 -0
- package/dist/templates/base/api/AGENTS.md +22 -0
- package/dist/templates/base/api/drizzle/0000_items.sql +13 -0
- package/dist/templates/base/api/drizzle/meta/0000_snapshot.json +126 -0
- package/dist/templates/base/api/drizzle/meta/_journal.json +13 -0
- package/dist/templates/base/api/drizzle.config.ts +16 -0
- package/dist/templates/base/api/openapi.json +450 -0
- package/dist/templates/base/api/package.json +50 -0
- package/dist/templates/base/api/scripts/openapi.ts +27 -0
- package/dist/templates/base/api/src/__tests__/server.test.ts +51 -0
- package/dist/templates/base/api/src/config.ts +43 -0
- package/dist/templates/base/api/src/core.ts +37 -0
- package/dist/templates/base/api/src/db/client.ts +30 -0
- package/dist/templates/base/api/src/db/migrate.ts +86 -0
- package/dist/templates/base/api/src/db/schema.ts +34 -0
- package/dist/templates/base/api/src/db/table.ts +8 -0
- package/dist/templates/base/api/src/logger.ts +5 -0
- package/dist/templates/base/api/src/main.ts +23 -0
- package/dist/templates/base/api/src/modules/items/__tests__/items.test.ts +86 -0
- package/dist/templates/base/api/src/modules/items/items.ts +121 -0
- package/dist/templates/base/api/src/orpc.ts +25 -0
- package/dist/templates/base/api/src/router.ts +10 -0
- package/dist/templates/base/api/src/server.ts +58 -0
- package/dist/templates/base/api/src/telemetry.ts +27 -0
- package/dist/templates/base/api/src/test/core-functions.sql +18 -0
- package/dist/templates/base/api/src/test/setup.ts +68 -0
- package/dist/templates/base/api/tsconfig.json +9 -0
- package/dist/templates/base/knip.ts +22 -0
- package/dist/templates/base/package.json +31 -0
- package/dist/templates/base/pnpm-workspace.yaml +20 -0
- package/dist/templates/base/tools/check-generated.ts +78 -0
- package/dist/templates/base/tools/check-rls.sh +30 -0
- package/dist/templates/base/tools/check-rls.sql +109 -0
- package/dist/templates/base/tools/no-org-id.sql +5 -0
- package/dist/templates/base/tools/test/no-skips.ts +58 -0
- package/dist/templates/base/tsconfig.base.json +16 -0
- package/dist/templates/base/tsconfig.json +9 -0
- package/dist/templates/base/ui/AGENTS.md +18 -0
- package/dist/templates/base/ui/package.json +32 -0
- package/dist/templates/base/ui/rsbuild.config.ts +36 -0
- package/dist/templates/base/ui/src/__Pascal__.tsx +9 -0
- package/dist/templates/base/ui/src/config.tsx +11 -0
- package/dist/templates/base/ui/src/index.ts +3 -0
- package/dist/templates/base/ui/src/items/ItemSheet.tsx +107 -0
- package/dist/templates/base/ui/src/items/ItemsPage.tsx +116 -0
- package/dist/templates/base/ui/src/items/useItems.ts +79 -0
- package/dist/templates/base/ui/src/orpc.ts +32 -0
- package/dist/templates/base/ui/tsconfig.json +11 -0
- package/dist/templates/base/vite.config.ts +63 -0
- package/dist/templates/migrate/.agents/skills/plugin-migrate/SKILL.md +61 -0
- package/dist/templates/migrate/migration/checklist.ts +429 -0
- package/dist/templates/migrate/migration/core-map.ts +149 -0
- package/dist/templates/migrate/migration/import-map.ts +4 -0
- package/dist/templates/migrate/migration/inventory.ts +881 -0
- package/dist/templates/migrate/package.json +15 -0
- package/dist/templates/migrate/scripts/import-mongo.ts +143 -0
- package/package.json +32 -3
package/README.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# create-erxes
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Creates an erxes plugin for the new core (Postgres): an Express 5, oRPC and Drizzle API, and a
|
|
4
|
+
React Module Federation remote that web loads.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pnpm create erxes inventory
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
The first question is a new plugin or a migration of an old erxes plugin. A migration adds a kit
|
|
11
|
+
that reads the old plugin from an erxes checkout (`--from <path>`) or a fresh clone (`--clone`)
|
|
12
|
+
and writes `MIGRATION.md`, one checklist section per module.
|
|
13
|
+
|
|
14
|
+
| Flag | Does |
|
|
15
|
+
| --------------------------- | ------------------------------------------- |
|
|
16
|
+
| `--migrate`, `--no-migrate` | migrate an old plugin, or start a new one |
|
|
17
|
+
| `--plugin <name>` | the old plugin to migrate, e.g. `operation` |
|
|
18
|
+
| `--from <path>`, `--clone` | read a local erxes checkout, or clone one |
|
|
19
|
+
| `--ref <ref>` | the git ref to read (`origin/main`) |
|
|
20
|
+
| `-n`, `-t`, `-d` | the plugin's name, title and description |
|
|
21
|
+
| `--no-install`, `--no-git` | skip `pnpm install`, skip `git init` |
|
|
22
|
+
| `-y` | take the default for every other question |
|
|
23
|
+
|
|
24
|
+
The generated repo's `AGENTS.md` says how to run and change it.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
3
|
+
import * as p from "@clack/prompts";
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
import { x } from "tinyexec";
|
|
6
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { mkdir, readFile, readdir, symlink, writeFile } from "node:fs/promises";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
// package.json
|
|
12
|
+
var version = "0.1.0";
|
|
13
|
+
// src/existing-plugins.ts
|
|
14
|
+
/** The old erxes plugins a new-core plugin can be migrated from (`backend/plugins/<name>_api`). */
|
|
15
|
+
const OLD_PLUGINS = [
|
|
16
|
+
"accounting",
|
|
17
|
+
"content",
|
|
18
|
+
"frontline",
|
|
19
|
+
"insurance",
|
|
20
|
+
"loyalty",
|
|
21
|
+
"mastra",
|
|
22
|
+
"mongolian",
|
|
23
|
+
"operation",
|
|
24
|
+
"payment",
|
|
25
|
+
"posclient",
|
|
26
|
+
"sales",
|
|
27
|
+
"tourism"
|
|
28
|
+
];
|
|
29
|
+
const isOldPlugin = (name) => OLD_PLUGINS.some((plugin) => plugin === name);
|
|
30
|
+
const ERXES_REPO = "https://github.com/erxes/erxes.git";
|
|
31
|
+
const DEFAULT_REF = "origin/main";
|
|
32
|
+
const git = async (args, cwd) => {
|
|
33
|
+
const result = await x("git", args, {
|
|
34
|
+
nodeOptions: { cwd },
|
|
35
|
+
throwOnError: false
|
|
36
|
+
});
|
|
37
|
+
if (result.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr.trim()}`);
|
|
38
|
+
};
|
|
39
|
+
const erxesCacheDir = () => join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "create-erxes", "erxes");
|
|
40
|
+
/** A shallow, blobless clone of erxes/erxes main that checks out only the plugin folders. */
|
|
41
|
+
const cloneErxes = async () => {
|
|
42
|
+
const dir = erxesCacheDir();
|
|
43
|
+
if (existsSync(join(dir, ".git"))) {
|
|
44
|
+
await git([
|
|
45
|
+
"fetch",
|
|
46
|
+
"-q",
|
|
47
|
+
"--depth=1",
|
|
48
|
+
"origin",
|
|
49
|
+
"main"
|
|
50
|
+
], dir);
|
|
51
|
+
await git([
|
|
52
|
+
"checkout",
|
|
53
|
+
"-q",
|
|
54
|
+
"--detach",
|
|
55
|
+
DEFAULT_REF
|
|
56
|
+
], dir);
|
|
57
|
+
return dir;
|
|
58
|
+
}
|
|
59
|
+
await mkdir(dirname(dir), { recursive: true });
|
|
60
|
+
await git([
|
|
61
|
+
"clone",
|
|
62
|
+
"-q",
|
|
63
|
+
"--depth=1",
|
|
64
|
+
"--filter=blob:none",
|
|
65
|
+
"--sparse",
|
|
66
|
+
ERXES_REPO,
|
|
67
|
+
dir
|
|
68
|
+
]);
|
|
69
|
+
await git([
|
|
70
|
+
"sparse-checkout",
|
|
71
|
+
"set",
|
|
72
|
+
"backend/plugins",
|
|
73
|
+
"frontend/plugins"
|
|
74
|
+
], dir);
|
|
75
|
+
return dir;
|
|
76
|
+
};
|
|
77
|
+
// src/naming.ts
|
|
78
|
+
const NAME_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
79
|
+
const RESERVED_NAMES = /* @__PURE__ */ new Set([
|
|
80
|
+
"core",
|
|
81
|
+
"gateway",
|
|
82
|
+
"api",
|
|
83
|
+
"graphql",
|
|
84
|
+
"health"
|
|
85
|
+
]);
|
|
86
|
+
/**
|
|
87
|
+
* Core keeps its own plugin registry, so an old plugin's name is free for its
|
|
88
|
+
* port. Core allows up to 40 characters.
|
|
89
|
+
*/
|
|
90
|
+
const validatePluginName = (name) => {
|
|
91
|
+
if (!NAME_PATTERN.test(name)) return "Use lowercase letters and digits, optionally separated by single dashes (e.g. inventory, erxes-agent-v2), starting with a letter.";
|
|
92
|
+
if (RESERVED_NAMES.has(name)) return `"${name}" is reserved by erxes.`;
|
|
93
|
+
if (name.length > 40) return "Use at most 40 characters.";
|
|
94
|
+
};
|
|
95
|
+
/** Core shows these in its plugin list: one line each, at most `max` characters. */
|
|
96
|
+
const validateLine = (max) => (text) => {
|
|
97
|
+
if (/[\r\n]/.test(text)) return "Use one line.";
|
|
98
|
+
if (text.length > max) return `Use at most ${max} characters.`;
|
|
99
|
+
};
|
|
100
|
+
const capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1);
|
|
101
|
+
const derivePluginNames = (name, title) => {
|
|
102
|
+
const words = name.split("-");
|
|
103
|
+
const id = words.join("_");
|
|
104
|
+
return {
|
|
105
|
+
/** The plugin's name as typed: the directory and the npm-style name. */
|
|
106
|
+
name,
|
|
107
|
+
/** Core's name for it: tables, permissions, events and the UI remote start with it. */
|
|
108
|
+
id,
|
|
109
|
+
/** The Module Federation remote web loads. */
|
|
110
|
+
remote: `${id}_ui`,
|
|
111
|
+
/** The React component the remote exposes. */
|
|
112
|
+
pascal: words.map(capitalize).join(""),
|
|
113
|
+
/** The label in erxes navigation and docs. */
|
|
114
|
+
title: title?.trim() || words.map(capitalize).join(" ")
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
// src/ask.ts
|
|
118
|
+
const CliOptions = z.object({
|
|
119
|
+
migrate: z.boolean().optional(),
|
|
120
|
+
plugin: z.string().optional(),
|
|
121
|
+
from: z.string().optional(),
|
|
122
|
+
clone: z.boolean().optional(),
|
|
123
|
+
ref: z.string().optional(),
|
|
124
|
+
name: z.string().optional(),
|
|
125
|
+
title: z.string().optional(),
|
|
126
|
+
description: z.string().optional(),
|
|
127
|
+
install: z.boolean(),
|
|
128
|
+
git: z.boolean(),
|
|
129
|
+
yes: z.boolean().optional()
|
|
130
|
+
});
|
|
131
|
+
const fail = (message) => {
|
|
132
|
+
p.cancel(message);
|
|
133
|
+
process.exit(1);
|
|
134
|
+
};
|
|
135
|
+
const isAnswer = (value) => typeof value !== "symbol";
|
|
136
|
+
/** A prompt's answer, or the end of the run when the user cancels it (clack returns a symbol). */
|
|
137
|
+
const answer = (value) => isAnswer(value) ? value : fail("Cancelled.");
|
|
138
|
+
const isCheckout = (dir) => existsSync(join(dir, ".git"));
|
|
139
|
+
const isEmptyDir = (dir) => !existsSync(dir) || readdirSync(dir).length === 0;
|
|
140
|
+
const askMigrate = async (cli) => {
|
|
141
|
+
if (cli.migrate !== void 0) return cli.migrate;
|
|
142
|
+
if (cli.plugin || cli.from || cli.clone) return true;
|
|
143
|
+
if (cli.yes) return false;
|
|
144
|
+
return answer(await p.select({
|
|
145
|
+
message: "What are you making?",
|
|
146
|
+
options: [{
|
|
147
|
+
value: false,
|
|
148
|
+
label: "New plugin"
|
|
149
|
+
}, {
|
|
150
|
+
value: true,
|
|
151
|
+
label: "Migrate an old plugin",
|
|
152
|
+
hint: "an erxes 3.x plugin, onto the new core"
|
|
153
|
+
}]
|
|
154
|
+
}));
|
|
155
|
+
};
|
|
156
|
+
const askOldPlugin = async (cli) => {
|
|
157
|
+
if (cli.plugin) return isOldPlugin(cli.plugin) ? cli.plugin : fail(`No old plugin "${cli.plugin}". Old plugins: ${OLD_PLUGINS.join(", ")}`);
|
|
158
|
+
if (cli.yes) return fail("Pass the old plugin to migrate with --plugin.");
|
|
159
|
+
return answer(await p.select({
|
|
160
|
+
message: "Old plugin to migrate",
|
|
161
|
+
options: OLD_PLUGINS.map((value) => ({
|
|
162
|
+
value,
|
|
163
|
+
label: value
|
|
164
|
+
}))
|
|
165
|
+
}));
|
|
166
|
+
};
|
|
167
|
+
/** The old erxes checkout to read, or undefined to clone one. */
|
|
168
|
+
const askCheckout = async (cli) => {
|
|
169
|
+
if (cli.from && cli.clone) return fail("Pass --from or --clone, not both.");
|
|
170
|
+
if (cli.from) {
|
|
171
|
+
const dir = resolve(cli.from);
|
|
172
|
+
return isCheckout(dir) ? dir : fail(`${dir} is not a git checkout.`);
|
|
173
|
+
}
|
|
174
|
+
if (cli.clone) return void 0;
|
|
175
|
+
if (cli.yes) return fail("Pass an old erxes checkout with --from, or --clone.");
|
|
176
|
+
if (answer(await p.select({
|
|
177
|
+
message: "Old erxes checkout",
|
|
178
|
+
options: [{
|
|
179
|
+
value: "path",
|
|
180
|
+
label: "A checkout on this machine"
|
|
181
|
+
}, {
|
|
182
|
+
value: "clone",
|
|
183
|
+
label: `Clone erxes/erxes main into ${erxesCacheDir()}`,
|
|
184
|
+
hint: "blobless, only backend/plugins and frontend/plugins"
|
|
185
|
+
}]
|
|
186
|
+
})) === "clone") return void 0;
|
|
187
|
+
const path = answer(await p.text({
|
|
188
|
+
message: "Path to the old erxes checkout",
|
|
189
|
+
validate: (value) => isCheckout(resolve(value ?? "")) ? void 0 : "Not a git checkout."
|
|
190
|
+
}));
|
|
191
|
+
return resolve(path);
|
|
192
|
+
};
|
|
193
|
+
/** The plugin name: --name, else the directory's name, else asked (an old plugin's name first). */
|
|
194
|
+
const askName = async (cli, directory, oldPlugin) => {
|
|
195
|
+
const fromDirectory = directory ? basename(resolve(directory)) : void 0;
|
|
196
|
+
const candidate = cli.name ?? fromDirectory ?? (cli.yes ? oldPlugin : void 0);
|
|
197
|
+
if (candidate !== void 0 && !validatePluginName(candidate)) return candidate;
|
|
198
|
+
if (cli.name) return fail(`Invalid plugin name "${cli.name}": ${validatePluginName(cli.name)}`);
|
|
199
|
+
if (cli.yes) return fail("Pass a valid plugin name with --name or as the directory.");
|
|
200
|
+
return answer(await p.text({
|
|
201
|
+
message: "Plugin name",
|
|
202
|
+
placeholder: "inventory",
|
|
203
|
+
initialValue: oldPlugin,
|
|
204
|
+
validate: (value) => validatePluginName(value ?? "")
|
|
205
|
+
}));
|
|
206
|
+
};
|
|
207
|
+
const askText = async (message, given, fallback, validate, yes) => {
|
|
208
|
+
if (given !== void 0) {
|
|
209
|
+
const error = validate(given);
|
|
210
|
+
return error ? fail(`${message}: ${error}`) : given;
|
|
211
|
+
}
|
|
212
|
+
if (yes) return fallback;
|
|
213
|
+
return answer(await p.text({
|
|
214
|
+
message,
|
|
215
|
+
defaultValue: fallback,
|
|
216
|
+
placeholder: fallback,
|
|
217
|
+
validate: (value) => validate(value ?? "")
|
|
218
|
+
}));
|
|
219
|
+
};
|
|
220
|
+
const askYes = async (message, yes = false) => yes || answer(await p.confirm({
|
|
221
|
+
message,
|
|
222
|
+
initialValue: true
|
|
223
|
+
}));
|
|
224
|
+
// src/scaffold.ts
|
|
225
|
+
/** scripts/templates.ts writes them at build time; this file and dist/index.js are both one level down. */
|
|
226
|
+
const TEMPLATES = fileURLToPath(new URL("../dist/templates/", import.meta.url));
|
|
227
|
+
const DOTFILES = /* @__PURE__ */ new Map([
|
|
228
|
+
["_gitignore", ".gitignore"],
|
|
229
|
+
["_dockerignore", ".dockerignore"],
|
|
230
|
+
["_env.example", ".env.example"],
|
|
231
|
+
["_node-version", ".node-version"]
|
|
232
|
+
]);
|
|
233
|
+
/** A value goes into a single-quoted string in code and a string in JSON; Markdown takes it as is. */
|
|
234
|
+
const escapeFor = (file) => {
|
|
235
|
+
switch (extname(file)) {
|
|
236
|
+
case ".ts":
|
|
237
|
+
case ".tsx": return (value) => value.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
|
|
238
|
+
case ".json": return (value) => JSON.stringify(value).slice(1, -1);
|
|
239
|
+
default: return (value) => value;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
/** Fills `__token__`s from the template only: a value that looks like a token stays as typed. */
|
|
243
|
+
const applyTokens = (text, tokens, escape = (value) => value) => text.replace(/__[A-Za-z][A-Za-z0-9]*__/g, (token) => {
|
|
244
|
+
const value = tokens.get(token);
|
|
245
|
+
return value === void 0 ? token : escape(value);
|
|
246
|
+
});
|
|
247
|
+
/** Copies a template layer into `targetDir`, renaming dotfiles and filling tokens. */
|
|
248
|
+
const copyLayer = async (layer, targetDir, tokens) => {
|
|
249
|
+
const root = join(TEMPLATES, layer);
|
|
250
|
+
const entries = await readdir(root, {
|
|
251
|
+
recursive: true,
|
|
252
|
+
withFileTypes: true
|
|
253
|
+
});
|
|
254
|
+
for (const entry of entries.filter((item) => item.isFile())) {
|
|
255
|
+
const rel = relative(root, join(entry.parentPath, entry.name));
|
|
256
|
+
const name = DOTFILES.get(entry.name) ?? applyTokens(entry.name, tokens);
|
|
257
|
+
const path = join(targetDir, dirname(rel), name);
|
|
258
|
+
const text = await readFile(join(entry.parentPath, entry.name), "utf8");
|
|
259
|
+
await mkdir(dirname(path), { recursive: true });
|
|
260
|
+
await writeFile(path, applyTokens(text, tokens, escapeFor(path)));
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
const Dependencies = z.record(z.string(), z.string());
|
|
264
|
+
const PackageJson = z.object({
|
|
265
|
+
scripts: Dependencies.default({}),
|
|
266
|
+
devDependencies: Dependencies.default({})
|
|
267
|
+
});
|
|
268
|
+
const readPackageJson = async (path) => {
|
|
269
|
+
const json = z.record(z.string(), z.unknown()).parse(JSON.parse(await readFile(path, "utf8")));
|
|
270
|
+
return {
|
|
271
|
+
...json,
|
|
272
|
+
...PackageJson.parse(json)
|
|
273
|
+
};
|
|
274
|
+
};
|
|
275
|
+
const writeJson = (path, value) => writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
|
|
276
|
+
const sortKeys = (record) => Object.fromEntries(Object.entries(record).toSorted(([a], [b]) => a.localeCompare(b)));
|
|
277
|
+
/**
|
|
278
|
+
* Claude Code loads skills from `.claude/skills`; the repo keeps them in
|
|
279
|
+
* `.agents/skills`, so the first links to the second. Git commits the link.
|
|
280
|
+
*/
|
|
281
|
+
const linkSkills = async (targetDir) => {
|
|
282
|
+
const link = join(targetDir, ".claude", "skills");
|
|
283
|
+
await mkdir(dirname(link), { recursive: true });
|
|
284
|
+
try {
|
|
285
|
+
await symlink(join("..", ".agents", "skills"), link, "dir");
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (process.platform !== "win32") throw error;
|
|
288
|
+
await symlink(join(targetDir, ".agents", "skills"), link, "junction");
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
const migrationSkill = (plugin) => `
|
|
292
|
+
- This repo ports the old erxes \`${plugin}\` plugin. Work through
|
|
293
|
+
the \`plugin-migrate\` skill. It starts with the inventory and checklist tasks.`;
|
|
294
|
+
/** Writes a plugin for the new core: the base template, plus the migration kit for a port. */
|
|
295
|
+
const scaffold = async (targetDir, options) => {
|
|
296
|
+
const { names, migrateFrom } = options;
|
|
297
|
+
const tokens = /* @__PURE__ */ new Map([
|
|
298
|
+
["__id__", names.id],
|
|
299
|
+
["__Pascal__", names.pascal],
|
|
300
|
+
["__title__", names.title],
|
|
301
|
+
["__description__", options.description],
|
|
302
|
+
["__apiPort__", String(options.apiPort)],
|
|
303
|
+
["__uiPort__", String(options.uiPort)],
|
|
304
|
+
["__pnpmVersion__", options.pnpmVersion],
|
|
305
|
+
["__migrationSkill__", migrateFrom ? migrationSkill(migrateFrom) : ""]
|
|
306
|
+
]);
|
|
307
|
+
await copyLayer("base", targetDir, tokens);
|
|
308
|
+
const uiPackageJson = join(targetDir, "ui/package.json");
|
|
309
|
+
const ui = await readPackageJson(uiPackageJson);
|
|
310
|
+
await writeJson(uiPackageJson, {
|
|
311
|
+
...ui,
|
|
312
|
+
devDependencies: sortKeys(ui.devDependencies)
|
|
313
|
+
});
|
|
314
|
+
await linkSkills(targetDir);
|
|
315
|
+
if (!migrateFrom) return;
|
|
316
|
+
const packageJson = join(targetDir, "package.json");
|
|
317
|
+
const base = await readPackageJson(packageJson);
|
|
318
|
+
await copyLayer("migrate", targetDir, tokens);
|
|
319
|
+
const extra = await readPackageJson(packageJson);
|
|
320
|
+
await writeJson(packageJson, {
|
|
321
|
+
...base,
|
|
322
|
+
scripts: {
|
|
323
|
+
...base.scripts,
|
|
324
|
+
...extra.scripts
|
|
325
|
+
},
|
|
326
|
+
devDependencies: sortKeys({
|
|
327
|
+
...base.devDependencies,
|
|
328
|
+
...extra.devDependencies
|
|
329
|
+
})
|
|
330
|
+
});
|
|
331
|
+
};
|
|
332
|
+
// src/cli.ts
|
|
333
|
+
const API_PORT = 3399;
|
|
334
|
+
const UI_PORT = 3099;
|
|
335
|
+
const run = async (command, args, cwd) => {
|
|
336
|
+
const result = await x(command, args, {
|
|
337
|
+
nodeOptions: { cwd },
|
|
338
|
+
throwOnError: false
|
|
339
|
+
});
|
|
340
|
+
return {
|
|
341
|
+
ok: result.exitCode === 0,
|
|
342
|
+
output: `${result.stdout}${result.stderr}`.trim()
|
|
343
|
+
};
|
|
344
|
+
};
|
|
345
|
+
const changeDirectoryCommand = (path) => process.platform === "win32" ? `Set-Location -LiteralPath '${path.replaceAll("'", "''")}'` : `cd -- '${path.replaceAll("'", "'\\''")}'`;
|
|
346
|
+
const pnpmVersion = async () => {
|
|
347
|
+
const version = (await x("pnpm", ["--version"], { throwOnError: false })).stdout.trim();
|
|
348
|
+
return /^\d+\.\d+\.\d+$/.test(version) ? version : fail("erxes plugins use pnpm. Install it with `corepack enable pnpm` and run again.");
|
|
349
|
+
};
|
|
350
|
+
/** Every question, before anything is written. */
|
|
351
|
+
const ask = async (directory, cli) => {
|
|
352
|
+
const plugin = await askMigrate(cli) ? await askOldPlugin(cli) : void 0;
|
|
353
|
+
const migration = plugin && {
|
|
354
|
+
plugin,
|
|
355
|
+
from: await askCheckout(cli),
|
|
356
|
+
ref: cli.ref ?? "origin/main"
|
|
357
|
+
};
|
|
358
|
+
const name = await askName(cli, directory, plugin);
|
|
359
|
+
const targetDir = resolve(directory ?? name);
|
|
360
|
+
if (!isEmptyDir(targetDir)) fail(`${targetDir} already exists and is not empty.`);
|
|
361
|
+
const fallback = derivePluginNames(name);
|
|
362
|
+
const title = await askText("Title", cli.title, fallback.title, validateLine(80), cli.yes);
|
|
363
|
+
const description = await askText("Description", cli.description, `${title} plugin for erxes`, validateLine(500), cli.yes);
|
|
364
|
+
const install = cli.install && await askYes("Install dependencies now?", cli.yes);
|
|
365
|
+
const git = cli.git && await askYes("Initialize a git repository?", cli.yes);
|
|
366
|
+
return {
|
|
367
|
+
targetDir,
|
|
368
|
+
names: derivePluginNames(name, title),
|
|
369
|
+
description,
|
|
370
|
+
migration,
|
|
371
|
+
install,
|
|
372
|
+
git,
|
|
373
|
+
pnpmVersion: await pnpmVersion()
|
|
374
|
+
};
|
|
375
|
+
};
|
|
376
|
+
/** Runs a step under the spinner; a failure prints its output. */
|
|
377
|
+
const step = async (label, done, work) => {
|
|
378
|
+
const spin = p.spinner();
|
|
379
|
+
spin.start(label);
|
|
380
|
+
const result = await work();
|
|
381
|
+
if (result.ok) spin.stop(done);
|
|
382
|
+
else {
|
|
383
|
+
spin.error(`${label} failed`);
|
|
384
|
+
p.log.message(result.output);
|
|
385
|
+
}
|
|
386
|
+
return result;
|
|
387
|
+
};
|
|
388
|
+
const clone = async () => {
|
|
389
|
+
try {
|
|
390
|
+
return {
|
|
391
|
+
ok: true,
|
|
392
|
+
output: await cloneErxes()
|
|
393
|
+
};
|
|
394
|
+
} catch (error) {
|
|
395
|
+
return {
|
|
396
|
+
ok: false,
|
|
397
|
+
output: error instanceof Error ? error.message : String(error)
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
const create = async (plan) => {
|
|
402
|
+
const { targetDir, names, migration } = plan;
|
|
403
|
+
await scaffold(targetDir, {
|
|
404
|
+
names,
|
|
405
|
+
description: plan.description,
|
|
406
|
+
apiPort: API_PORT,
|
|
407
|
+
uiPort: UI_PORT,
|
|
408
|
+
pnpmVersion: plan.pnpmVersion,
|
|
409
|
+
migrateFrom: migration?.plugin
|
|
410
|
+
});
|
|
411
|
+
p.log.success(`Created ${relative(process.cwd(), targetDir) || "."}`);
|
|
412
|
+
if (plan.git) {
|
|
413
|
+
const git = await run("git", ["init", "-q"], targetDir);
|
|
414
|
+
if (!git.ok) p.log.warn(`git init failed: ${git.output}`);
|
|
415
|
+
}
|
|
416
|
+
const cloned = migration && !migration.from ? await step("Cloning erxes/erxes", `Old erxes is in ${erxesCacheDir()}`, clone) : void 0;
|
|
417
|
+
const from = migration?.from ?? (cloned?.ok ? cloned.output : void 0);
|
|
418
|
+
const installed = plan.install && (await step("Installing dependencies with pnpm", "Dependencies installed", () => run("pnpm", ["install"], targetDir))).ok;
|
|
419
|
+
const inventoryArgs = migration && from ? [
|
|
420
|
+
"--from",
|
|
421
|
+
from,
|
|
422
|
+
"--plugin",
|
|
423
|
+
migration.plugin,
|
|
424
|
+
"--ref",
|
|
425
|
+
migration.ref
|
|
426
|
+
] : [];
|
|
427
|
+
const inventoried = installed && inventoryArgs.length > 0 && (await step(`Reading ${migration?.plugin} at ${migration?.ref}`, "Wrote MIGRATION.md", async () => {
|
|
428
|
+
const inventory = await run("pnpm", [
|
|
429
|
+
"-s",
|
|
430
|
+
"migrate:inventory",
|
|
431
|
+
"--",
|
|
432
|
+
...inventoryArgs
|
|
433
|
+
], targetDir);
|
|
434
|
+
return inventory.ok ? run("pnpm", ["-s", "migrate:checklist"], targetDir) : inventory;
|
|
435
|
+
})).ok;
|
|
436
|
+
if (installed) await run("pnpm", [
|
|
437
|
+
"exec",
|
|
438
|
+
"vp",
|
|
439
|
+
"fmt"
|
|
440
|
+
], targetDir);
|
|
441
|
+
return {
|
|
442
|
+
installed,
|
|
443
|
+
inventoried,
|
|
444
|
+
inventoryArgs
|
|
445
|
+
};
|
|
446
|
+
};
|
|
447
|
+
const nextSteps = (plan, result) => {
|
|
448
|
+
const cd = relative(process.cwd(), plan.targetDir);
|
|
449
|
+
return [
|
|
450
|
+
...cd ? [changeDirectoryCommand(cd)] : [],
|
|
451
|
+
...result.installed ? [] : ["pnpm install"],
|
|
452
|
+
...plan.migration && !result.inventoried ? [`pnpm migrate:inventory -- ${result.inventoryArgs.join(" ")}`, "pnpm migrate:checklist"] : [],
|
|
453
|
+
"cp .env.example .env",
|
|
454
|
+
"pnpm dev:api",
|
|
455
|
+
"pnpm dev:ui",
|
|
456
|
+
"",
|
|
457
|
+
`core .env: CORE_PLUGIN_KEYS=${plan.names.id}:<32+ character secret>`,
|
|
458
|
+
`web .env: PUBLIC_PLUGINS=${plan.names.remote}@http://localhost:${UI_PORT}/remoteEntry.js`,
|
|
459
|
+
...plan.migration ? ["", "Then work through MIGRATION.md with the plugin-migrate skill."] : []
|
|
460
|
+
].join("\n");
|
|
461
|
+
};
|
|
462
|
+
const main = async (directory, options) => {
|
|
463
|
+
p.intro("create-erxes");
|
|
464
|
+
const plan = await ask(directory, CliOptions.parse(options));
|
|
465
|
+
const result = await create(plan);
|
|
466
|
+
const ready = (!plan.install || result.installed) && (!plan.migration || !plan.install || result.inventoried);
|
|
467
|
+
p.note(nextSteps(plan, result), "Next steps");
|
|
468
|
+
if (!ready) {
|
|
469
|
+
p.log.error("A step failed; see its output above.");
|
|
470
|
+
p.outro(`Plugin "${plan.names.name}" was created, but it is not ready yet.`);
|
|
471
|
+
process.exitCode = 1;
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
p.outro(`Plugin "${plan.names.name}" is ready. See AGENTS.md.`);
|
|
475
|
+
};
|
|
476
|
+
const runCli = async (argv) => {
|
|
477
|
+
await new Command("create-erxes").version(version).description("Create an erxes plugin for the new core, or migrate an old erxes plugin onto it").argument("[directory]", "target directory (defaults to the plugin name)").option("--migrate", "migrate an old erxes plugin").option("--no-migrate", "start a new plugin").option("--plugin <name>", "migrate: the old plugin, e.g. operation").option("--from <path>", "migrate: read this old erxes checkout").option("--clone", "migrate: clone erxes/erxes main to read the old plugin").option("--ref <ref>", `migrate: the git ref to read (default ${DEFAULT_REF})`).option("-n, --name <name>", "plugin name, e.g. inventory or erxes-agent-v2").option("-t, --title <title>", "title shown in erxes navigation").option("-d, --description <text>", "one-line description").option("--no-install", "skip installing dependencies").option("--no-git", "skip git init").option("-y, --yes", "accept defaults for every unanswered question").action(main).parseAsync(argv);
|
|
478
|
+
};
|
|
479
|
+
// src/index.ts
|
|
480
|
+
await runCli(process.argv);
|
|
481
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: endpoint
|
|
3
|
+
description: Add or change an API procedure. Use when editing api/src/modules, api/src/router.ts or the manifest's permissions, or when the UI needs data the API doesn't serve yet.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
1. Pick the permission from `PERMISSIONS` in `api/src/core.ts`. A new one goes
|
|
7
|
+
there and into `manifest.permissions`, named `__id__.<record>.<verb>`.
|
|
8
|
+
2. Write the procedure in `api/src/modules/<module>/<module>.ts` on `reads(action)`
|
|
9
|
+
or `writes(action)` from `api/src/orpc.ts`, with zod `.input()` and `.output()` schemas. Query
|
|
10
|
+
through `context.tx` with no org filter: row-level security scopes it.
|
|
11
|
+
Lists page by cursor, newest first, as `items.list` does.
|
|
12
|
+
3. Fail with `ORPCError` (`NOT_FOUND`, `FORBIDDEN`, `CONFLICT`, `BAD_REQUEST`);
|
|
13
|
+
the UI shows its `message`.
|
|
14
|
+
4. Add the module to `router` in `api/src/router.ts`. The UI's types follow.
|
|
15
|
+
Run `pnpm openapi` and commit the contract document.
|
|
16
|
+
5. In the UI, read with `orpc.<group>.<name>.queryOptions()` and write with
|
|
17
|
+
`mutationOptions()`, invalidating `orpc.<group>.key()` on success.
|
|
18
|
+
6. Test it in the module's `__tests__`: the happy path, another organisation
|
|
19
|
+
seeing nothing, and a member without the permission getting `FORBIDDEN`.
|
|
20
|
+
|
|
21
|
+
Done when that test passes in `vp run test` and `vp run check` is clean.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: schema-change
|
|
3
|
+
description: Change the Postgres schema. Use when adding or altering a table, column or index in api/src/db/schema.ts, or when the CI migration drift check or pnpm check:rls fails.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
1. Edit `api/src/db/schema.ts`. Declare tables with `table('<name>')` from
|
|
7
|
+
`./table.ts`, which makes them `__id___<name>`. A new table has
|
|
8
|
+
`id: text().primaryKey()` and `orgId: text().notNull()`, and its indexes and
|
|
9
|
+
constraints lead with `orgId` and carry their full `__id___` name.
|
|
10
|
+
2. Run `pnpm db:generate` and read the SQL in `api/drizzle/`. For each new
|
|
11
|
+
table, append to that same file:
|
|
12
|
+
|
|
13
|
+
```sql
|
|
14
|
+
--> statement-breakpoint
|
|
15
|
+
SELECT core_enable_tenant_rls('__id___<name>');
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
A table that can't have `org_id` goes into `no_org_id` in
|
|
19
|
+
`tools/check-rls.sql`, with the reason.
|
|
20
|
+
|
|
21
|
+
3. Migrations only add or alter. Never edit one that has been applied anywhere,
|
|
22
|
+
and never run `drizzle-kit push`. To retire a column, stop reading and
|
|
23
|
+
writing it and leave it in the table.
|
|
24
|
+
4. Run `pnpm db:check`, then `pnpm check:rls` and `vp run test` with
|
|
25
|
+
`DATA_TEST_URL`. Both migrate fresh databases.
|
|
26
|
+
|
|
27
|
+
Done when the schema change and its migration are in one commit,
|
|
28
|
+
`pnpm check:rls` passes, and a second `pnpm db:generate` writes nothing.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: verify
|
|
3
|
+
description: Show a change works in erxes, not only in tests. Use before calling any change a member can see or do finished.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Use synthetic data only.
|
|
7
|
+
|
|
8
|
+
1. Run the gates: `vp run check`, `vp run test`, `pnpm build`.
|
|
9
|
+
2. Start core from an erxes checkout on branch `postgre`, following its
|
|
10
|
+
`verify-feature` skill. Give core
|
|
11
|
+
`CORE_PLUGIN_KEYS=__id__:<32+ character secret>`, and web
|
|
12
|
+
`PUBLIC_PLUGINS=__id___ui@http://localhost:__uiPort__/remoteEntry.js`.
|
|
13
|
+
3. Give the plugin role a database by running `core$ pnpm db:plugin-role __id__` in core, then
|
|
14
|
+
put its URL in this repo's `.env` as `DATA_URL`, with the same secret as
|
|
15
|
+
`PLUGIN_SECRET`.
|
|
16
|
+
4. Run `pnpm dev:api` and `pnpm dev:ui`. The API log ends with its address; a
|
|
17
|
+
failed `registerManifest` means the secret or `CORE_URL` is wrong.
|
|
18
|
+
5. In web, open the plugin's tab, walk the change, reload, and check it
|
|
19
|
+
persisted. Repeat as a member whose role lacks the permission and check
|
|
20
|
+
they are refused.
|
|
21
|
+
6. Keep screenshots and logs in `.scratch/` (git ignores it).
|
|
22
|
+
|
|
23
|
+
Done when the handoff lists what you saw at each step, the refusal included,
|
|
24
|
+
and where the screenshots are.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
concurrency:
|
|
12
|
+
group: ci-${{ github.ref }}
|
|
13
|
+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
|
14
|
+
|
|
15
|
+
jobs:
|
|
16
|
+
check:
|
|
17
|
+
runs-on: ubuntu-latest
|
|
18
|
+
services:
|
|
19
|
+
postgres:
|
|
20
|
+
image: postgres:18
|
|
21
|
+
env:
|
|
22
|
+
POSTGRES_USER: ci
|
|
23
|
+
POSTGRES_PASSWORD: ci-only-password
|
|
24
|
+
POSTGRES_DB: postgres
|
|
25
|
+
ports: ['5432:5432']
|
|
26
|
+
options: --health-cmd "pg_isready -U ci" --health-interval 5s --health-timeout 3s --health-retries 10
|
|
27
|
+
steps:
|
|
28
|
+
- uses: actions/checkout@v7
|
|
29
|
+
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
|
30
|
+
- uses: actions/setup-node@v7
|
|
31
|
+
with:
|
|
32
|
+
node-version-file: .node-version
|
|
33
|
+
cache: pnpm
|
|
34
|
+
- run: pnpm install --frozen-lockfile
|
|
35
|
+
- run: pnpm exec vp run check
|
|
36
|
+
- run: pnpm exec vp run test
|
|
37
|
+
env:
|
|
38
|
+
DATA_TEST_URL: postgres://ci:ci-only-password@127.0.0.1:5432/postgres
|
|
39
|
+
# What lets queries rely on withOrg() instead of org filters (tools/check-rls.sql).
|
|
40
|
+
- run: pnpm check:rls
|
|
41
|
+
env:
|
|
42
|
+
DATA_TEST_URL: postgres://ci:ci-only-password@127.0.0.1:5432/postgres
|
|
43
|
+
- run: pnpm image:context
|
|
44
|
+
- run: docker build --build-arg VERSION=${{ github.sha }} -t __id__-plugin .
|