@burnsred/entity-sync 0.0.0-stage → 3.0.0-rc.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.
Files changed (50) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +11 -0
  3. package/CHANGELOG.md +15 -0
  4. package/LICENSE +21 -0
  5. package/README.md +240 -2
  6. package/agents/entity-editor.md +16 -0
  7. package/bin/entity-sync.mjs +36 -0
  8. package/dist/cli.d.mts +20 -0
  9. package/dist/commands/asserts.d.mts +4 -0
  10. package/dist/commands/check.d.mts +6 -0
  11. package/dist/commands/inspect.d.mts +30 -0
  12. package/dist/commands/plan.d.mts +28 -0
  13. package/dist/commands/schema.d.mts +39 -0
  14. package/dist/config.d.mts +175 -0
  15. package/dist/index.d.mts +5 -0
  16. package/dist/lib/cache.d.mts +120 -0
  17. package/dist/lib/diff.d.mts +228 -0
  18. package/dist/lib/field-map.d.mts +93 -0
  19. package/dist/lib/gen-asserts.d.mts +70 -0
  20. package/dist/lib/graph.d.mts +90 -0
  21. package/dist/lib/parse-entities.d.mts +257 -0
  22. package/dist/lib/parse-schema.d.mts +98 -0
  23. package/dist/lib/resolve.d.mts +135 -0
  24. package/dist/project.d.mts +60 -0
  25. package/hooks/editor-guard.mjs +86 -0
  26. package/hooks/hooks.json +15 -0
  27. package/package.json +54 -4
  28. package/skills/entity/SKILL.md +105 -0
  29. package/skills/entity/reference/create.md +74 -0
  30. package/skills/entity/reference/editor.md +80 -0
  31. package/skills/entity/reference/enums.md +89 -0
  32. package/skills/entity/reference/fields.md +101 -0
  33. package/skills/entity/reference/sync.md +191 -0
  34. package/src/cli.mjs +110 -0
  35. package/src/commands/asserts.mjs +52 -0
  36. package/src/commands/check.mjs +88 -0
  37. package/src/commands/inspect.mjs +290 -0
  38. package/src/commands/plan.mjs +542 -0
  39. package/src/commands/schema.mjs +206 -0
  40. package/src/config.mjs +205 -0
  41. package/src/index.mjs +19 -0
  42. package/src/lib/cache.mjs +323 -0
  43. package/src/lib/diff.mjs +706 -0
  44. package/src/lib/field-map.mjs +438 -0
  45. package/src/lib/gen-asserts.mjs +478 -0
  46. package/src/lib/graph.mjs +284 -0
  47. package/src/lib/parse-entities.mjs +935 -0
  48. package/src/lib/parse-schema.mjs +667 -0
  49. package/src/lib/resolve.mjs +455 -0
  50. package/src/project.mjs +115 -0
@@ -0,0 +1,206 @@
1
+ // @ts-check
2
+ /**
3
+ * Fetch (or read) the broker's OpenAPI schema and regenerate the TypeScript
4
+ * types.
5
+ *
6
+ * With `schema.url`, writes two artifacts, both meant to be committed:
7
+ *
8
+ * - `schema.yaml` - verbatim, exactly as the API sent it. Its job is
9
+ * provenance: `info.title` / `info.version` are the only way to tell which
10
+ * service answered, and `openapi-typescript` discards both.
11
+ * - `schema.dts` - the generated types. This is the artifact everything
12
+ * downstream parses; the yaml is never parsed for field data.
13
+ *
14
+ * With `schema.file`, the file is already the provenance record, so only the
15
+ * types are written.
16
+ *
17
+ * Two guards run before anything is written, because both failure modes produce
18
+ * a schema that parses perfectly and is completely wrong:
19
+ *
20
+ * 1. A non-2xx response body would generate a near-empty `schema.d.ts`, which
21
+ * the drift report would faithfully describe as "the API deleted every field".
22
+ * 2. The wrong service on the expected port returns a valid schema for a
23
+ * different application. `info.title` (`schema.expectedTitle`) is the cheap
24
+ * discriminator, so it is required with `schema.url`.
25
+ *
26
+ * The generated types are formatted with the project's prettier: without that,
27
+ * every sync would produce a whole-file diff.
28
+ *
29
+ * Usage: `entity-sync schema`
30
+ */
31
+
32
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
33
+ import { dirname } from 'node:path';
34
+
35
+ import openapiTS, { COMMENT_HEADER, astToString } from 'openapi-typescript';
36
+ import { parse as parseYaml } from 'yaml';
37
+
38
+ import { display } from '../config.mjs';
39
+ import { formatForProject } from '../project.mjs';
40
+
41
+ /**
42
+ * @typedef {import('../config.mjs').ResolvedConfig} ResolvedConfig
43
+ */
44
+
45
+ /**
46
+ * Load the configured env files. Later files win over earlier ones, and the
47
+ * shell wins over all of them: `process.loadEnvFile` never overrides a variable
48
+ * that is already set, so the files are loaded last-first.
49
+ *
50
+ * @param {string[]} files absolute
51
+ */
52
+ export function loadEnvFiles(files) {
53
+ for (const file of [...files].reverse()) {
54
+ if (existsSync(file)) process.loadEnvFile(file);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * @param {ResolvedConfig} config
60
+ * @returns {Record<string, string>} request headers
61
+ */
62
+ function authHeaders(config) {
63
+ const { auth } = config.schema;
64
+ if (!auth) return {};
65
+
66
+ loadEnvFiles(config.schema.envFiles);
67
+ const username = process.env[auth.usernameEnv];
68
+ const password = process.env[auth.passwordEnv];
69
+
70
+ if (!username || !password) {
71
+ const files = config.schema.envFiles.map((f) => display(config, f));
72
+ throw new Error(
73
+ `${auth.usernameEnv} / ${auth.passwordEnv} are not set.\n` +
74
+ `Export them, or set them in one of: ${files.join(', ')} ` +
75
+ '(keep those files gitignored).',
76
+ );
77
+ }
78
+
79
+ const token = Buffer.from(`${username}:${password}`).toString('base64');
80
+ return { Authorization: `Basic ${token}` };
81
+ }
82
+
83
+ /**
84
+ * Fetch the schema document as text, failing loudly on any non-2xx response.
85
+ *
86
+ * @param {string} url
87
+ * @param {Record<string, string>} headers
88
+ * @returns {Promise<string>} the raw response body
89
+ */
90
+ async function fetchSchema(url, headers) {
91
+ let res;
92
+ try {
93
+ res = await fetch(url, { headers });
94
+ } catch (cause) {
95
+ // A connection refused here almost always means the broker isn't running.
96
+ throw new Error(
97
+ `could not reach ${url} - is the broker running?\n ${cause}`,
98
+ );
99
+ }
100
+
101
+ if (!res.ok) {
102
+ throw new Error(
103
+ `schema fetch failed: ${res.status} ${res.statusText} from ${url}`,
104
+ );
105
+ }
106
+
107
+ return res.text();
108
+ }
109
+
110
+ /**
111
+ * Confirm the document describes the application we expect.
112
+ *
113
+ * @param {unknown} doc parsed OpenAPI document
114
+ * @param {string | null} expectedTitle
115
+ * @param {string} source where the document came from, for the error
116
+ * @returns {{ title: string, version: string }}
117
+ */
118
+ export function assertExpectedApi(doc, expectedTitle, source) {
119
+ const info = /** @type {{ info?: { title?: string, version?: string } }} */ (
120
+ doc
121
+ )?.info;
122
+
123
+ if (expectedTitle !== null && info?.title !== expectedTitle) {
124
+ throw new Error(
125
+ `wrong API at ${source}: ` +
126
+ `expected info.title "${expectedTitle}", got "${info?.title ?? '(none)'}"`,
127
+ );
128
+ }
129
+
130
+ return {
131
+ title: info?.title ?? '(none)',
132
+ version: info?.version ?? '(none)',
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Generate the `.d.ts` text from a parsed document.
138
+ *
139
+ * The parsed document is passed rather than the raw text, so generation cannot
140
+ * disagree with the document the guards just validated. `astToString` emits
141
+ * only the types; the "do not edit" banner is added by openapi-typescript's
142
+ * CLI, so prepend it explicitly or it is lost.
143
+ *
144
+ * @param {unknown} doc
145
+ */
146
+ export async function generateDts(doc) {
147
+ return (
148
+ COMMENT_HEADER +
149
+ astToString(
150
+ await openapiTS(/** @type {Parameters<typeof openapiTS>[0]} */ (doc)),
151
+ )
152
+ );
153
+ }
154
+
155
+ /**
156
+ * @param {ResolvedConfig} config
157
+ */
158
+ export async function run(config) {
159
+ const { url, file, expectedTitle, yaml, dts } = config.schema;
160
+
161
+ /** @type {string} */
162
+ let text;
163
+ /** @type {string} */
164
+ let source;
165
+
166
+ if (url) {
167
+ if (expectedTitle === null) {
168
+ throw new Error(
169
+ 'schema.expectedTitle is required with schema.url: it is the only ' +
170
+ 'guard against a different service answering on the same port.',
171
+ );
172
+ }
173
+ source = url;
174
+ console.log(`fetching ${url}`);
175
+ text = await fetchSchema(url, authHeaders(config));
176
+ } else if (file) {
177
+ source = display(config, file);
178
+ console.log(`reading ${source}`);
179
+ text = readFileSync(file, 'utf8');
180
+ } else {
181
+ throw new Error('set schema.url or schema.file in the entity-sync config');
182
+ }
183
+
184
+ // YAML is a superset of JSON, so this reads either.
185
+ const doc = parseYaml(text);
186
+ const { title, version } = assertExpectedApi(doc, expectedTitle, source);
187
+ // Logged so an upstream version bump is visible in the sync output.
188
+ console.log(`schema: ${title} v${version}`);
189
+
190
+ const written = [];
191
+ if (url) {
192
+ // Verbatim, so the file remains an accurate record of what was served.
193
+ mkdirSync(dirname(yaml), { recursive: true });
194
+ writeFileSync(yaml, text);
195
+ written.push(display(config, yaml));
196
+ }
197
+
198
+ mkdirSync(dirname(dts), { recursive: true });
199
+ writeFileSync(
200
+ dts,
201
+ await formatForProject(config, dts, await generateDts(doc)),
202
+ );
203
+ written.push(display(config, dts));
204
+
205
+ console.log(`wrote ${written.join(', ')}`);
206
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,205 @@
1
+ // @ts-check
2
+ /**
3
+ * Load and resolve `entity-sync.config.{mjs,js,json}`.
4
+ *
5
+ * Every path in the config is relative to the directory holding the config
6
+ * file (the project root), and is resolved to an absolute path here so the
7
+ * commands never have to know where they were run from.
8
+ *
9
+ * The defaults describe the conventional BurnsRED frontend layout. Nothing
10
+ * project-specific (API title, URL prefixes) has a default: a missing value
11
+ * should fail loudly or resolve to "no prefix", never to another project's.
12
+ */
13
+
14
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
15
+ import { dirname, join, posix, relative, resolve, sep } from 'node:path';
16
+ import { pathToFileURL } from 'node:url';
17
+
18
+ import { DEFAULT_EQUIVALENT_FIELD_CLASSES } from './lib/diff.mjs';
19
+
20
+ export const CONFIG_FILENAMES = [
21
+ 'entity-sync.config.mjs',
22
+ 'entity-sync.config.js',
23
+ 'entity-sync.config.json',
24
+ ];
25
+
26
+ /**
27
+ * @typedef {object} BasicAuthConfig
28
+ * @property {'basic'} type
29
+ * @property {string} [usernameEnv] default `API_SUPERUSER_USERNAME`
30
+ * @property {string} [passwordEnv] default `API_SUPERUSER_PASSWORD`
31
+ */
32
+
33
+ /**
34
+ * @typedef {object} SchemaConfig
35
+ * @property {string} [url] fetch the OpenAPI document from the broker
36
+ * @property {string} [file] or read it from a file (yaml or json)
37
+ * @property {string} [expectedTitle] required with `url`: guards against the wrong service answering
38
+ * @property {BasicAuthConfig | false} [auth] default basic auth from env
39
+ * @property {string[]} [envFiles] loaded before reading credentials; later files win, the shell wins over all
40
+ * @property {string} [yaml] where the verbatim document is written (`url` only)
41
+ * @property {string} [dts] generated types, the artifact everything parses
42
+ * @property {string} [importSpecifier] how `schema-asserts.ts` imports `components`; default: relative path to `dts`
43
+ */
44
+
45
+ /**
46
+ * @typedef {object} Config
47
+ * @property {SchemaConfig} [schema]
48
+ * @property {string} [entitiesDir]
49
+ * @property {string} [assertsFile]
50
+ * @property {string} [stateDir] per-developer state (report, plan, lock); gitignore it
51
+ * @property {Record<string, string>} [settingsPrefixes] `settings.X` constant -> schema path prefix
52
+ * @property {string} [apiBasePrefix] prefix for a bare relative `apiBase`; a `settingsPrefixes` key or a literal path
53
+ * @property {Record<string, string[]>} [equivalentFieldClasses] merged over the defaults
54
+ * @property {string} [knownNoise] optional doc listing report ops that are not real drift
55
+ */
56
+
57
+ /**
58
+ * @typedef {object} ResolvedConfig
59
+ * @property {string} root
60
+ * @property {string | null} configFile
61
+ * @property {{ url: string | null, file: string | null, expectedTitle: string | null, auth: Required<BasicAuthConfig> | false, envFiles: string[], yaml: string, dts: string, importSpecifier: string }} schema
62
+ * @property {string} entitiesDir
63
+ * @property {string} assertsFile
64
+ * @property {string} stateDir
65
+ * @property {Record<string, string>} settingsPrefixes
66
+ * @property {string} apiBasePrefix
67
+ * @property {Readonly<Record<string, readonly string[]>>} equivalentFieldClasses
68
+ * @property {string | null} knownNoise
69
+ */
70
+
71
+ /**
72
+ * Identity helper so a config file gets editor completion.
73
+ *
74
+ * @param {Config} config
75
+ * @returns {Config}
76
+ */
77
+ export function defineConfig(config) {
78
+ return config;
79
+ }
80
+
81
+ /**
82
+ * @param {string} dir
83
+ * @returns {string | null}
84
+ */
85
+ function findConfigFile(dir) {
86
+ for (const name of CONFIG_FILENAMES) {
87
+ const candidate = join(dir, name);
88
+ if (existsSync(candidate)) return candidate;
89
+ }
90
+ return null;
91
+ }
92
+
93
+ /**
94
+ * Module specifier from one file's directory to another file, posix-style and
95
+ * always explicitly relative, with TypeScript extensions dropped.
96
+ *
97
+ * @param {string} fromDir absolute
98
+ * @param {string} toFile absolute
99
+ */
100
+ export function relativeSpecifier(fromDir, toFile) {
101
+ const rel = relative(fromDir, toFile)
102
+ .split(sep)
103
+ .join(posix.sep)
104
+ .replace(/\.d\.ts$/, '')
105
+ .replace(/\.(tsx?|mts|cts)$/, '');
106
+ return rel.startsWith('.') ? rel : `./${rel}`;
107
+ }
108
+
109
+ /**
110
+ * Apply defaults and resolve paths. Exported separately from `loadConfig` so
111
+ * tests can resolve an in-memory config.
112
+ *
113
+ * @param {Config} config
114
+ * @param {string} root absolute directory the config's paths are relative to
115
+ * @param {string | null} [configFile]
116
+ * @returns {ResolvedConfig}
117
+ */
118
+ export function resolveConfig(config, root, configFile = null) {
119
+ const at = (/** @type {string} */ path) => resolve(root, path);
120
+ const schema = config.schema ?? {};
121
+
122
+ const entitiesDir = at(config.entitiesDir ?? 'src/entities');
123
+ const assertsFile = config.assertsFile
124
+ ? at(config.assertsFile)
125
+ : join(entitiesDir, '__generated__', 'schema-asserts.ts');
126
+ const dts = at(schema.dts ?? 'src/api/schema.d.ts');
127
+
128
+ const settingsPrefixes = { ...config.settingsPrefixes };
129
+ const basePrefixOption = config.apiBasePrefix ?? '';
130
+ const apiBasePrefix = settingsPrefixes[basePrefixOption] ?? basePrefixOption;
131
+
132
+ const auth =
133
+ schema.auth === false
134
+ ? false
135
+ : {
136
+ type: /** @type {const} */ ('basic'),
137
+ usernameEnv: schema.auth?.usernameEnv ?? 'API_SUPERUSER_USERNAME',
138
+ passwordEnv: schema.auth?.passwordEnv ?? 'API_SUPERUSER_PASSWORD',
139
+ };
140
+
141
+ return {
142
+ root,
143
+ configFile,
144
+ schema: {
145
+ url: schema.url ?? null,
146
+ file: schema.file ? at(schema.file) : null,
147
+ expectedTitle: schema.expectedTitle ?? null,
148
+ auth,
149
+ envFiles: (schema.envFiles ?? ['env/.env', 'env/.env.local']).map(at),
150
+ yaml: at(schema.yaml ?? 'src/api/schema.yaml'),
151
+ dts,
152
+ importSpecifier:
153
+ schema.importSpecifier ?? relativeSpecifier(dirname(assertsFile), dts),
154
+ },
155
+ entitiesDir,
156
+ assertsFile,
157
+ stateDir: at(config.stateDir ?? '.entity-sync'),
158
+ settingsPrefixes,
159
+ apiBasePrefix,
160
+ equivalentFieldClasses: {
161
+ ...DEFAULT_EQUIVALENT_FIELD_CLASSES,
162
+ ...config.equivalentFieldClasses,
163
+ },
164
+ knownNoise: config.knownNoise ? at(config.knownNoise) : null,
165
+ };
166
+ }
167
+
168
+ /**
169
+ * Find, import and resolve the project config.
170
+ *
171
+ * @param {{ cwd?: string, configPath?: string }} [options]
172
+ * @returns {Promise<ResolvedConfig>}
173
+ */
174
+ export async function loadConfig({ cwd = process.cwd(), configPath } = {}) {
175
+ const file = configPath ? resolve(cwd, configPath) : findConfigFile(cwd);
176
+
177
+ if (!file) {
178
+ throw new Error(
179
+ `no ${CONFIG_FILENAMES.join(' / ')} in ${cwd}.\n` +
180
+ 'Run entity-sync from the project root, or pass --config <path>.',
181
+ );
182
+ }
183
+ if (!existsSync(file)) throw new Error(`config not found: ${file}`);
184
+
185
+ /** @type {Config} */
186
+ let config;
187
+ if (file.endsWith('.json')) {
188
+ config = JSON.parse(readFileSync(file, 'utf8'));
189
+ } else {
190
+ const mod = await import(pathToFileURL(realpathSync(file)).href);
191
+ config = mod.default ?? mod;
192
+ }
193
+
194
+ return resolveConfig(config, dirname(file), file);
195
+ }
196
+
197
+ /**
198
+ * A path relative to the project root, for log lines and report text.
199
+ *
200
+ * @param {ResolvedConfig} config
201
+ * @param {string} path absolute
202
+ */
203
+ export function display(config, path) {
204
+ return relative(config.root, path).split(sep).join(posix.sep);
205
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,19 @@
1
+ // @ts-check
2
+ /**
3
+ * Public API. The CLI (`entity-sync`) is the main interface; this exists for
4
+ * `defineConfig` in config files and for tooling that wants the parsed data.
5
+ */
6
+
7
+ /**
8
+ * @typedef {import('./config.mjs').Config} Config
9
+ * @typedef {import('./config.mjs').ResolvedConfig} ResolvedConfig
10
+ */
11
+
12
+ export {
13
+ defineConfig,
14
+ loadConfig,
15
+ resolveConfig,
16
+ CONFIG_FILENAMES,
17
+ } from './config.mjs';
18
+ export { loadProject } from './project.mjs';
19
+ export { main } from './cli.mjs';