@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,290 @@
1
+ // @ts-check
2
+ /**
3
+ * Debug CLI for the entity-sync modules. Not part of the sync itself - it exists
4
+ * so each parsing stage can be eyeballed against the real schema without adding
5
+ * console noise to the modules themselves.
6
+ *
7
+ * Usage: `entity-sync inspect <command>` (or `npm run entity:inspect -- <command>`):
8
+ * component <Name> one component's fields
9
+ * components all component names + kinds
10
+ * path <substring> matching endpoints
11
+ * entity <Name> one entity's declarations
12
+ * entities all entities + apiBase
13
+ * enums choices dicts, their component and any value drift
14
+ * errors assertion failures grouped by entity, from tsc output on stdin
15
+ */
16
+
17
+ import { readFileSync } from 'node:fs';
18
+ import { basename } from 'node:path';
19
+
20
+ import { resolveEnums } from '../lib/resolve.mjs';
21
+ import { readEntities, readEnums, readSchema } from '../project.mjs';
22
+
23
+ export const USAGE =
24
+ 'usage: entity-sync inspect component <Name> | components | path <substring> | entity <Name> | entities | enums | errors';
25
+
26
+ /**
27
+ * Group tsc's assertion failures by entity, resolving each error's line number
28
+ * back to the entity block it sits in.
29
+ *
30
+ * Exists so this analysis is a command rather than a throwaway one-liner: it
31
+ * was re-typed by hand several times while calibrating the assertions, which is
32
+ * exactly the work that belongs in a script.
33
+ *
34
+ * @param {string} tscOutput
35
+ * @param {string} assertsSource contents of the assertions file
36
+ * @param {string} assertsName its basename, as tsc prints it
37
+ * @returns {{ grouped: Map<string, string[]>, total: number }}
38
+ */
39
+ export function groupAssertionErrors(tscOutput, assertsSource, assertsName) {
40
+ const source = assertsSource.split('\n');
41
+ const escaped = assertsName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
42
+ const pattern = new RegExp(`${escaped}\\((\\d+),\\d+\\): error \\S+ (.*)$`);
43
+
44
+ /** @param {number} line 1-indexed */
45
+ const entityAt = (line) => {
46
+ for (let i = line - 1; i >= 0; i -= 1) {
47
+ const match = source[i]?.match(/^\/\/ (\w+) -> (\w+)/);
48
+ if (match) return `${match[1]} -> ${match[2]}`;
49
+ }
50
+ return '(unknown)';
51
+ };
52
+
53
+ /** @type {Map<string, string[]>} */
54
+ const grouped = new Map();
55
+ let total = 0;
56
+
57
+ for (const line of tscOutput.split('\n')) {
58
+ const match = line.match(pattern);
59
+ if (!match) continue;
60
+
61
+ total += 1;
62
+ const lineNumber = Number(match[1]);
63
+ const field = (source[lineNumber - 1] ?? '')
64
+ .trim()
65
+ .replace(/:\s*true,?$/, '')
66
+ .replace(/^export const \w+: Exact<?/, '(record type)');
67
+ // The `{ expected; got }` payload is the useful half of the message.
68
+ const detail = match[2].match(/type '(\{.*\})'\.?$/)?.[1] ?? match[2];
69
+
70
+ const key = entityAt(lineNumber);
71
+ const entries = grouped.get(key) ?? [];
72
+ entries.push(`${field} :: ${detail}`);
73
+ grouped.set(key, entries);
74
+ }
75
+
76
+ return { grouped, total };
77
+ }
78
+
79
+ /**
80
+ * @param {{ grouped: Map<string, string[]>, total: number }} result
81
+ */
82
+ export function printGroupedErrors({ grouped, total }) {
83
+ for (const [key, entries] of grouped) {
84
+ console.log(`\n${key} (${entries.length})`);
85
+ for (const entry of entries) console.log(` ${entry}`);
86
+ }
87
+ console.log(`\n${total} assertion failures across ${grouped.size} entities`);
88
+ }
89
+
90
+ /**
91
+ * One-line summary of a field, showing every signal `field-map.mjs` consumes.
92
+ *
93
+ * @param {import('../lib/parse-schema.mjs').SchemaField} field
94
+ */
95
+ function formatField(field) {
96
+ const flags = [
97
+ field.readonly && 'readonly',
98
+ field.optional && 'optional',
99
+ field.nullable && 'nullable',
100
+ field.isArray && 'array',
101
+ ].filter(Boolean);
102
+
103
+ const type = field.refs.length ? field.refs.join(' | ') : field.tsType;
104
+
105
+ return [
106
+ ` ${field.name}:`,
107
+ type,
108
+ field.format ? `[${field.format}]` : '',
109
+ flags.length ? `(${flags.join(', ')})` : '',
110
+ ]
111
+ .filter(Boolean)
112
+ .join(' ');
113
+ }
114
+
115
+ /**
116
+ * One-line summary of an entity field declaration.
117
+ *
118
+ * @param {import('../lib/parse-entities.mjs').EntityFieldDecl} field
119
+ */
120
+ function formatEntityField(field) {
121
+ const flags = [
122
+ field.readOnly && 'readOnly',
123
+ field.blank && 'blank',
124
+ field.many && 'many',
125
+ ].filter(Boolean);
126
+
127
+ return [
128
+ ` ${field.name}:`,
129
+ field.fieldClass ?? '(not a field constructor)',
130
+ field.entityRef ? `-> ${field.entityRef}` : '',
131
+ flags.length ? `(${flags.join(', ')})` : '',
132
+ ]
133
+ .filter(Boolean)
134
+ .join(' ');
135
+ }
136
+
137
+ /**
138
+ * @param {import('../config.mjs').ResolvedConfig} config
139
+ * @param {string[]} [args]
140
+ */
141
+ export function run(config, args = []) {
142
+ const [command, argument] = args;
143
+ /** Parsed lazily, so an entity-only command doesn't pay for schema parsing. */
144
+ const lazySchema = () => readSchema(config);
145
+ const lazyEntities = () => readEntities(config);
146
+
147
+ switch (command) {
148
+ case 'component': {
149
+ const schema = lazySchema();
150
+ const component = schema.components[argument];
151
+ if (!component) {
152
+ throw new Error(`no such component: ${argument}`);
153
+ }
154
+ console.log(`${component.name} [${component.kind}]`);
155
+ if (component.kind === 'enum') {
156
+ console.log(` ${component.enumValues.join(' | ')}`);
157
+ }
158
+ for (const field of component.fields) console.log(formatField(field));
159
+ break;
160
+ }
161
+
162
+ case 'components': {
163
+ const schema = lazySchema();
164
+ const entries = Object.values(schema.components);
165
+ for (const component of entries) {
166
+ const size =
167
+ component.kind === 'enum'
168
+ ? `${component.enumValues.length} values`
169
+ : `${component.fields.length} fields`;
170
+ console.log(`${component.kind.padEnd(6)} ${component.name} (${size})`);
171
+ }
172
+ console.log(`\n${entries.length} components`);
173
+ break;
174
+ }
175
+
176
+ case 'path': {
177
+ const schema = lazySchema();
178
+ const matches = Object.entries(schema.pathsIndex).filter(([urlPath]) =>
179
+ argument ? urlPath.includes(argument) : true,
180
+ );
181
+ for (const [urlPath, methods] of matches) {
182
+ console.log(urlPath);
183
+ for (const [method, info] of Object.entries(methods)) {
184
+ const suffix = info.paginated ? ' (paginated)' : '';
185
+ console.log(` ${method.padEnd(6)} -> ${info.component}${suffix}`);
186
+ }
187
+ }
188
+ console.log(`\n${matches.length} paths`);
189
+ break;
190
+ }
191
+
192
+ case 'entity': {
193
+ const entity = lazyEntities().find((e) => e.className === argument);
194
+ if (!entity) {
195
+ throw new Error(`no such entity class: ${argument}`);
196
+ }
197
+ console.log(`${entity.className} (${entity.file})`);
198
+ console.log(` @schema ${entity.schemaAnnotation ?? '-'}`);
199
+ console.log(` duck ${entity.duck ?? '-'}`);
200
+ console.log(` paginated ${entity.paginated}`);
201
+ console.log(` apiBase raw ${entity.apiBaseRaw ?? '-'}`);
202
+ console.log(
203
+ ` apiBase ${entity.apiBase ?? `- (${entity.apiBaseNote ?? 'none declared'})`}`,
204
+ );
205
+ console.log(` Fields type ${entity.fieldsTypeName ?? '-'}`);
206
+ console.log(` Record type ${entity.recordTypeName ?? '-'}`);
207
+ console.log(` fields (${entity.fields.length}):`);
208
+ for (const field of entity.fields) console.log(formatEntityField(field));
209
+ console.log(
210
+ ` Fields type members (${entity.fieldsTypeMembers.length}):`,
211
+ );
212
+ for (const member of entity.fieldsTypeMembers) {
213
+ console.log(
214
+ ` ${member.name}${member.optional ? '?' : ''}: ${member.typeText}`,
215
+ );
216
+ }
217
+ break;
218
+ }
219
+
220
+ case 'entities': {
221
+ const entities = lazyEntities();
222
+ for (const entity of entities) {
223
+ const base = entity.apiBase ?? (entity.apiBaseRaw ? 'UNRESOLVED' : '-');
224
+ console.log(
225
+ [
226
+ entity.className.padEnd(28),
227
+ (entity.duck ?? '-').padEnd(22),
228
+ `${entity.fields.length}f`.padEnd(5),
229
+ base,
230
+ entity.apiBaseNote ? ` !! ${entity.apiBaseNote}` : '',
231
+ ].join(' '),
232
+ );
233
+ }
234
+ console.log(`\n${entities.length} entity classes`);
235
+ break;
236
+ }
237
+
238
+ case 'errors': {
239
+ // Reads tsc's output on stdin:
240
+ // tsc --noEmit 2>&1 | entity-sync errors
241
+ printGroupedErrors(
242
+ groupAssertionErrors(
243
+ readFileSync(0, 'utf8'),
244
+ readFileSync(config.assertsFile, 'utf8'),
245
+ basename(config.assertsFile),
246
+ ),
247
+ );
248
+ break;
249
+ }
250
+
251
+ case 'enums': {
252
+ const schema = lazySchema();
253
+ const resolutions = resolveEnums({
254
+ enums: readEnums(config),
255
+ schema,
256
+ });
257
+
258
+ for (const resolution of resolutions) {
259
+ const wire = resolution.component
260
+ ? (schema.components[resolution.component]?.enumValues ?? [])
261
+ : [];
262
+ const dict = new Set(resolution.values);
263
+ const missing = wire.filter((value) => !dict.has(value));
264
+ const extra = resolution.component
265
+ ? resolution.values.filter((value) => !wire.includes(value))
266
+ : [];
267
+
268
+ const target = resolution.local
269
+ ? '(local)'
270
+ : `-> ${resolution.component ?? '(unresolved)'}`;
271
+
272
+ console.log(`\n${resolution.name} ${target} ${resolution.file}`);
273
+ console.log(` type: ${resolution.typeName ?? '(none exported)'}`);
274
+ console.log(` values: ${resolution.values.join(' | ')}`);
275
+ if (missing.length) console.log(` missing: ${missing.join(' | ')}`);
276
+ if (extra.length) console.log(` extra: ${extra.join(' | ')}`);
277
+ if (resolution.note) console.log(` note: ${resolution.note}`);
278
+ }
279
+
280
+ const tagged = resolutions.filter((r) => !r.local).length;
281
+ console.log(
282
+ `\n${resolutions.length} dicts, ${tagged} tagged with @schemaEnum`,
283
+ );
284
+ break;
285
+ }
286
+
287
+ default:
288
+ throw new Error(USAGE);
289
+ }
290
+ }