@latticecms/cli 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/LICENSE +21 -0
- package/README.md +140 -2
- package/dist/bin.d.ts +3 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +12 -0
- package/dist/bin.js.map +1 -0
- package/dist/changes.d.ts +22 -0
- package/dist/changes.d.ts.map +1 -0
- package/dist/changes.js +118 -0
- package/dist/changes.js.map +1 -0
- package/dist/collection.d.ts +5 -0
- package/dist/collection.d.ts.map +1 -0
- package/dist/collection.js +166 -0
- package/dist/collection.js.map +1 -0
- package/dist/config.d.ts +37 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +111 -0
- package/dist/config.js.map +1 -0
- package/dist/diff.d.ts +6 -0
- package/dist/diff.d.ts.map +1 -0
- package/dist/diff.js +83 -0
- package/dist/diff.js.map +1 -0
- package/dist/edit.d.ts +105 -0
- package/dist/edit.d.ts.map +1 -0
- package/dist/edit.js +571 -0
- package/dist/edit.js.map +1 -0
- package/dist/exit.d.ts +13 -0
- package/dist/exit.d.ts.map +1 -0
- package/dist/exit.js +19 -0
- package/dist/exit.js.map +1 -0
- package/dist/layout.d.ts +20 -0
- package/dist/layout.d.ts.map +1 -0
- package/dist/layout.js +59 -0
- package/dist/layout.js.map +1 -0
- package/dist/main.d.ts +7 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +58 -0
- package/dist/main.js.map +1 -0
- package/dist/migrate.d.ts +9 -0
- package/dist/migrate.d.ts.map +1 -0
- package/dist/migrate.js +120 -0
- package/dist/migrate.js.map +1 -0
- package/dist/migration.d.ts +5 -0
- package/dist/migration.d.ts.map +1 -0
- package/dist/migration.js +170 -0
- package/dist/migration.js.map +1 -0
- package/dist/names.d.ts +15 -0
- package/dist/names.d.ts.map +1 -0
- package/dist/names.js +32 -0
- package/dist/names.js.map +1 -0
- package/dist/templates.d.ts +21 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +73 -0
- package/dist/templates.js.map +1 -0
- package/dist/typescript.d.ts +9 -0
- package/dist/typescript.d.ts.map +1 -0
- package/dist/typescript.js +60 -0
- package/dist/typescript.js.map +1 -0
- package/package.json +72 -4
- package/src/bin.ts +12 -0
- package/src/changes.ts +170 -0
- package/src/collection.ts +228 -0
- package/src/config.ts +142 -0
- package/src/diff.ts +90 -0
- package/src/edit.ts +812 -0
- package/src/exit.ts +19 -0
- package/src/layout.ts +91 -0
- package/src/main.ts +71 -0
- package/src/migrate.ts +155 -0
- package/src/migration.ts +239 -0
- package/src/names.ts +48 -0
- package/src/templates.ts +104 -0
- package/src/typescript.ts +79 -0
package/src/exit.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ends a command: 1 for a refusal or a failure, 2 for a usage error. The
|
|
3
|
+
* message is the `lattice: <why>` line on stderr. `details` goes to stdout
|
|
4
|
+
* after it, such as the lines a refused edit would have added.
|
|
5
|
+
*/
|
|
6
|
+
export class Exit extends Error {
|
|
7
|
+
constructor(
|
|
8
|
+
message: string,
|
|
9
|
+
readonly code: 1 | 2,
|
|
10
|
+
readonly details = '',
|
|
11
|
+
) {
|
|
12
|
+
super(message);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Whether `value` is a plain object, as JSON parses one. */
|
|
17
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
18
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
package/src/layout.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Generated lines follow Biome's defaults (line width 80), so an app that
|
|
2
|
+
// runs Biome or Prettier finds nothing to change in a typical edit. Only the
|
|
3
|
+
// breaks the CLI's own lines need are here, one level deep: a name long
|
|
4
|
+
// enough to need a second level is left for the app's formatter.
|
|
5
|
+
|
|
6
|
+
const width = 80;
|
|
7
|
+
|
|
8
|
+
/** Whether a line fits Biome's default width. */
|
|
9
|
+
const fits = (line: string) => line.length <= width;
|
|
10
|
+
|
|
11
|
+
/** An object argument: its property lines, and whether it stays expanded. */
|
|
12
|
+
export type ObjectArg = {
|
|
13
|
+
/** Its property lines at `indent`, each ending in a comma. */
|
|
14
|
+
readonly lines: (indent: string) => readonly string[];
|
|
15
|
+
/** Whether it is written over several lines, which Biome keeps. */
|
|
16
|
+
readonly expanded: boolean;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type Arg = string | ObjectArg;
|
|
20
|
+
|
|
21
|
+
/** `{ a: 1, b: 2 }`: an object's property lines on one line. */
|
|
22
|
+
function inline(object: ObjectArg): string {
|
|
23
|
+
const props = object.lines('').map((line) => line.replace(/,$/, ''));
|
|
24
|
+
return `{ ${props.join(', ')} }`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A call, as Biome lays it out: on one line if it fits; else hugging a last
|
|
29
|
+
* object argument, if the line up to its `{` fits; else one argument per
|
|
30
|
+
* line. `tail` follows the closing parenthesis, such as `;`.
|
|
31
|
+
*/
|
|
32
|
+
export function call(
|
|
33
|
+
indent: string,
|
|
34
|
+
head: string,
|
|
35
|
+
args: readonly Arg[],
|
|
36
|
+
tail: string,
|
|
37
|
+
unit = ' ',
|
|
38
|
+
): string[] {
|
|
39
|
+
const last = args.at(-1);
|
|
40
|
+
const first = args.slice(0, -1);
|
|
41
|
+
if (args.every((arg) => typeof arg === 'string' || !arg.expanded)) {
|
|
42
|
+
const one = `${indent}${head}(${args
|
|
43
|
+
.map((arg) => (typeof arg === 'string' ? arg : inline(arg)))
|
|
44
|
+
.join(', ')})${tail}`;
|
|
45
|
+
if (fits(one)) return [one];
|
|
46
|
+
}
|
|
47
|
+
if (last !== undefined && typeof last !== 'string') {
|
|
48
|
+
const open = `${indent}${head}(${[...first, '{'].join(', ')}`;
|
|
49
|
+
if (first.every((arg) => typeof arg === 'string') && fits(open)) {
|
|
50
|
+
return [open, ...last.lines(indent + unit), `${indent}})${tail}`];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const inner = indent + unit;
|
|
54
|
+
return [
|
|
55
|
+
`${indent}${head}(`,
|
|
56
|
+
...args.flatMap((arg) =>
|
|
57
|
+
typeof arg === 'string'
|
|
58
|
+
? [`${inner}${arg},`]
|
|
59
|
+
: [`${inner}{`, ...arg.lines(inner + unit), `${inner}},`],
|
|
60
|
+
),
|
|
61
|
+
`${indent})${tail}`,
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** `key: value,`, or the value on the next line when it does not fit. */
|
|
66
|
+
export function entry(
|
|
67
|
+
indent: string,
|
|
68
|
+
key: string,
|
|
69
|
+
value: string,
|
|
70
|
+
unit = ' ',
|
|
71
|
+
): string[] {
|
|
72
|
+
const one = `${indent}${key}: ${value},`;
|
|
73
|
+
return fits(one) ? [one] : [`${indent}${key}:`, `${indent}${unit}${value},`];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `key: { a, b },`, or the object's properties on their own lines. */
|
|
77
|
+
export function objectEntry(
|
|
78
|
+
indent: string,
|
|
79
|
+
key: string,
|
|
80
|
+
props: readonly string[],
|
|
81
|
+
unit = ' ',
|
|
82
|
+
): string[] {
|
|
83
|
+
const one = `${indent}${key}: { ${props.join(', ')} },`;
|
|
84
|
+
return fits(one)
|
|
85
|
+
? [one]
|
|
86
|
+
: [
|
|
87
|
+
`${indent}${key}: {`,
|
|
88
|
+
...props.map((prop) => `${indent}${unit}${prop},`),
|
|
89
|
+
`${indent}},`,
|
|
90
|
+
];
|
|
91
|
+
}
|
package/src/main.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { collectionCommand, collectionUsage } from './collection.js';
|
|
2
|
+
import { Exit } from './exit.js';
|
|
3
|
+
import { migrateCommand, migrateUsage } from './migrate.js';
|
|
4
|
+
import { migrationCommand, migrationUsage } from './migration.js';
|
|
5
|
+
|
|
6
|
+
export const help = `Usage: lattice <command> [options]
|
|
7
|
+
|
|
8
|
+
Commands:
|
|
9
|
+
collection <slug> Add a collection, its test, and its registrations.
|
|
10
|
+
migration <name> Add the next data migration to the list.
|
|
11
|
+
migrate Run the pending migrations, from the built app.
|
|
12
|
+
|
|
13
|
+
Run lattice <command> --help for a command's options.
|
|
14
|
+
`;
|
|
15
|
+
|
|
16
|
+
const commands: Record<
|
|
17
|
+
string,
|
|
18
|
+
{
|
|
19
|
+
readonly usage: string;
|
|
20
|
+
readonly run: (args: readonly string[], cwd: string) => Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
> = {
|
|
23
|
+
collection: { usage: collectionUsage, run: collectionCommand },
|
|
24
|
+
migration: { usage: migrationUsage, run: migrationCommand },
|
|
25
|
+
migrate: { usage: migrateUsage, run: migrateCommand },
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** The first sentence of parseArgs' message, which goes on to explain `--`. */
|
|
29
|
+
const firstSentence = (message: string) => message.split(/\.\s/)[0] ?? message;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Runs the command `args` names, in `cwd`, and returns the exit code: 0
|
|
33
|
+
* done, 1 refused or failed, 2 a usage error.
|
|
34
|
+
*/
|
|
35
|
+
export async function main(
|
|
36
|
+
args: readonly string[],
|
|
37
|
+
cwd: string,
|
|
38
|
+
): Promise<number> {
|
|
39
|
+
const [name, ...rest] = args;
|
|
40
|
+
if (name === undefined || name === '--help' || name === '-h') {
|
|
41
|
+
process.stdout.write(help);
|
|
42
|
+
return name === undefined ? 2 : 0;
|
|
43
|
+
}
|
|
44
|
+
const command = commands[name];
|
|
45
|
+
if (command === undefined) {
|
|
46
|
+
process.stderr.write(`lattice: unknown command "${name}"\n\n${help}`);
|
|
47
|
+
return 2;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
await command.run(rest, cwd);
|
|
51
|
+
return 0;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (error instanceof Exit) {
|
|
54
|
+
process.stderr.write(`lattice: ${error.message}\n`);
|
|
55
|
+
if (error.code === 2) process.stderr.write(`${command.usage}\n`);
|
|
56
|
+
if (error.details !== '') process.stdout.write(`${error.details}\n`);
|
|
57
|
+
return error.code;
|
|
58
|
+
}
|
|
59
|
+
// parseArgs throws a TypeError for an unknown flag or a missing value.
|
|
60
|
+
if (error instanceof TypeError && 'code' in error) {
|
|
61
|
+
process.stderr.write(
|
|
62
|
+
`lattice: ${firstSentence(error.message)}\n${command.usage}\n`,
|
|
63
|
+
);
|
|
64
|
+
return 2;
|
|
65
|
+
}
|
|
66
|
+
process.stderr.write(
|
|
67
|
+
`lattice: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
68
|
+
);
|
|
69
|
+
return 1;
|
|
70
|
+
}
|
|
71
|
+
}
|
package/src/migrate.ts
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import type * as HexokLogger from '@hexok/logger';
|
|
7
|
+
import type * as StoreMongo from '@latticecms/store-mongo';
|
|
8
|
+
import { shown } from './changes.js';
|
|
9
|
+
import { loadConfig } from './config.js';
|
|
10
|
+
import { Exit, isRecord } from './exit.js';
|
|
11
|
+
|
|
12
|
+
export const migrateUsage = 'Usage: lattice migrate';
|
|
13
|
+
|
|
14
|
+
export const migrateHelp = `${migrateUsage}
|
|
15
|
+
|
|
16
|
+
Runs the app's pending migrations with @latticecms/store-mongo's migrate(),
|
|
17
|
+
from the module "lattice.migrate" in package.json names (a built file that
|
|
18
|
+
exports store and migrations). Build the app first.
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
const options = { help: { type: 'boolean', short: 'h' } } as const;
|
|
22
|
+
|
|
23
|
+
/** A package's entry, resolved and imported from the app's directory. */
|
|
24
|
+
async function fromApp(
|
|
25
|
+
root: string,
|
|
26
|
+
name: string,
|
|
27
|
+
install: string,
|
|
28
|
+
): Promise<unknown> {
|
|
29
|
+
let resolved: string;
|
|
30
|
+
try {
|
|
31
|
+
resolved = createRequire(join(root, 'package.json')).resolve(name);
|
|
32
|
+
} catch {
|
|
33
|
+
throw new Exit(`${name} is not installed in the app: run ${install}`, 1);
|
|
34
|
+
}
|
|
35
|
+
return import(pathToFileURL(resolved).href);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Each guard checks what the command uses of the package.
|
|
39
|
+
function isStoreMongo(value: unknown): value is typeof StoreMongo {
|
|
40
|
+
return (
|
|
41
|
+
isRecord(value) &&
|
|
42
|
+
typeof value.migrate === 'function' &&
|
|
43
|
+
typeof value.MongoStore === 'function' &&
|
|
44
|
+
typeof value.MigrationError === 'function'
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isLogger(value: unknown): value is typeof HexokLogger {
|
|
49
|
+
return isRecord(value) && typeof value.ConsoleLogger === 'function';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Whether `value` is a migration as migrate() takes one. */
|
|
53
|
+
function isMigration(value: unknown): value is StoreMongo.Migration {
|
|
54
|
+
return (
|
|
55
|
+
isRecord(value) &&
|
|
56
|
+
typeof value.id === 'number' &&
|
|
57
|
+
typeof value.name === 'string' &&
|
|
58
|
+
typeof value.up === 'function' &&
|
|
59
|
+
(value.transaction === undefined || typeof value.transaction === 'boolean')
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One line for an error: a MigrationError's message and data, or the message. */
|
|
64
|
+
function lineOf(storeMongo: typeof StoreMongo, error: unknown): string {
|
|
65
|
+
if (storeMongo.MigrationError.is(error)) {
|
|
66
|
+
const data = 'data' in error ? JSON.stringify(error.data) : undefined;
|
|
67
|
+
return data === undefined || data === '{}'
|
|
68
|
+
? error.message
|
|
69
|
+
: `${error.message} ${data}`;
|
|
70
|
+
}
|
|
71
|
+
return error instanceof Error ? error.message : String(error);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* `lattice migrate`: imports the app's built module, starts its store, runs
|
|
76
|
+
* migrate() with a console logger, and stops the store. Ordering, history
|
|
77
|
+
* and the lock are migrate()'s.
|
|
78
|
+
*/
|
|
79
|
+
export async function migrateCommand(
|
|
80
|
+
args: readonly string[],
|
|
81
|
+
cwd: string,
|
|
82
|
+
): Promise<void> {
|
|
83
|
+
const { values: flags, positionals } = parseArgs({
|
|
84
|
+
args: [...args],
|
|
85
|
+
options,
|
|
86
|
+
allowPositionals: true,
|
|
87
|
+
strict: true,
|
|
88
|
+
});
|
|
89
|
+
if (flags.help === true) {
|
|
90
|
+
process.stdout.write(migrateHelp);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (positionals.length > 0) throw new Exit('migrate takes no arguments', 2);
|
|
94
|
+
const config = await loadConfig(cwd);
|
|
95
|
+
const { root } = config;
|
|
96
|
+
const path = config.paths.migrate;
|
|
97
|
+
const file = shown(root, path);
|
|
98
|
+
|
|
99
|
+
const storeMongo = await fromApp(
|
|
100
|
+
root,
|
|
101
|
+
'@latticecms/store-mongo',
|
|
102
|
+
'npm install @latticecms/store-mongo',
|
|
103
|
+
);
|
|
104
|
+
if (!isStoreMongo(storeMongo)) {
|
|
105
|
+
throw new Exit('@latticecms/store-mongo in the app has no migrate()', 1);
|
|
106
|
+
}
|
|
107
|
+
const loggers = await fromApp(
|
|
108
|
+
root,
|
|
109
|
+
'@hexok/logger',
|
|
110
|
+
'npm install @hexok/logger',
|
|
111
|
+
);
|
|
112
|
+
if (!isLogger(loggers)) {
|
|
113
|
+
throw new Exit('@hexok/logger in the app has no ConsoleLogger', 1);
|
|
114
|
+
}
|
|
115
|
+
if (!existsSync(path)) {
|
|
116
|
+
throw new Exit(
|
|
117
|
+
`${file} does not exist: build the app first, or set "lattice.migrate" in ${config.manifest}`,
|
|
118
|
+
1,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
let module: unknown;
|
|
122
|
+
try {
|
|
123
|
+
module = await import(pathToFileURL(path).href);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
throw new Exit(`cannot load ${file}: ${lineOf(storeMongo, error)}`, 1);
|
|
126
|
+
}
|
|
127
|
+
const store = isRecord(module) ? module.store : undefined;
|
|
128
|
+
const migrations = isRecord(module) ? module.migrations : undefined;
|
|
129
|
+
if (!(store instanceof storeMongo.MongoStore)) {
|
|
130
|
+
throw new Exit(
|
|
131
|
+
`${file} must export store, a MongoStore that is not started`,
|
|
132
|
+
1,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
if (!Array.isArray(migrations) || !migrations.every(isMigration)) {
|
|
136
|
+
throw new Exit(
|
|
137
|
+
`${file} must export migrations, the list of migrations migrate() runs`,
|
|
138
|
+
1,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// migrate() logs each migration it runs, with its duration, and
|
|
143
|
+
// "migrations up to date" when none is pending, so the command adds no
|
|
144
|
+
// lines of its own.
|
|
145
|
+
try {
|
|
146
|
+
await store.start();
|
|
147
|
+
await storeMongo.migrate(store, migrations, {
|
|
148
|
+
logger: new loggers.ConsoleLogger(),
|
|
149
|
+
});
|
|
150
|
+
} catch (error) {
|
|
151
|
+
throw new Exit(lineOf(storeMongo, error), 1);
|
|
152
|
+
} finally {
|
|
153
|
+
await store.stop();
|
|
154
|
+
}
|
|
155
|
+
}
|
package/src/migration.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import type * as TS from 'typescript';
|
|
6
|
+
import { apply, shown } from './changes.js';
|
|
7
|
+
import { existing, loadConfig } from './config.js';
|
|
8
|
+
import {
|
|
9
|
+
type ListElement,
|
|
10
|
+
migrationList,
|
|
11
|
+
migrationsEdit,
|
|
12
|
+
parse,
|
|
13
|
+
} from './edit.js';
|
|
14
|
+
import { Exit } from './exit.js';
|
|
15
|
+
import { call } from './layout.js';
|
|
16
|
+
import { loadTypeScript, type TypeScript } from './typescript.js';
|
|
17
|
+
|
|
18
|
+
export const migrationUsage =
|
|
19
|
+
'Usage: lattice migration <name> [--transaction] [--dry-run]';
|
|
20
|
+
|
|
21
|
+
export const migrationHelp = `${migrationUsage}
|
|
22
|
+
|
|
23
|
+
Adds a data migration: its file, with the next id, and its place at the end
|
|
24
|
+
of the list that migrate() runs.
|
|
25
|
+
|
|
26
|
+
<name> Kebab case: add-notes-index.
|
|
27
|
+
--transaction Run it and its record in one transaction (a replica set).
|
|
28
|
+
--dry-run Print the changes as a diff and write nothing.
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
const options = {
|
|
32
|
+
transaction: { type: 'boolean' },
|
|
33
|
+
'dry-run': { type: 'boolean' },
|
|
34
|
+
help: { type: 'boolean', short: 'h' },
|
|
35
|
+
} as const;
|
|
36
|
+
|
|
37
|
+
/** How many digits an id has in a file name, as the crm's `0001-…` have. */
|
|
38
|
+
const digits = 4;
|
|
39
|
+
|
|
40
|
+
/** The object a default export holds, under `satisfies`, `as` and parentheses. */
|
|
41
|
+
function exported(
|
|
42
|
+
ts: TypeScript,
|
|
43
|
+
source: TS.SourceFile,
|
|
44
|
+
): TS.ObjectLiteralExpression | undefined {
|
|
45
|
+
for (const statement of source.statements) {
|
|
46
|
+
if (!ts.isExportAssignment(statement) || statement.isExportEquals) continue;
|
|
47
|
+
let value: TS.Expression = statement.expression;
|
|
48
|
+
while (
|
|
49
|
+
ts.isSatisfiesExpression(value) ||
|
|
50
|
+
ts.isAsExpression(value) ||
|
|
51
|
+
ts.isParenthesizedExpression(value)
|
|
52
|
+
) {
|
|
53
|
+
value = value.expression;
|
|
54
|
+
}
|
|
55
|
+
return ts.isObjectLiteralExpression(value) ? value : undefined;
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A listed migration's id and name, read from its file's default export. */
|
|
61
|
+
async function readMigration(
|
|
62
|
+
ts: TypeScript,
|
|
63
|
+
root: string,
|
|
64
|
+
index: string,
|
|
65
|
+
element: ListElement,
|
|
66
|
+
): Promise<{ readonly id: number; readonly name: string }> {
|
|
67
|
+
const path = resolve(
|
|
68
|
+
dirname(index),
|
|
69
|
+
element.specifier.replace(/\.js$/, '.ts'),
|
|
70
|
+
);
|
|
71
|
+
const file = shown(root, path);
|
|
72
|
+
const text = await readFile(path, 'utf8').catch(() => undefined);
|
|
73
|
+
if (text === undefined) {
|
|
74
|
+
throw new Exit(`${file}, which the list imports, does not exist`, 1);
|
|
75
|
+
}
|
|
76
|
+
const object = exported(ts, parse(ts, path, text));
|
|
77
|
+
const value = (key: string) =>
|
|
78
|
+
object?.properties.find(
|
|
79
|
+
(property): property is TS.PropertyAssignment =>
|
|
80
|
+
ts.isPropertyAssignment(property) &&
|
|
81
|
+
ts.isIdentifier(property.name) &&
|
|
82
|
+
property.name.text === key,
|
|
83
|
+
)?.initializer;
|
|
84
|
+
const id = value('id');
|
|
85
|
+
const name = value('name');
|
|
86
|
+
if (
|
|
87
|
+
id === undefined ||
|
|
88
|
+
!ts.isNumericLiteral(id) ||
|
|
89
|
+
name === undefined ||
|
|
90
|
+
!ts.isStringLiteral(name)
|
|
91
|
+
) {
|
|
92
|
+
throw new Exit(
|
|
93
|
+
`cannot read the id and name of ${file}: its default export needs a numeric id and a string name`,
|
|
94
|
+
1,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
return { id: Number(id.text), name: name.text };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The list's own checks, as migrate() makes them: ids 1, 2, 3 … in order,
|
|
102
|
+
* none twice. The words are migrate()'s, with the error it would throw.
|
|
103
|
+
*/
|
|
104
|
+
function checkIds(file: string, ids: readonly number[]): void {
|
|
105
|
+
const seen = new Set<number>();
|
|
106
|
+
for (const id of ids) {
|
|
107
|
+
if (seen.has(id)) {
|
|
108
|
+
throw new Exit(
|
|
109
|
+
`two migrations in ${file} share an id: ${id} (migrate() throws MigrationError.Duplicate)`,
|
|
110
|
+
1,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
seen.add(id);
|
|
114
|
+
}
|
|
115
|
+
ids.forEach((id, index) => {
|
|
116
|
+
if (id !== index + 1) {
|
|
117
|
+
throw new Exit(
|
|
118
|
+
`migration ids in ${file} must run 1, 2, 3 … in list order, with no gap: expected ${index + 1}, found ${id} (migrate() throws MigrationError.Gap)`,
|
|
119
|
+
1,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A new migration: its id and name, and `transaction` when asked. Its `up`
|
|
127
|
+
* throws until it is written, so a build that runs it early fails instead
|
|
128
|
+
* of recording it as done.
|
|
129
|
+
*/
|
|
130
|
+
function migrationText(id: number, name: string, transaction: boolean): string {
|
|
131
|
+
return [
|
|
132
|
+
"import type { Migration } from '@latticecms/store-mongo';",
|
|
133
|
+
'',
|
|
134
|
+
'/**',
|
|
135
|
+
' * What this migration changes, and why. `up` must be safe to run again',
|
|
136
|
+
' * after it failed partway: the next run retries it.',
|
|
137
|
+
' *',
|
|
138
|
+
" * `up({ db, session, signal, logger })` receives the store's raw `db`,",
|
|
139
|
+
" * whose documents are in their stored shape; the transaction's `session`",
|
|
140
|
+
' * when `transaction` is true, to pass to each call; a `signal` that aborts',
|
|
141
|
+
' * when the migrations lock is lost, to check in long loops; and a',
|
|
142
|
+
" * `logger` with the migration's id and name.",
|
|
143
|
+
' */',
|
|
144
|
+
'export default {',
|
|
145
|
+
` id: ${id},`,
|
|
146
|
+
` name: '${name}',`,
|
|
147
|
+
...(transaction ? [' transaction: true,'] : []),
|
|
148
|
+
' async up() {',
|
|
149
|
+
...call(
|
|
150
|
+
' ',
|
|
151
|
+
'throw new Error',
|
|
152
|
+
[
|
|
153
|
+
`'Migration ${id} ${name} is not written yet: write up() before running it.'`,
|
|
154
|
+
],
|
|
155
|
+
';',
|
|
156
|
+
),
|
|
157
|
+
' },',
|
|
158
|
+
'} satisfies Migration;',
|
|
159
|
+
'',
|
|
160
|
+
].join('\n');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** `lattice migration`: writes the next migration and appends it to the list. */
|
|
164
|
+
export async function migrationCommand(
|
|
165
|
+
args: readonly string[],
|
|
166
|
+
cwd: string,
|
|
167
|
+
): Promise<void> {
|
|
168
|
+
const { values: flags, positionals } = parseArgs({
|
|
169
|
+
args: [...args],
|
|
170
|
+
options,
|
|
171
|
+
allowPositionals: true,
|
|
172
|
+
strict: true,
|
|
173
|
+
});
|
|
174
|
+
if (flags.help === true) {
|
|
175
|
+
process.stdout.write(migrationHelp);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const [name, ...extra] = positionals;
|
|
179
|
+
if (name === undefined || extra.length > 0) {
|
|
180
|
+
throw new Exit(
|
|
181
|
+
name === undefined
|
|
182
|
+
? 'migration needs a name'
|
|
183
|
+
: 'migration takes one name',
|
|
184
|
+
2,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(name)) {
|
|
188
|
+
throw new Exit(
|
|
189
|
+
`"${name}" is not a migration name: use kebab case, as add-notes-index`,
|
|
190
|
+
2,
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
const config = await loadConfig(cwd);
|
|
194
|
+
const { root } = config;
|
|
195
|
+
const directory = await existing(config, 'migrations', 'directory');
|
|
196
|
+
const index = join(directory, 'index.ts');
|
|
197
|
+
const file = shown(root, index);
|
|
198
|
+
if (!existsSync(index)) {
|
|
199
|
+
throw new Exit(`${file} does not exist: the migrations list goes there`, 1);
|
|
200
|
+
}
|
|
201
|
+
const ts = loadTypeScript(root);
|
|
202
|
+
const before = await readFile(index, 'utf8');
|
|
203
|
+
const list = migrationList(ts, parse(ts, index, before), file);
|
|
204
|
+
if (typeof list === 'string') throw new Exit(list, 1);
|
|
205
|
+
|
|
206
|
+
const listed = await Promise.all(
|
|
207
|
+
list.elements.map((element) => readMigration(ts, root, index, element)),
|
|
208
|
+
);
|
|
209
|
+
checkIds(
|
|
210
|
+
file,
|
|
211
|
+
listed.map(({ id }) => id),
|
|
212
|
+
);
|
|
213
|
+
if (listed.some((migration) => migration.name === name)) {
|
|
214
|
+
throw new Exit(`${file} already lists a migration named ${name}`, 1);
|
|
215
|
+
}
|
|
216
|
+
const taken = (await readdir(directory)).find(
|
|
217
|
+
(entry) => entry.replace(/^\d+-/, '').replace(/\.[cm]?tsx?$/, '') === name,
|
|
218
|
+
);
|
|
219
|
+
if (taken !== undefined) {
|
|
220
|
+
throw new Exit(`${shown(root, join(directory, taken))} already exists`, 1);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const id = listed.length + 1;
|
|
224
|
+
const base = `${String(id).padStart(digits, '0')}-${name}`;
|
|
225
|
+
const path = join(directory, `${base}.ts`);
|
|
226
|
+
const local = `m${String(id).padStart(digits, '0')}`;
|
|
227
|
+
await apply(
|
|
228
|
+
root,
|
|
229
|
+
[
|
|
230
|
+
{
|
|
231
|
+
path,
|
|
232
|
+
before: undefined,
|
|
233
|
+
after: migrationText(id, name, flags.transaction === true),
|
|
234
|
+
},
|
|
235
|
+
],
|
|
236
|
+
[migrationsEdit(ts, index, file, before, list, local, `./${base}.js`)],
|
|
237
|
+
flags['dry-run'] === true,
|
|
238
|
+
);
|
|
239
|
+
}
|
package/src/names.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { reservedFields, reservedNames } from '@latticecms/core';
|
|
2
|
+
import { Exit } from './exit.js';
|
|
3
|
+
|
|
4
|
+
/** What a slug becomes: its file name, its export and its events' prefix. */
|
|
5
|
+
export type Names = {
|
|
6
|
+
readonly slug: string;
|
|
7
|
+
/** Kebab case, without an extension: `deal-notes`. */
|
|
8
|
+
readonly file: string;
|
|
9
|
+
/** Pascal case: `DealNotes`. */
|
|
10
|
+
readonly exportName: string;
|
|
11
|
+
/** Camel case, the events' prefix: `dealNotes`. */
|
|
12
|
+
readonly camel: string;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Lower snake case: a MongoDB collection, a URL segment and a label. */
|
|
16
|
+
const slugPattern = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;
|
|
17
|
+
|
|
18
|
+
/** The names of a slug, or a refusal when the slug breaks the rule. */
|
|
19
|
+
export function namesOf(slug: string): Names {
|
|
20
|
+
if (!slugPattern.test(slug)) {
|
|
21
|
+
throw new Exit(
|
|
22
|
+
`"${slug}" is not a slug: use lower snake case, as deal_notes`,
|
|
23
|
+
1,
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
if (reservedNames.some((name) => name === slug)) {
|
|
27
|
+
throw new Exit(`"${slug}" is reserved: a ts-pf implementer key`, 1);
|
|
28
|
+
}
|
|
29
|
+
const words = slug.split('_');
|
|
30
|
+
const upper = (word: string) => `${word[0]?.toUpperCase()}${word.slice(1)}`;
|
|
31
|
+
return {
|
|
32
|
+
slug,
|
|
33
|
+
file: words.join('-'),
|
|
34
|
+
exportName: words.map(upper).join(''),
|
|
35
|
+
camel: `${words[0]}${words.slice(1).map(upper).join('')}`,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Why `name` cannot be a field, such as the tenant field, or undefined when it can. */
|
|
40
|
+
export function fieldProblem(name: string): string | undefined {
|
|
41
|
+
if (reservedFields.some((field) => field === name)) {
|
|
42
|
+
return `"${name}" is a reserved field name`;
|
|
43
|
+
}
|
|
44
|
+
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name)) {
|
|
45
|
+
return `"${name}" is not a field name`;
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|