@opencloudcms/codegen 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 +4 -2
- package/dist/blocks.d.ts +58 -0
- package/dist/blocks.js +408 -0
- package/dist/blocks.js.map +1 -0
- package/dist/codegen.d.ts +10 -0
- package/dist/codegen.js +236 -0
- package/dist/codegen.js.map +1 -0
- package/dist/ddl.d.ts +67 -0
- package/dist/ddl.js +185 -0
- package/dist/ddl.js.map +1 -0
- package/dist/diff.d.ts +52 -0
- package/dist/diff.js +158 -0
- package/dist/diff.js.map +1 -0
- package/dist/eject.d.ts +20 -0
- package/dist/eject.js +773 -0
- package/dist/eject.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/loader.d.ts +17 -0
- package/dist/loader.js +134 -0
- package/dist/loader.js.map +1 -0
- package/dist/migration-file.d.ts +9 -0
- package/dist/migration-file.js +52 -0
- package/dist/migration-file.js.map +1 -0
- package/dist/pipeline.d.ts +78 -0
- package/dist/pipeline.js +227 -0
- package/dist/pipeline.js.map +1 -0
- package/dist/plan.d.ts +11 -0
- package/dist/plan.js +217 -0
- package/dist/plan.js.map +1 -0
- package/dist/printer.d.ts +11 -0
- package/dist/printer.js +127 -0
- package/dist/printer.js.map +1 -0
- package/dist/snapshot.d.ts +11 -0
- package/dist/snapshot.js +60 -0
- package/dist/snapshot.js.map +1 -0
- package/package.json +33 -3
package/dist/pipeline.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.nextMigrationStamp = nextMigrationStamp;
|
|
37
|
+
exports.computePlan = computePlan;
|
|
38
|
+
exports.createMigration = createMigration;
|
|
39
|
+
exports.generate = generate;
|
|
40
|
+
exports.checkSchema = checkSchema;
|
|
41
|
+
exports.captureProjectFiles = captureProjectFiles;
|
|
42
|
+
exports.restoreProjectFiles = restoreProjectFiles;
|
|
43
|
+
exports.definitionsWith = definitionsWith;
|
|
44
|
+
exports.previewChange = previewChange;
|
|
45
|
+
exports.writeSchemaChange = writeSchemaChange;
|
|
46
|
+
/**
|
|
47
|
+
* The one pipeline shared by the CLI and the admin UI:
|
|
48
|
+
*
|
|
49
|
+
* schema files -> validate -> diff with _snapshot.json -> migration file
|
|
50
|
+
* -> src/generated/*
|
|
51
|
+
* -> _snapshot.json
|
|
52
|
+
*
|
|
53
|
+
* The UI never runs DDL directly: it writes a schema file and calls this.
|
|
54
|
+
*/
|
|
55
|
+
const fs = __importStar(require("node:fs"));
|
|
56
|
+
const path = __importStar(require("node:path"));
|
|
57
|
+
const schema_1 = require("@opencloudcms/schema");
|
|
58
|
+
const codegen_1 = require("./codegen");
|
|
59
|
+
const ddl_1 = require("./ddl");
|
|
60
|
+
const diff_1 = require("./diff");
|
|
61
|
+
const loader_1 = require("./loader");
|
|
62
|
+
const migration_file_1 = require("./migration-file");
|
|
63
|
+
const plan_1 = require("./plan");
|
|
64
|
+
const printer_1 = require("./printer");
|
|
65
|
+
const snapshot_1 = require("./snapshot");
|
|
66
|
+
/**
|
|
67
|
+
* Migrations run in file-name order, so a new stamp must sort after every
|
|
68
|
+
* existing migration (two changes within the same second would otherwise
|
|
69
|
+
* be ordered by name).
|
|
70
|
+
*/
|
|
71
|
+
function nextMigrationStamp(migrationsDir, now = new Date()) {
|
|
72
|
+
const stamp = (0, migration_file_1.migrationStamp)(now);
|
|
73
|
+
const existing = fs.existsSync(migrationsDir)
|
|
74
|
+
? fs.readdirSync(migrationsDir).map((f) => /^(\d{14})_/.exec(f)?.[1]).filter((s) => !!s).sort()
|
|
75
|
+
: [];
|
|
76
|
+
const latest = existing.at(-1);
|
|
77
|
+
if (!latest || stamp > latest)
|
|
78
|
+
return stamp;
|
|
79
|
+
const d = new Date(Date.UTC(+latest.slice(0, 4), +latest.slice(4, 6) - 1, +latest.slice(6, 8), +latest.slice(8, 10), +latest.slice(10, 12), +latest.slice(12, 14) + 1));
|
|
80
|
+
return (0, migration_file_1.migrationStamp)(d);
|
|
81
|
+
}
|
|
82
|
+
async function computePlan(config, opts = {}) {
|
|
83
|
+
const definitions = opts.definitions ?? (await (0, loader_1.loadDefinitions)(config)).map((l) => l.def);
|
|
84
|
+
(0, loader_1.assertNoCoreApiIds)(definitions);
|
|
85
|
+
(0, schema_1.assertValidSchema)(definitions, await (0, loader_1.loadContentGroups)(config));
|
|
86
|
+
const snapshot = (0, snapshot_1.readSnapshot)(config.migrationsDir);
|
|
87
|
+
const diff = (0, diff_1.diffSchemas)(snapshot.contentTypes, definitions);
|
|
88
|
+
const stamp = nextMigrationStamp(config.migrationsDir, opts.now);
|
|
89
|
+
const plan = (0, plan_1.planMigration)(diff.operations, stamp);
|
|
90
|
+
return { definitions, snapshot, diff, plan, stamp, sql: plan.up.map(ddl_1.compileStatement) };
|
|
91
|
+
}
|
|
92
|
+
async function createMigration(config, opts = {}) {
|
|
93
|
+
const result = await computePlan(config, opts);
|
|
94
|
+
const generated = (0, codegen_1.writeGeneratedFiles)((0, codegen_1.generateCode)(result.definitions, config.generatedDir));
|
|
95
|
+
if (!result.diff.changed)
|
|
96
|
+
return { status: 'up-to-date', generated };
|
|
97
|
+
if (result.diff.operations.length === 0 || result.plan.up.length === 0) {
|
|
98
|
+
(0, snapshot_1.writeSnapshot)(config.migrationsDir, { ...result.snapshot, contentTypes: result.definitions });
|
|
99
|
+
return { status: 'metadata-only', generated, plan: result };
|
|
100
|
+
}
|
|
101
|
+
const name = opts.name ? (0, migration_file_1.slugifyMigrationName)(opts.name) : (0, migration_file_1.suggestMigrationName)(result.plan);
|
|
102
|
+
fs.mkdirSync(config.migrationsDir, { recursive: true });
|
|
103
|
+
let file = path.join(config.migrationsDir, `${result.stamp}_${name}.ts`);
|
|
104
|
+
for (let i = 2; fs.existsSync(file); i++)
|
|
105
|
+
file = path.join(config.migrationsDir, `${result.stamp}_${name}_${i}.ts`);
|
|
106
|
+
fs.writeFileSync(file, (0, migration_file_1.renderMigrationFile)(result.plan, { name, generatedAt: new Date().toISOString() }));
|
|
107
|
+
(0, snapshot_1.writeSnapshot)(config.migrationsDir, {
|
|
108
|
+
version: 1,
|
|
109
|
+
lastMigration: path.basename(file, '.ts'),
|
|
110
|
+
contentTypes: result.definitions,
|
|
111
|
+
});
|
|
112
|
+
return { status: 'created', file, generated, plan: result };
|
|
113
|
+
}
|
|
114
|
+
async function generate(config) {
|
|
115
|
+
const definitions = (await (0, loader_1.loadDefinitions)(config)).map((l) => l.def);
|
|
116
|
+
(0, schema_1.assertValidSchema)(definitions, await (0, loader_1.loadContentGroups)(config));
|
|
117
|
+
return { definitions, changed: (0, codegen_1.writeGeneratedFiles)((0, codegen_1.generateCode)(definitions, config.generatedDir)) };
|
|
118
|
+
}
|
|
119
|
+
/** For CI: fails when definitions changed without a migration, or generated code is stale. */
|
|
120
|
+
async function checkSchema(config) {
|
|
121
|
+
const problems = [];
|
|
122
|
+
const result = await computePlan(config);
|
|
123
|
+
if (result.diff.changed) {
|
|
124
|
+
problems.push(result.diff.operations.length
|
|
125
|
+
? `Schema changed without a migration (${result.plan.summary.join('; ')}). Run \`opencloudcms migrate:create\`.`
|
|
126
|
+
: 'Schema metadata changed; run `opencloudcms migrate:create` to update migrations/_snapshot.json.');
|
|
127
|
+
}
|
|
128
|
+
for (const f of (0, codegen_1.staleGeneratedFiles)((0, codegen_1.generateCode)(result.definitions, config.generatedDir))) {
|
|
129
|
+
problems.push(`Generated file is stale: ${path.relative(config.root, f)}. Run \`opencloudcms generate\`.`);
|
|
130
|
+
}
|
|
131
|
+
return { ok: problems.length === 0, problems };
|
|
132
|
+
}
|
|
133
|
+
/** Directories that existed (under the extra dirs) when a snapshot was captured. */
|
|
134
|
+
const snapshotDirs = new WeakMap();
|
|
135
|
+
function listFiles(dir) {
|
|
136
|
+
if (!fs.existsSync(dir))
|
|
137
|
+
return [];
|
|
138
|
+
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
|
|
139
|
+
const p = path.join(dir, e.name);
|
|
140
|
+
return e.isDirectory() ? listFiles(p) : [p];
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function listDirs(dir) {
|
|
144
|
+
if (!fs.existsSync(dir))
|
|
145
|
+
return [];
|
|
146
|
+
return [dir, ...fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? listDirs(path.join(dir, e.name)) : []))];
|
|
147
|
+
}
|
|
148
|
+
/** Removes directories that are empty and were not present at capture (deepest first). */
|
|
149
|
+
function pruneNewEmptyDirs(dir, existed) {
|
|
150
|
+
if (!fs.existsSync(dir))
|
|
151
|
+
return;
|
|
152
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
153
|
+
if (e.isDirectory())
|
|
154
|
+
pruneNewEmptyDirs(path.join(dir, e.name), existed);
|
|
155
|
+
}
|
|
156
|
+
if (!existed.has(dir) && !fs.readdirSync(dir).length)
|
|
157
|
+
fs.rmdirSync(dir);
|
|
158
|
+
}
|
|
159
|
+
function captureProjectFiles(config, extraDirs = []) {
|
|
160
|
+
const snap = new Map();
|
|
161
|
+
for (const dir of [config.contentTypesDir, config.generatedDir, config.migrationsDir, ...extraDirs]) {
|
|
162
|
+
for (const f of listFiles(dir))
|
|
163
|
+
snap.set(f, fs.readFileSync(f));
|
|
164
|
+
}
|
|
165
|
+
snapshotDirs.set(snap, new Set(extraDirs.flatMap(listDirs)));
|
|
166
|
+
return snap;
|
|
167
|
+
}
|
|
168
|
+
function restoreProjectFiles(config, snap, extraDirs = []) {
|
|
169
|
+
for (const dir of [config.contentTypesDir, config.generatedDir, config.migrationsDir, ...extraDirs]) {
|
|
170
|
+
for (const f of listFiles(dir))
|
|
171
|
+
if (!snap.has(f))
|
|
172
|
+
fs.rmSync(f);
|
|
173
|
+
}
|
|
174
|
+
const existed = snapshotDirs.get(snap) ?? new Set();
|
|
175
|
+
for (const dir of extraDirs)
|
|
176
|
+
pruneNewEmptyDirs(dir, existed);
|
|
177
|
+
for (const [f, content] of snap) {
|
|
178
|
+
if (!fs.existsSync(f) || !fs.readFileSync(f).equals(content)) {
|
|
179
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
180
|
+
fs.writeFileSync(f, content);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/* ------------------------------------------------------------------ */
|
|
185
|
+
/* Schema file editing (used by the admin UI and `content-type:add`) */
|
|
186
|
+
/* ------------------------------------------------------------------ */
|
|
187
|
+
function fileFor(config, loaded, def) {
|
|
188
|
+
const existing = loaded.find((l) => l.def.id === def.id);
|
|
189
|
+
return existing?.file ?? path.join(config.contentTypesDir, def.apiId, `${def.apiId}.schema.ts`);
|
|
190
|
+
}
|
|
191
|
+
/** Definitions as they would be after upserting / removing one content type (nothing is written). */
|
|
192
|
+
async function definitionsWith(config, change) {
|
|
193
|
+
const loaded = await (0, loader_1.loadDefinitions)(config);
|
|
194
|
+
let definitions = loaded.map((l) => l.def);
|
|
195
|
+
if (change.upsert) {
|
|
196
|
+
const def = (0, schema_1.normalizeDefinition)(change.upsert);
|
|
197
|
+
const i = definitions.findIndex((d) => d.id === def.id);
|
|
198
|
+
definitions = i >= 0 ? definitions.map((d, j) => (j === i ? def : d)) : [...definitions, def];
|
|
199
|
+
}
|
|
200
|
+
if (change.removeId)
|
|
201
|
+
definitions = definitions.filter((d) => d.id !== change.removeId);
|
|
202
|
+
return { loaded, definitions };
|
|
203
|
+
}
|
|
204
|
+
async function previewChange(config, change) {
|
|
205
|
+
const { definitions } = await definitionsWith(config, change);
|
|
206
|
+
return computePlan(config, { definitions });
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Writes (or deletes) the schema file for one content type. Validation and the
|
|
210
|
+
* diff run first, so an invalid change never touches the disk.
|
|
211
|
+
*/
|
|
212
|
+
async function writeSchemaChange(config, change) {
|
|
213
|
+
const { loaded, definitions } = await definitionsWith(config, change);
|
|
214
|
+
await computePlan(config, { definitions }); // throws on invalid / unsupported change
|
|
215
|
+
if (change.upsert) {
|
|
216
|
+
const def = (0, schema_1.normalizeDefinition)(change.upsert);
|
|
217
|
+
const file = fileFor(config, loaded, def);
|
|
218
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
219
|
+
fs.writeFileSync(file, (0, printer_1.printSchemaFile)(def));
|
|
220
|
+
return { file, definitions };
|
|
221
|
+
}
|
|
222
|
+
const victim = loaded.find((l) => l.def.id === change.removeId);
|
|
223
|
+
if (victim)
|
|
224
|
+
fs.rmSync(victim.file);
|
|
225
|
+
return { file: victim?.file ?? null, definitions };
|
|
226
|
+
}
|
|
227
|
+
//# sourceMappingURL=pipeline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../src/pipeline.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,gDAWC;AAED,kCAYC;AAOD,0CAwBC;AAED,4BAIC;AAQD,kCAcC;AAkCD,kDAOC;AAED,kDAYC;AAYD,0CAaC;AAED,sCAMC;AAMD,8CAgBC;AAvOD;;;;;;;;GAQG;AACH,4CAA8B;AAC9B,gDAAkC;AAElC,iDAA8E;AAC9E,uCAAmF;AACnF,+BAAyC;AACzC,iCAAsD;AACtD,qCAAyG;AACzG,qDAAmH;AACnH,iCAA2D;AAC3D,uCAA4C;AAC5C,yCAAwE;AAYxE;;;;GAIG;AACH,SAAgB,kBAAkB,CAAC,aAAqB,EAAE,GAAG,GAAG,IAAI,IAAI,EAAE;IACxE,MAAM,KAAK,GAAG,IAAA,+BAAc,EAAC,GAAG,CAAC,CAAC;IAClC,MAAM,QAAQ,GAAG,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC;QAC3C,CAAC,CAAC,EAAE,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAA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AC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,IAAA,yBAAe,EAAC,GAAG,CAAC,CAAC,CAAC;QAC7C,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IAC/B,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,MAAM,CAAC,QAAQ,CAAC,CAAC;IAChE,IAAI,MAAM;QAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,IAAI,EAAE,WAAW,EAAE,CAAC;AACrD,CAAC"}
|
package/dist/plan.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { isMultiRelation } from '@opencloudcms/schema';
|
|
2
|
+
import type { Operation } from './diff';
|
|
3
|
+
import type { Statement } from './ddl';
|
|
4
|
+
export interface MigrationPlan {
|
|
5
|
+
up: Statement[];
|
|
6
|
+
down: Statement[];
|
|
7
|
+
warnings: string[];
|
|
8
|
+
summary: string[];
|
|
9
|
+
}
|
|
10
|
+
export declare function planMigration(operations: Operation[], stamp: string): MigrationPlan;
|
|
11
|
+
export { isMultiRelation };
|
package/dist/plan.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isMultiRelation = void 0;
|
|
4
|
+
exports.planMigration = planMigration;
|
|
5
|
+
const schema_1 = require("@opencloudcms/schema");
|
|
6
|
+
Object.defineProperty(exports, "isMultiRelation", { enumerable: true, get: function () { return schema_1.isMultiRelation; } });
|
|
7
|
+
const archived = (stamp, name) => (0, schema_1.pgName)(`_del${stamp}_${name}`);
|
|
8
|
+
function relationTableSteps(def, field) {
|
|
9
|
+
const table = (0, schema_1.relTable)(def, field);
|
|
10
|
+
return {
|
|
11
|
+
up: [
|
|
12
|
+
{ type: 'createTable', table, columns: (0, schema_1.relBaseColumns)(def, field), primaryKey: { name: (0, schema_1.relPkeyName)(def, field), columns: ['entry_id', 'target_id'] } },
|
|
13
|
+
{ type: 'createIndex', index: { name: (0, schema_1.relTargetIndexName)(def, field), table, columns: ['target_id'], unique: false } },
|
|
14
|
+
],
|
|
15
|
+
down: [{ type: 'dropTable', table }],
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function createType(def) {
|
|
19
|
+
const main = (0, schema_1.mainTable)(def);
|
|
20
|
+
const l10n = (0, schema_1.l10nTable)(def);
|
|
21
|
+
const mainCols = [...(0, schema_1.mainBaseColumns)()];
|
|
22
|
+
const l10nCols = [...(0, schema_1.l10nBaseColumns)(def)];
|
|
23
|
+
const up = [];
|
|
24
|
+
const down = [];
|
|
25
|
+
const rel = [];
|
|
26
|
+
for (const field of def.fields) {
|
|
27
|
+
const s = (0, schema_1.fieldStorage)(def, field);
|
|
28
|
+
if (s.mode === 'columns')
|
|
29
|
+
(s.location === 'main' ? mainCols : l10nCols).push(...s.columns);
|
|
30
|
+
else
|
|
31
|
+
rel.push(relationTableSteps(def, field));
|
|
32
|
+
}
|
|
33
|
+
up.push({ type: 'createTable', table: main, columns: mainCols, primaryKey: { name: (0, schema_1.mainPkeyName)(def), columns: ['id'] } });
|
|
34
|
+
up.push({ type: 'createIndex', index: { name: (0, schema_1.documentStatusIndexName)(def), table: main, columns: ['document_id', 'status'], unique: true } });
|
|
35
|
+
up.push({ type: 'createTable', table: l10n, columns: l10nCols, primaryKey: { name: (0, schema_1.l10nPkeyName)(def), columns: ['entry_id', 'locale'] } });
|
|
36
|
+
for (const r of rel)
|
|
37
|
+
up.push(...r.up);
|
|
38
|
+
for (const field of def.fields) {
|
|
39
|
+
const idx = (0, schema_1.fieldIndex)(def, field);
|
|
40
|
+
if (idx)
|
|
41
|
+
up.push({ type: 'createIndex', index: idx });
|
|
42
|
+
}
|
|
43
|
+
for (const r of [...rel].reverse())
|
|
44
|
+
down.push(...r.down);
|
|
45
|
+
down.push({ type: 'dropTable', table: l10n }, { type: 'dropTable', table: main });
|
|
46
|
+
return { up, down };
|
|
47
|
+
}
|
|
48
|
+
function renamePairs(fromNames, toNames, kind) {
|
|
49
|
+
const up = [];
|
|
50
|
+
const down = [];
|
|
51
|
+
fromNames.forEach((from, i) => {
|
|
52
|
+
const to = toNames[i];
|
|
53
|
+
if (from === to)
|
|
54
|
+
return;
|
|
55
|
+
if (kind === 'table') {
|
|
56
|
+
up.push({ type: 'renameTable', from, to });
|
|
57
|
+
down.unshift({ type: 'renameTable', from: to, to: from });
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
up.push({ type: 'renameIndex', from, to });
|
|
61
|
+
down.unshift({ type: 'renameIndex', from: to, to: from });
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
return { up, down };
|
|
65
|
+
}
|
|
66
|
+
function merge(...steps) {
|
|
67
|
+
// up runs in order; down runs in reverse order of steps.
|
|
68
|
+
return { up: steps.flatMap((s) => s.up), down: [...steps].reverse().flatMap((s) => s.down) };
|
|
69
|
+
}
|
|
70
|
+
function renameType(def, toApiId) {
|
|
71
|
+
const next = { ...def, apiId: toApiId };
|
|
72
|
+
return merge(renamePairs((0, schema_1.typeTableNames)(def), (0, schema_1.typeTableNames)(next), 'table'), renamePairs((0, schema_1.typeIndexNames)(def), (0, schema_1.typeIndexNames)(next), 'index'));
|
|
73
|
+
}
|
|
74
|
+
function dropType(def, stamp) {
|
|
75
|
+
const tables = (0, schema_1.typeTableNames)(def);
|
|
76
|
+
const indexes = (0, schema_1.typeIndexNames)(def);
|
|
77
|
+
return merge(renamePairs(tables, tables.map((t) => archived(stamp, t)), 'table'), renamePairs(indexes, indexes.map((i) => archived(stamp, i)), 'index'));
|
|
78
|
+
}
|
|
79
|
+
function addField(ctx, field) {
|
|
80
|
+
const s = (0, schema_1.fieldStorage)(ctx, field);
|
|
81
|
+
if (s.mode === 'relation')
|
|
82
|
+
return relationTableSteps(ctx, field);
|
|
83
|
+
const up = s.columns.map((column) => ({ type: 'addColumn', table: s.table, column }));
|
|
84
|
+
const down = s.columns.map((c) => ({ type: 'dropColumn', table: s.table, column: c.name })).reverse();
|
|
85
|
+
const idx = (0, schema_1.fieldIndex)(ctx, field);
|
|
86
|
+
if (idx) {
|
|
87
|
+
up.push({ type: 'createIndex', index: idx });
|
|
88
|
+
down.unshift({ type: 'dropIndex', name: idx.name });
|
|
89
|
+
}
|
|
90
|
+
return { up, down };
|
|
91
|
+
}
|
|
92
|
+
function dropField(ctx, field, stamp) {
|
|
93
|
+
const s = (0, schema_1.fieldStorage)(ctx, field);
|
|
94
|
+
if (s.mode === 'relation') {
|
|
95
|
+
const idx = [(0, schema_1.relPkeyName)(ctx, field), (0, schema_1.relTargetIndexName)(ctx, field)];
|
|
96
|
+
return merge(renamePairs([s.table], [archived(stamp, s.table)], 'table'), renamePairs(idx, idx.map((i) => archived(stamp, i)), 'index'));
|
|
97
|
+
}
|
|
98
|
+
const up = [];
|
|
99
|
+
const down = [];
|
|
100
|
+
const idx = (0, schema_1.fieldIndex)(ctx, field);
|
|
101
|
+
if (idx) {
|
|
102
|
+
up.push({ type: 'dropIndex', name: idx.name });
|
|
103
|
+
}
|
|
104
|
+
for (const c of s.columns) {
|
|
105
|
+
const to = archived(stamp, c.name);
|
|
106
|
+
up.push({ type: 'renameColumn', table: s.table, from: c.name, to });
|
|
107
|
+
down.unshift({ type: 'renameColumn', table: s.table, from: to, to: c.name });
|
|
108
|
+
}
|
|
109
|
+
if (idx)
|
|
110
|
+
down.push({ type: 'createIndex', index: idx });
|
|
111
|
+
return { up, down };
|
|
112
|
+
}
|
|
113
|
+
function renameField(ctx, from, to) {
|
|
114
|
+
const a = (0, schema_1.fieldStorage)(ctx, from);
|
|
115
|
+
const b = (0, schema_1.fieldStorage)(ctx, to);
|
|
116
|
+
if (a.mode === 'relation' && b.mode === 'relation') {
|
|
117
|
+
return merge(renamePairs([a.table], [b.table], 'table'), renamePairs([(0, schema_1.relPkeyName)(ctx, from), (0, schema_1.relTargetIndexName)(ctx, from)], [(0, schema_1.relPkeyName)(ctx, to), (0, schema_1.relTargetIndexName)(ctx, to)], 'index'));
|
|
118
|
+
}
|
|
119
|
+
if (a.mode !== 'columns' || b.mode !== 'columns')
|
|
120
|
+
throw new Error('unreachable');
|
|
121
|
+
const up = [];
|
|
122
|
+
const down = [];
|
|
123
|
+
a.columns.forEach((c, i) => {
|
|
124
|
+
const target = b.columns[i].name;
|
|
125
|
+
if (c.name === target)
|
|
126
|
+
return;
|
|
127
|
+
up.push({ type: 'renameColumn', table: a.table, from: c.name, to: target });
|
|
128
|
+
down.unshift({ type: 'renameColumn', table: a.table, from: target, to: c.name });
|
|
129
|
+
});
|
|
130
|
+
const ia = (0, schema_1.fieldIndex)(ctx, from);
|
|
131
|
+
const ib = (0, schema_1.fieldIndex)(ctx, to);
|
|
132
|
+
const idx = ia && ib ? renamePairs([ia.name], [ib.name], 'index') : { up: [], down: [] };
|
|
133
|
+
return merge({ up, down }, idx);
|
|
134
|
+
}
|
|
135
|
+
function alterField(ctx, from, to, warnings) {
|
|
136
|
+
const a = (0, schema_1.fieldStorage)(ctx, from);
|
|
137
|
+
const b = (0, schema_1.fieldStorage)(ctx, to);
|
|
138
|
+
if (a.mode !== 'columns' || b.mode !== 'columns')
|
|
139
|
+
return { up: [], down: [] }; // relation target change: no DDL
|
|
140
|
+
const ia = (0, schema_1.fieldIndex)(ctx, from);
|
|
141
|
+
const ib = (0, schema_1.fieldIndex)(ctx, to);
|
|
142
|
+
const indexChanged = JSON.stringify(ia) !== JSON.stringify(ib);
|
|
143
|
+
const dropOld = ia && indexChanged
|
|
144
|
+
? { up: [{ type: 'dropIndex', name: ia.name }], down: [{ type: 'createIndex', index: ia }] }
|
|
145
|
+
: { up: [], down: [] };
|
|
146
|
+
const alter = { up: [], down: [] };
|
|
147
|
+
a.columns.forEach((c, i) => {
|
|
148
|
+
const t = b.columns[i].type;
|
|
149
|
+
if (c.type === t)
|
|
150
|
+
return;
|
|
151
|
+
alter.up.push({ type: 'alterColumnType', table: a.table, column: c.name, toType: t });
|
|
152
|
+
alter.down.unshift({ type: 'alterColumnType', table: a.table, column: c.name, toType: c.type });
|
|
153
|
+
warnings.push(`${ctx.apiId}.${to.name}: column ${c.name} widened ${c.type} -> ${t} (rollback may fail if longer values were saved).`);
|
|
154
|
+
});
|
|
155
|
+
const createNew = ib && indexChanged
|
|
156
|
+
? { up: [{ type: 'createIndex', index: ib }], down: [{ type: 'dropIndex', name: ib.name }] }
|
|
157
|
+
: { up: [], down: [] };
|
|
158
|
+
if (ib?.unique && !ia?.unique) {
|
|
159
|
+
warnings.push(`${ctx.apiId}.${to.name}: adding a unique index fails if existing entries contain duplicates.`);
|
|
160
|
+
}
|
|
161
|
+
return merge(dropOld, alter, createNew);
|
|
162
|
+
}
|
|
163
|
+
function planMigration(operations, stamp) {
|
|
164
|
+
const warnings = [];
|
|
165
|
+
const summary = [];
|
|
166
|
+
const steps = [];
|
|
167
|
+
for (const op of operations) {
|
|
168
|
+
switch (op.op) {
|
|
169
|
+
case 'setPrivate':
|
|
170
|
+
summary.push(`set private=${op.to} on content type "${op.def.apiId}"`);
|
|
171
|
+
warnings.push(`Switching "private" on ${op.def.apiId} aborts the migration if the type has entries.`);
|
|
172
|
+
steps.push({ up: [{ type: 'assertTableEmpty', table: (0, schema_1.mainTable)(op.def), apiId: op.def.apiId, option: 'private' }], down: [] });
|
|
173
|
+
break;
|
|
174
|
+
case 'createType':
|
|
175
|
+
summary.push(`create content type "${op.def.apiId}"`);
|
|
176
|
+
steps.push(createType(op.def));
|
|
177
|
+
break;
|
|
178
|
+
case 'dropType':
|
|
179
|
+
summary.push(`archive content type "${op.def.apiId}"`);
|
|
180
|
+
warnings.push(`Content type "${op.def.apiId}" is archived: its tables are renamed with prefix _del${stamp}_ (data kept, drop them manually when sure).`);
|
|
181
|
+
steps.push(dropType(op.def, stamp));
|
|
182
|
+
break;
|
|
183
|
+
case 'renameType':
|
|
184
|
+
summary.push(`rename content type "${op.def.apiId}" -> "${op.toApiId}"`);
|
|
185
|
+
warnings.push(`REST path changes from /${op.def.apiId} to /${op.toApiId}; update API clients.`);
|
|
186
|
+
steps.push(renameType(op.def, op.toApiId));
|
|
187
|
+
break;
|
|
188
|
+
case 'addField':
|
|
189
|
+
summary.push(`add field ${op.ctx.apiId}.${op.field.name} (${op.field.kind})`);
|
|
190
|
+
if (op.field.required) {
|
|
191
|
+
warnings.push(`${op.ctx.apiId}.${op.field.name} is required: existing entries must be filled in before they can be re-published.`);
|
|
192
|
+
}
|
|
193
|
+
steps.push(addField(op.ctx, op.field));
|
|
194
|
+
break;
|
|
195
|
+
case 'dropField':
|
|
196
|
+
summary.push(`archive field ${op.ctx.apiId}.${op.field.name}`);
|
|
197
|
+
warnings.push(`${op.ctx.apiId}.${op.field.name} is archived (column renamed with prefix _del${stamp}_, data kept).`);
|
|
198
|
+
steps.push(dropField(op.ctx, op.field, stamp));
|
|
199
|
+
break;
|
|
200
|
+
case 'renameField':
|
|
201
|
+
summary.push(`rename field ${op.ctx.apiId}.${op.from.name} -> ${op.to.name}`);
|
|
202
|
+
steps.push(renameField(op.ctx, op.from, op.to));
|
|
203
|
+
break;
|
|
204
|
+
case 'alterField':
|
|
205
|
+
summary.push(`alter field ${op.ctx.apiId}.${op.to.name}`);
|
|
206
|
+
steps.push(alterField(op.ctx, op.from, op.to, warnings));
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
up: steps.flatMap((s) => s.up),
|
|
212
|
+
down: [...steps].reverse().flatMap((s) => s.down),
|
|
213
|
+
warnings,
|
|
214
|
+
summary,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
//# sourceMappingURL=plan.js.map
|
package/dist/plan.js.map
ADDED
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CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;gBAC/C,MAAM;YACR,KAAK,aAAa;gBAChB,OAAO,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,IAAI,OAAO,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;gBAC9E,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;gBAChD,MAAM;YACR,KAAK,YAAY;gBACf,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;gBAC1D,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC,CAAC;gBACzD,MAAM;QACV,CAAC;IACH,CAAC;IACD,OAAO;QACL,EAAE,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9B,IAAI,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QACjD,QAAQ;QACR,OAAO;KACR,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prints a content type definition back to a `*.schema.ts` source file.
|
|
3
|
+
* Used when a content type is created / edited from the admin UI, so the UI
|
|
4
|
+
* and hand-written files share the same source of truth.
|
|
5
|
+
*/
|
|
6
|
+
import type { ContentGroupDefinition, ContentTypeDefinition, LocaleSettings, ThemeDefinition } from '@opencloudcms/schema';
|
|
7
|
+
export declare function printSchemaFile(def: ContentTypeDefinition): string;
|
|
8
|
+
export declare function printContentGroupsFile(groups: ContentGroupDefinition[]): string;
|
|
9
|
+
export declare function printLocalesFile(s: LocaleSettings): string;
|
|
10
|
+
/** `src/theme.ts`: brand colors and palettes, written by the admin Page builder > Theme. */
|
|
11
|
+
export declare function printThemeFile(t: ThemeDefinition): string;
|
package/dist/printer.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.printSchemaFile = printSchemaFile;
|
|
4
|
+
exports.printContentGroupsFile = printContentGroupsFile;
|
|
5
|
+
exports.printLocalesFile = printLocalesFile;
|
|
6
|
+
exports.printThemeFile = printThemeFile;
|
|
7
|
+
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
8
|
+
function lit(value, indent) {
|
|
9
|
+
if (value === null)
|
|
10
|
+
return 'null';
|
|
11
|
+
if (typeof value === 'string')
|
|
12
|
+
return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')}'`;
|
|
13
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
14
|
+
return String(value);
|
|
15
|
+
if (Array.isArray(value))
|
|
16
|
+
return `[${value.map((v) => lit(v, indent)).join(', ')}]`;
|
|
17
|
+
if (typeof value === 'object') {
|
|
18
|
+
const entries = Object.entries(value).filter(([, v]) => v !== undefined);
|
|
19
|
+
if (!entries.length)
|
|
20
|
+
return '{}';
|
|
21
|
+
return `{ ${entries.map(([k, v]) => `${IDENT.test(k) ? k : lit(k, indent)}: ${lit(v, indent)}`).join(', ')} }`;
|
|
22
|
+
}
|
|
23
|
+
throw new Error(`Cannot print value of type ${typeof value}`);
|
|
24
|
+
}
|
|
25
|
+
function printField(field) {
|
|
26
|
+
const arg = { id: field.id };
|
|
27
|
+
if (field.label)
|
|
28
|
+
arg.label = field.label;
|
|
29
|
+
if (field.description)
|
|
30
|
+
arg.description = field.description;
|
|
31
|
+
if (field.required)
|
|
32
|
+
arg.required = true;
|
|
33
|
+
if (field.localizable)
|
|
34
|
+
arg.localizable = true;
|
|
35
|
+
if (field.unique)
|
|
36
|
+
arg.unique = true;
|
|
37
|
+
else if (field.indexed)
|
|
38
|
+
arg.indexed = true;
|
|
39
|
+
if (field.readOnly)
|
|
40
|
+
arg.readOnly = true;
|
|
41
|
+
for (const [k, v] of Object.entries(field.options ?? {})) {
|
|
42
|
+
if (v !== undefined && v !== null && v !== '')
|
|
43
|
+
arg[k] = v;
|
|
44
|
+
}
|
|
45
|
+
return ` ${field.name}: f.${field.kind}(${lit(arg, '')}),`;
|
|
46
|
+
}
|
|
47
|
+
/** `{ path, slugField? }` in a fixed key order (empty `slugField` left out). */
|
|
48
|
+
function detailPageLiteral(d) {
|
|
49
|
+
return { path: d.path, ...(d.slugField ? { slugField: d.slugField } : {}) };
|
|
50
|
+
}
|
|
51
|
+
function printSchemaFile(def) {
|
|
52
|
+
const lines = [
|
|
53
|
+
'// Source of truth for this content type. Edit by hand or from the admin',
|
|
54
|
+
'// Content Type Builder (which rewrites this file), then run `opencloudcms migrate:create`.',
|
|
55
|
+
"import { defineContentType, f } from '@opencloudcms/schema';",
|
|
56
|
+
'',
|
|
57
|
+
'export default defineContentType({',
|
|
58
|
+
` id: ${lit(def.id, '')},`,
|
|
59
|
+
` apiId: ${lit(def.apiId, '')},`,
|
|
60
|
+
` displayName: ${lit(def.displayName, '')},`,
|
|
61
|
+
...(def.group ? [` group: ${lit(def.group, '')},`] : []),
|
|
62
|
+
...(def.description ? [` description: ${lit(def.description, '')},`] : []),
|
|
63
|
+
...(def.review ? [' review: true,'] : []),
|
|
64
|
+
...(def.private ? [' private: true,'] : []),
|
|
65
|
+
...(def.detailPage ? [` detailPage: ${lit(detailPageLiteral(def.detailPage), '')},`] : []),
|
|
66
|
+
' fields: {',
|
|
67
|
+
...def.fields.map(printField),
|
|
68
|
+
' },',
|
|
69
|
+
'});',
|
|
70
|
+
'',
|
|
71
|
+
];
|
|
72
|
+
return lines.join('\n');
|
|
73
|
+
}
|
|
74
|
+
function printContentGroupsFile(groups) {
|
|
75
|
+
return [
|
|
76
|
+
'// Content groups. Managed by OpenCloudCMS: edit by hand or from the admin',
|
|
77
|
+
'// Content Type Builder (which rewrites this file).',
|
|
78
|
+
"import { defineContentGroups } from '@opencloudcms/schema';",
|
|
79
|
+
'',
|
|
80
|
+
'export default defineContentGroups([',
|
|
81
|
+
...groups.map((g) => ` ${lit({ key: g.key, title: g.title, order: g.order }, '')},`),
|
|
82
|
+
']);',
|
|
83
|
+
'',
|
|
84
|
+
].join('\n');
|
|
85
|
+
}
|
|
86
|
+
function printLocalesFile(s) {
|
|
87
|
+
return [
|
|
88
|
+
'// Supported locales. Managed by OpenCloudCMS: edit by hand or from the admin',
|
|
89
|
+
'// Settings > Languages (which rewrites this file).',
|
|
90
|
+
"import { defineLocales } from '@opencloudcms/schema';",
|
|
91
|
+
'',
|
|
92
|
+
'export default defineLocales({',
|
|
93
|
+
` defaultLocale: ${lit(s.defaultLocale, '')},`,
|
|
94
|
+
` locales: ${lit(s.locales, '')},`,
|
|
95
|
+
'});',
|
|
96
|
+
'',
|
|
97
|
+
].join('\n');
|
|
98
|
+
}
|
|
99
|
+
/** `src/theme.ts`: brand colors and palettes, written by the admin Page builder > Theme. */
|
|
100
|
+
function printThemeFile(t) {
|
|
101
|
+
const pad = ' ';
|
|
102
|
+
const colors = Object.entries(t.colors).map(([k, v]) => ` ${IDENT.test(k) ? k : lit(k, '')}: ${lit(v, '')},`);
|
|
103
|
+
const palettes = Object.entries(t.palettes).map(([id, p]) => {
|
|
104
|
+
const body = {};
|
|
105
|
+
if (p.label !== undefined)
|
|
106
|
+
body.label = p.label;
|
|
107
|
+
body.values = p.values;
|
|
108
|
+
return ` ${IDENT.test(id) ? id : lit(id, '')}: ${lit(body, '')},`;
|
|
109
|
+
});
|
|
110
|
+
return [
|
|
111
|
+
'// Brand colors and palettes. Managed by OpenCloudCMS: edit by hand or from the admin',
|
|
112
|
+
'// Page builder > Theme (which rewrites this file).',
|
|
113
|
+
"import { defineTheme } from '@opencloudcms/schema';",
|
|
114
|
+
'',
|
|
115
|
+
'export default defineTheme({',
|
|
116
|
+
`${pad}colors: {`,
|
|
117
|
+
...colors,
|
|
118
|
+
`${pad}},`,
|
|
119
|
+
`${pad}palettes: {`,
|
|
120
|
+
...palettes,
|
|
121
|
+
`${pad}},`,
|
|
122
|
+
`${pad}activePalette: ${lit(t.activePalette, '')},`,
|
|
123
|
+
'});',
|
|
124
|
+
'',
|
|
125
|
+
].join('\n');
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=printer.js.map
|