@magmonium/cli 0.7.14 → 0.8.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/bin/cli.js CHANGED
@@ -21,6 +21,8 @@ const sanitizeI18nCommand = require('./commands/sanitize-i18n');
21
21
  const compileI18nCommand = require('./commands/compile-i18n');
22
22
  const generateCommand = require('./commands/generate');
23
23
  const patchWcEnvCommand = require('./commands/patch-wc-env');
24
+ const genCodeCommand = require('./commands/gen-code');
25
+ const genTestCommand = require('./commands/gen-test');
24
26
 
25
27
  const program = new Command();
26
28
 
@@ -51,5 +53,7 @@ sanitizeI18nCommand(program);
51
53
  compileI18nCommand(program);
52
54
  generateCommand(program);
53
55
  patchWcEnvCommand(program);
56
+ genCodeCommand(program);
57
+ genTestCommand(program);
54
58
 
55
59
  program.parse();
@@ -0,0 +1,155 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { stringify } = require('yaml');
4
+ const pkg = require('../../package.json');
5
+
6
+ const DESIGN_ROOT = '.magmonium';
7
+
8
+ /**
9
+ * The editor's codegen, bundled into this package at build time from
10
+ * `libs/codegen` (ADR 0181). Absent when the CLI runs from workspace source
11
+ * rather than from `dist/` or npm, which is the one case worth naming.
12
+ */
13
+ function loadCodegen() {
14
+ const bundle = path.join(__dirname, '..', '..', 'codegen', 'index.js');
15
+ if (!fs.existsSync(bundle)) {
16
+ throw new Error(
17
+ `codegen bundle not found at ${bundle} — run \`npx nx build cli\` and use dist/libs/cli`
18
+ );
19
+ }
20
+ return require(bundle);
21
+ }
22
+
23
+ // `.magmonium/` as the `path → text` map the codec reads, POSIX paths from the
24
+ // app root — the same shape the editor reads a linked folder into.
25
+ function readDesignFiles(root) {
26
+ const files = {};
27
+ const walk = (dir) => {
28
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
29
+ const full = path.join(dir, entry.name);
30
+ if (entry.isDirectory()) walk(full);
31
+ else if (entry.isFile()) {
32
+ files[path.relative(root, full).split(path.sep).join('/')] =
33
+ fs.readFileSync(full, 'utf8');
34
+ }
35
+ }
36
+ };
37
+ walk(path.join(root, DESIGN_ROOT));
38
+ return files;
39
+ }
40
+
41
+ // `a > b` over `major.minor.patch`, prerelease tags ignored.
42
+ function isNewer(a, b) {
43
+ const parts = (v) =>
44
+ v
45
+ .split('-')[0]
46
+ .split('.')
47
+ .map((n) => Number(n) || 0);
48
+ const [x, y] = [parts(a), parts(b)];
49
+ for (let i = 0; i < 3; i++) {
50
+ if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
51
+ }
52
+ return false;
53
+ }
54
+
55
+ // Every file the GeneratedSet occupies on disk now, so a Screen deleted in the
56
+ // editor does not leave its slice behind: the set is regenerated whole.
57
+ function clearGeneratedSet(root, generatedSet) {
58
+ let removed = 0;
59
+ for (const line of generatedSet) {
60
+ const rel = line.replace(/^\//, '');
61
+ if (rel.endsWith('/')) {
62
+ const dir = path.join(root, rel);
63
+ if (fs.existsSync(dir)) {
64
+ fs.rmSync(dir, { recursive: true, force: true });
65
+ removed++;
66
+ }
67
+ continue;
68
+ }
69
+ // `src/app/*.router.ts` — one `*` in the file name, never in a folder.
70
+ const dir = path.join(root, path.dirname(rel));
71
+ const pattern = new RegExp(
72
+ `^${path
73
+ .basename(rel)
74
+ .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
75
+ .replace('*', '[^/]+')}$`
76
+ );
77
+ if (!fs.existsSync(dir)) continue;
78
+ for (const name of fs.readdirSync(dir)) {
79
+ if (pattern.test(name)) {
80
+ fs.rmSync(path.join(dir, name), { force: true });
81
+ removed++;
82
+ }
83
+ }
84
+ }
85
+ return removed;
86
+ }
87
+
88
+ /**
89
+ * Regenerates the GeneratedSet from `.magmonium/` alone (ADR 0181): the
90
+ * DesignSource through the same codec and codegen the editor runs, its
91
+ * operations snapshot standing in for the live spec. With `tests`, the Emitted
92
+ * tests beside the code as well.
93
+ */
94
+ function generate({ root = process.cwd(), tests = false } = {}) {
95
+ if (!fs.existsSync(path.join(root, DESIGN_ROOT, 'index.json'))) {
96
+ throw new Error(
97
+ `${DESIGN_ROOT}/index.json not found in ${root} — not an app emitted by the editor`
98
+ );
99
+ }
100
+ const codegen = loadCodegen();
101
+ const read = codegen.readDesignSource(readDesignFiles(root));
102
+ if (!read.ok || !read.source) {
103
+ const refusal = read.refusal || {};
104
+ throw new Error(
105
+ `cannot read ${DESIGN_ROOT}/ (${refusal.reason || 'unreadable'}${
106
+ refusal.path ? `: ${refusal.path}` : ''
107
+ }${refusal.version ? `, v${refusal.version}` : ''})`
108
+ );
109
+ }
110
+ const source = read.source;
111
+ if (source.codegen && isNewer(source.codegen, pkg.version)) {
112
+ throw new Error(
113
+ `the design was written by @magmonium/cli ${source.codegen}, newer than this ${pkg.version}.\n` +
114
+ ` Pin the version it needs: npm install --save-dev --save-exact @magmonium/cli@${source.codegen}`
115
+ );
116
+ }
117
+
118
+ const ws = {
119
+ ...source,
120
+ operationOf: codegen.operationResolverOf(source.operations),
121
+ };
122
+ const files = codegen.emitGeneratedFiles(ws, stringify, tests);
123
+ const removed = clearGeneratedSet(root, codegen.GENERATED_SET);
124
+ for (const file of files) {
125
+ const target = path.join(root, file.path);
126
+ fs.mkdirSync(path.dirname(target), { recursive: true });
127
+ fs.writeFileSync(target, file.contents);
128
+ }
129
+ return { written: files.length, removed };
130
+ }
131
+
132
+ function genCodeCommand(program) {
133
+ program
134
+ .command('gen-code')
135
+ .description(
136
+ 'Regenerate the generated code (features, pages, widgets, shared/lib, shared/type, router and provide overlays) from .magmonium/'
137
+ )
138
+ .option('--root <path>', 'App root (default: cwd)')
139
+ .action((options) => {
140
+ try {
141
+ const { written } = generate({ root: options.root || process.cwd() });
142
+ console.log(
143
+ `✅ gen-code: ${written} file(s) generated from ${DESIGN_ROOT}/`
144
+ );
145
+ } catch (error) {
146
+ console.error(`❌ gen-code: ${error.message}`);
147
+ process.exit(1);
148
+ }
149
+ });
150
+ }
151
+
152
+ module.exports = genCodeCommand;
153
+ module.exports.generate = generate;
154
+ module.exports.isNewer = isNewer;
155
+ module.exports.clearGeneratedSet = clearGeneratedSet;
@@ -0,0 +1,27 @@
1
+ const { generate } = require('./gen-code');
2
+
3
+ /** `gen-code` plus the Emitted tests beside it, so it runs on its own (ADR 0181). */
4
+ function genTestCommand(program) {
5
+ program
6
+ .command('gen-test')
7
+ .description(
8
+ 'Regenerate the generated code and its Emitted tests from .magmonium/'
9
+ )
10
+ .option('--root <path>', 'App root (default: cwd)')
11
+ .action((options) => {
12
+ try {
13
+ const { written } = generate({
14
+ root: options.root || process.cwd(),
15
+ tests: true,
16
+ });
17
+ console.log(
18
+ `✅ gen-test: ${written} file(s) generated from .magmonium/`
19
+ );
20
+ } catch (error) {
21
+ console.error(`❌ gen-test: ${error.message}`);
22
+ process.exit(1);
23
+ }
24
+ });
25
+ }
26
+
27
+ module.exports = genTestCommand;