@homepages/concrete 10.0.0 → 12.0.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 (121) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/codemods/manifest.json +7 -154
  3. package/dist/artifact/playground/client/assets/index-BcLGpWLR.js +1266 -0
  4. package/dist/artifact/playground/client/assets/index-CxWPYOH2.css +1 -0
  5. package/dist/artifact/playground/client/index.html +2 -2
  6. package/dist/artifact/playground/client/island-canvas-host.mjs +1 -1
  7. package/dist/artifact/playground/host.mjs +39 -40
  8. package/dist/base.css +18 -65
  9. package/dist/cli/build/artifact.js +1 -1
  10. package/dist/cli/build/fixtures.js +3 -2
  11. package/dist/cli/capture/capture.js +8 -6
  12. package/dist/cli/check/stages/sections.js +1 -1
  13. package/dist/cli/dev/workspace-reader.js +4 -2
  14. package/dist/css/compile.js +3 -6
  15. package/dist/css/rules.js +1 -51
  16. package/dist/design-system/format-variants.js +1 -1
  17. package/dist/fixtures/resolve.js +5 -1
  18. package/dist/fixtures/rows.js +2 -2
  19. package/dist/index.d.ts +5 -5
  20. package/dist/packages/external/concrete/package.js +1 -1
  21. package/dist/packages/internal/fill-bake/dist/compute-reads.js +1 -1
  22. package/dist/packages/internal/fill-bake/dist/held-rows.js +2 -0
  23. package/dist/packages/internal/fill-bake/dist/index.js +1 -0
  24. package/dist/packages/internal/fill-vocabulary/dist/holder.js +3 -14
  25. package/dist/packages/internal/format-geometry/dist/capture.js +3 -11
  26. package/dist/packages/internal/format-geometry/dist/format.d.ts +2 -8
  27. package/dist/packages/internal/format-geometry/dist/geometry.js +2 -13
  28. package/dist/packages/internal/media-resolution/dist/document.js +3 -3
  29. package/dist/packages/internal/media-resolution/dist/image.js +3 -3
  30. package/dist/packages/internal/media-resolution/dist/tour.js +6 -6
  31. package/dist/packages/internal/media-resolution/dist/video.js +9 -9
  32. package/dist/packages/internal/section-contracts/dist/fill-verb-contract.js +1 -0
  33. package/dist/packages/internal/section-contracts/dist/runners.js +1 -3
  34. package/dist/packages/internal/section-contracts/dist/source-contract.js +3 -3
  35. package/dist/packages/internal/section-contracts/dist/sources-contract.js +0 -2
  36. package/dist/packages/internal/template-artifact/dist/index.js +2 -2
  37. package/dist/packages/internal/template-artifact/dist/layout.js +11 -11
  38. package/dist/packages/internal/template-artifact/dist/manifest.js +1 -1
  39. package/dist/packages/internal/template-artifact/dist/verify.js +13 -17
  40. package/dist/packages/internal/template-contracts/dist/document-value.d.ts +3 -5
  41. package/dist/packages/internal/template-contracts/dist/fact-registry.js +1 -1
  42. package/dist/packages/internal/template-contracts/dist/fill-builders.js +2 -6
  43. package/dist/packages/internal/template-contracts/dist/fill-spec-schema.js +4 -1
  44. package/dist/packages/internal/template-contracts/dist/list.js +0 -14
  45. package/dist/packages/internal/template-contracts/dist/primitive-descriptors.js +1 -1
  46. package/dist/packages/internal/template-contracts/dist/runtime-values.d.ts +6 -7
  47. package/dist/packages/internal/template-contracts/dist/slot-builders.js +0 -2
  48. package/dist/packages/internal/template-contracts/dist/slot-ref.d.ts +6 -1
  49. package/dist/packages/internal/template-contracts/dist/tour-value.d.ts +2 -4
  50. package/dist/packages/internal/template-contracts/dist/video-value.d.ts +3 -4
  51. package/dist/primitives/FrameShell.d.ts +5 -2
  52. package/dist/primitives/FrameShell.js +2 -1
  53. package/dist/primitives/Image.d.ts +2 -2
  54. package/dist/primitives/Tour.d.ts +2 -2
  55. package/dist/primitives/Video.d.ts +2 -2
  56. package/dist/primitives/slot-bindings.js +6 -13
  57. package/dist/primitives/slot-document.d.ts +1 -1
  58. package/dist/primitives/slot-download.d.ts +3 -1
  59. package/dist/primitives/slot-media.d.ts +5 -2
  60. package/dist/primitives/slot-media.js +1 -1
  61. package/dist/rules/registry.js +1 -7
  62. package/dist/schema/format-presets.d.ts +1 -1
  63. package/dist/schema/format.d.ts +0 -1
  64. package/dist/schema/format.js +1 -2
  65. package/dist/schema/manifest.js +18 -24
  66. package/dist/schema/section-schema.d.ts +5 -5
  67. package/dist/site-analytics.js +6 -1
  68. package/dist/site-runtime/window-height.js +19 -0
  69. package/dist/styles.css +4 -4
  70. package/dist/template/define-template.d.ts +11 -0
  71. package/dist/template/define-template.js +1 -1
  72. package/dist/template/materialize.js +2 -0
  73. package/guide/reference/cli/INDEX.md +2 -2
  74. package/guide/reference/cli/build.md +1 -1
  75. package/guide/reference/cli/check.md +1 -1
  76. package/guide/reference/cli/dev.md +1 -1
  77. package/guide/reference/cli/property-add.md +1 -1
  78. package/guide/reference/cli/property-list.md +1 -1
  79. package/guide/reference/cli/publish.md +1 -1
  80. package/guide/reference/cli/upgrade.md +1 -1
  81. package/guide/reference/rules/INDEX.md +2 -3
  82. package/package.json +2 -2
  83. package/codemods/fill-is-a-source.mjs +0 -533
  84. package/codemods/framework-namespace.mjs +0 -107
  85. package/codemods/list-grammar.mjs +0 -923
  86. package/codemods/object-form-only.mjs +0 -39
  87. package/codemods/platform-namespace.mjs +0 -83
  88. package/codemods/process-builders.mjs +0 -198
  89. package/codemods/reads-replace-reconcile.mjs +0 -285
  90. package/codemods/registry-keys-only.mjs +0 -113
  91. package/codemods/slot-object.mjs +0 -1097
  92. package/codemods/steps/content-object-fields.mjs +0 -324
  93. package/codemods/steps/list-object-form.mjs +0 -686
  94. package/codemods/steps/registry-key-reads.mjs +0 -276
  95. package/codemods/steps/select-object-form.mjs +0 -210
  96. package/codemods/table-rows.mjs +0 -568
  97. package/codemods/theme-collapse.mjs +0 -396
  98. package/codemods/unlayer-author-css.mjs +0 -194
  99. package/codemods/unwrap-object-fields.mjs +0 -310
  100. package/codemods/viewer-slot-document.mjs +0 -131
  101. package/codemods/write-property-as-facts-document.mjs +0 -716
  102. package/codemods/write-the-address-line.mjs +0 -255
  103. package/codemods/write-the-registry-members.mjs +0 -653
  104. package/codemods/write-the-select-from.mjs +0 -141
  105. package/codemods/write-the-sole-from.mjs +0 -369
  106. package/codemods/write-the-table-from.mjs +0 -267
  107. package/codemods/write-the-whole-item.mjs +0 -512
  108. package/codemods/writeback-drop.mjs +0 -168
  109. package/codemods/written-contact-address.mjs +0 -162
  110. package/codemods/written-media-category.mjs +0 -227
  111. package/codemods/written-ref-kinds-name-the-layer.mjs +0 -172
  112. package/codemods/written-uploads-replace-pool-reads.mjs +0 -454
  113. package/codemods/written-uploads-sort-into-lists.mjs +0 -405
  114. package/codemods/written-uploads-stated-in-sorted-lists.mjs +0 -295
  115. package/codemods/written-video-sources-drop.mjs +0 -144
  116. package/codemods/written-without-pick-none.mjs +0 -146
  117. package/codemods/written-without-retired-knowledge.mjs +0 -223
  118. package/codemods/written-without-the-media-key.mjs +0 -202
  119. package/codemods/written-without-the-property-type.mjs +0 -249
  120. package/dist/artifact/playground/client/assets/index-BFNHB7VM.css +0 -1
  121. package/dist/artifact/playground/client/assets/index-Div1yo6s.js +0 -1259
@@ -1,276 +0,0 @@
1
- // A section reads a property's facts by their registry keys: the description as
2
- // `fact.property.description`, and a contact's or a unit's member through a row of its
3
- // table. `fact.description`, `fact.contact.<member>` and `fact.unit.<member>` are the
4
- // flat spellings that came before, which 10.0.0 removes.
5
- //
6
- // This is a codemod STEP: a workspace runs it by importing this file by path from the
7
- // installed package and calling its default export with the workspace root, and the
8
- // 10.0.0 codemod `registry-keys-only` runs it. It honors the release codemod contract:
9
- // `(root) => { rewritten, notRewritten }`.
10
- //
11
- // What it does, in every `.ts` and `.tsx` under the workspace that imports `fact` from
12
- // the package:
13
- //
14
- // - `fact.description` becomes `fact.property.description`, wherever it is read.
15
- // - Each section reading `fact.contact.<member>` or `fact.unit.<member>` declares the
16
- // table's first row once, before the statement that first reads it — `const contact =
17
- // row({ label: "Contact", from: fact.property.contacts, locked: true })` — as a
18
- // top-level slot of the section, and reads each member through it: `contact.phone`, in
19
- // a `source:`, a `compute()`'s `reads` and a fill's `reads` alike. The row is locked,
20
- // so the section keeps reading the first row, as the flat spelling did; no slot moves
21
- // or is renamed. The row's slot key is no name the section already uses anywhere, since
22
- // an item's row field is read by the same spelling (`primary_contact` beside an item's
23
- // `contact`). A unit's `unit_label` reads the row's `label`. A read at module level
24
- // belongs to the file's one section.
25
- // - Imports `row` where a rewrite uses it.
26
- //
27
- // A second run finds nothing left to rewrite.
28
- //
29
- // What it hands back, by line: a read of `fact.contact.address`, which the row answers
30
- // with an address value rather than one line of text, rewritten for you to finish; and,
31
- // left as written, a read outside any section in a file declaring none or several, a
32
- // section whose `slots` is not an object literal, and a read of a whole primary row.
33
-
34
- import { readdir, readFile, writeFile } from "node:fs/promises";
35
- import { join, relative, sep } from "node:path";
36
-
37
- import ts from "typescript";
38
-
39
- const CONCRETE = "@homepages/concrete";
40
-
41
- const EXTENSIONS = [".ts", ".tsx"];
42
- const SKIP_DIRS = new Set(["node_modules", ".concrete", ".git", "dist", "build"]);
43
-
44
- /** Each flat container and the table whose first row it read. */
45
- const TABLES = { contact: "contacts", unit: "units" };
46
-
47
- /** A flat member the table's row names otherwise. */
48
- const RENAMED = { unit: { unit_label: "label" } };
49
-
50
- async function sourceFiles(root) {
51
- const found = [];
52
- async function walk(dir) {
53
- for (const entry of await readdir(dir, { withFileTypes: true })) {
54
- if (entry.isDirectory()) {
55
- if (!SKIP_DIRS.has(entry.name)) await walk(join(dir, entry.name));
56
- } else if (EXTENSIONS.some((ext) => entry.name.endsWith(ext)) && !entry.name.endsWith(".d.ts")) {
57
- found.push(join(dir, entry.name));
58
- }
59
- }
60
- }
61
- await walk(root);
62
- return found.sort();
63
- }
64
-
65
- function lineOf(sf, node) {
66
- return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
67
- }
68
-
69
- function lineIndent(text, pos) {
70
- const start = text.lastIndexOf("\n", pos - 1) + 1;
71
- return /^[ \t]*/.exec(text.slice(start, pos))[0];
72
- }
73
-
74
- function propertyKey(property) {
75
- if (ts.isShorthandPropertyAssignment(property)) return property.name.text;
76
- if (!ts.isPropertyAssignment(property)) return undefined;
77
- const { name } = property;
78
- return ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : undefined;
79
- }
80
-
81
- /** Every name the file declares or imports, in any scope — a new const must shadow none. */
82
- function declaredNames(sf) {
83
- const names = new Set();
84
- const visit = (node) => {
85
- if ((ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isBindingElement(node)) && ts.isIdentifier(node.name)) names.add(node.name.text);
86
- if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && node.name !== undefined) names.add(node.name.text);
87
- if (ts.isImportSpecifier(node) || ts.isImportClause(node) || ts.isNamespaceImport(node)) if (node.name !== undefined) names.add(node.name.text);
88
- ts.forEachChild(node, visit);
89
- };
90
- visit(sf);
91
- return names;
92
- }
93
-
94
- const capitalized = (word) => word.charAt(0).toUpperCase() + word.slice(1);
95
-
96
- /** Text replacements that never overlap, applied last to first. */
97
- function applyEdits(text, edits) {
98
- let out = text;
99
- for (const e of [...edits].sort((a, b) => b.start - a.start || b.end - a.end)) out = out.slice(0, e.start) + e.text + out.slice(e.end);
100
- return out;
101
- }
102
-
103
- function rewrite(text, file) {
104
- if (!text.includes(CONCRETE)) return null;
105
- const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
106
-
107
- let host;
108
- const imported = new Map();
109
- for (const statement of sf.statements) {
110
- if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
111
- if (statement.moduleSpecifier.text !== CONCRETE) continue;
112
- const bindings = statement.importClause?.namedBindings;
113
- if (bindings === undefined || !ts.isNamedImports(bindings)) continue;
114
- if (!statement.importClause.isTypeOnly && host === undefined) host = statement;
115
- for (const element of bindings.elements) imported.set((element.propertyName ?? element.name).text, element.name.text);
116
- }
117
- const factName = imported.get("fact");
118
- if (factName === undefined) return null;
119
-
120
- // `fact.<name>` — the flat reads and nothing else off the namespace.
121
- const isFactAccess = (node, name) =>
122
- ts.isPropertyAccessExpression(node) && node.name.text === name && ts.isIdentifier(node.expression) && node.expression.text === factName;
123
-
124
- const edits = [];
125
- const manual = [];
126
- const refused = [];
127
- const rowReads = [];
128
- const visit = (node) => {
129
- if (isFactAccess(node, "description")) {
130
- edits.push({ start: node.getStart(sf), end: node.getEnd(), text: `${factName}.property.description` });
131
- return;
132
- }
133
- const container = Object.keys(TABLES).find((name) => isFactAccess(node, name));
134
- if (container !== undefined) {
135
- if (ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node) {
136
- rowReads.push({ container, read: node.parent });
137
- } else {
138
- refused.push(`\`${node.getText(sf)}\` at line ${String(lineOf(sf, node))} reads the whole primary ${container} — read its members through \`row({ label, from: ${factName}.property.${TABLES[container]}, locked: true })\``);
139
- }
140
- return;
141
- }
142
- ts.forEachChild(node, visit);
143
- };
144
- visit(sf);
145
- if (edits.length === 0 && rowReads.length === 0) return { text: null, manual, refused };
146
-
147
- const sectionName = imported.get("section");
148
- const sections = [];
149
- const findSections = (node) => {
150
- if (ts.isCallExpression(node) && sectionName !== undefined && ts.isIdentifier(node.expression) && node.expression.text === sectionName && node.arguments[0] !== undefined) {
151
- sections.push(node);
152
- }
153
- ts.forEachChild(node, findSections);
154
- };
155
- findSections(sf);
156
- const within = (node, outer) => node.getStart(sf) >= outer.getStart(sf) && node.getEnd() <= outer.getEnd();
157
- const topStatement = (node) => {
158
- let at = node;
159
- while (at.parent !== sf) at = at.parent;
160
- return at;
161
- };
162
-
163
- // Each read by section and container; a module-level read belongs to the file's one section.
164
- const bySection = new Map();
165
- for (const entry of rowReads) {
166
- let section = sections.find((call) => within(entry.read, call.arguments[0]));
167
- if (section === undefined) {
168
- if (sections.length !== 1) {
169
- refused.push(`\`${entry.read.getText(sf)}\` at line ${String(lineOf(sf, entry.read))} is read outside a section, in a file declaring ${sections.length === 0 ? "none" : "several"} — declare the row in the section that reads it`);
170
- continue;
171
- }
172
- section = sections[0];
173
- }
174
- const perSection = bySection.get(section) ?? new Map();
175
- bySection.set(section, perSection);
176
- const list = perSection.get(entry.container) ?? [];
177
- list.push(entry.read);
178
- perSection.set(entry.container, list);
179
- }
180
-
181
- const names = declaredNames(sf);
182
- const declarationsBefore = new Map();
183
- let usesRow = false;
184
- for (const [section, perSection] of bySection) {
185
- const options = section.arguments[0];
186
- const slotsProperty = ts.isObjectLiteralExpression(options) ? options.properties.find((p) => propertyKey(p) === "slots") : undefined;
187
- const slots = slotsProperty !== undefined && ts.isPropertyAssignment(slotsProperty) && ts.isObjectLiteralExpression(slotsProperty.initializer) ? slotsProperty.initializer : undefined;
188
- if (slots === undefined) {
189
- for (const container of perSection.keys()) {
190
- refused.push(`the section at line ${String(lineOf(sf, section))} reads \`${factName}.${container}\`, but its \`slots\` is not an object literal this codemod can read — declare the row by hand`);
191
- }
192
- continue;
193
- }
194
- // A read of a row slot names it by key alone, and an item's row field is read by the same
195
- // spelling, so the new slot's key is no name the section's declaration or the file
196
- // already uses anywhere.
197
- const taken = new Set(names);
198
- const collectKeys = (node) => {
199
- if (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) {
200
- const key = propertyKey(node);
201
- if (key !== undefined) taken.add(key);
202
- }
203
- ts.forEachChild(node, collectKeys);
204
- };
205
- collectKeys(options);
206
- const entries = [];
207
- for (const [container, reads] of perSection) {
208
- const table = TABLES[container];
209
- let constName = container;
210
- for (let n = 1; names.has(constName); n += 1) constName = `primary${capitalized(container)}${n === 1 ? "" : String(n)}`;
211
- names.add(constName);
212
- let key = container;
213
- for (let n = 1; taken.has(key); n += 1) key = `primary_${container}${n === 1 ? "" : `_${String(n)}`}`;
214
- taken.add(key);
215
-
216
- for (const read of reads) {
217
- const member = RENAMED[container]?.[read.name.text] ?? read.name.text;
218
- edits.push({ start: read.getStart(sf), end: read.getEnd(), text: `${constName}.${member}` });
219
- if (container === "contact" && read.name.text === "address") {
220
- manual.push(
221
- `line ${String(lineOf(sf, read))} now reads \`${constName}.address\`, the contact's address value rather than one line of text — bind a text slot reading it as \`address({ label, source: ${constName}.address })\` and print it in \`Slot.Address\`, and handle the value or \`null\` in a \`compute()\``,
222
- );
223
- }
224
- }
225
- const first = topStatement(reads.reduce((earliest, read) => (read.getStart(sf) < earliest.getStart(sf) ? read : earliest)));
226
- const statement = first.getStart(sf) < topStatement(section).getStart(sf) ? first : topStatement(section);
227
- const declarations = declarationsBefore.get(statement) ?? [];
228
- declarations.push(`const ${constName} = row({ label: ${JSON.stringify(capitalized(container))}, from: ${factName}.property.${table}, locked: true });`);
229
- declarationsBefore.set(statement, declarations);
230
- entries.push(key === constName ? constName : `${key}: ${constName}`);
231
- usesRow = true;
232
- }
233
- const firstSlot = slots.properties[0];
234
- const indent = firstSlot === undefined ? "" : lineIndent(text, firstSlot.getStart(sf));
235
- // Above the first slot's comments, which stay with it.
236
- const slotComments = firstSlot === undefined ? [] : (ts.getLeadingCommentRanges(text, firstSlot.getFullStart()) ?? []);
237
- const at = firstSlot === undefined ? slots.getStart(sf) + 1 : slotComments.length > 0 ? slotComments[0].pos : firstSlot.getStart(sf);
238
- edits.push({ start: at, end: at, text: entries.map((entry) => `${entry},\n${indent}`).join("") });
239
- }
240
-
241
- // The rows, each declared once before the statement that first reads it, above its comments.
242
- for (const [statement, declarations] of declarationsBefore) {
243
- const comments = ts.getLeadingCommentRanges(text, statement.getFullStart()) ?? [];
244
- const start = comments.length > 0 ? comments[0].pos : statement.getStart(sf);
245
- edits.push({ start, end: start, text: `${declarations.join("\n")}\n\n` });
246
- }
247
-
248
- if (usesRow && !imported.has("row")) {
249
- const bindings = host.importClause.namedBindings;
250
- const kept = bindings.elements.map((element) => element.getText(sf));
251
- const all = [...kept, "row"].sort((a, b) => a.replace(/^type\s+/, "").localeCompare(b.replace(/^type\s+/, ""), "en", { sensitivity: "base" }));
252
- const multiline = bindings.getText(sf).includes("\n");
253
- const indent = lineIndent(text, bindings.elements[0]?.getStart(sf) ?? bindings.getStart(sf));
254
- edits.push({ start: bindings.getStart(sf), end: bindings.getEnd(), text: multiline ? `{\n${all.map((k) => `${indent}${k},`).join("\n")}\n}` : `{ ${all.join(", ")} }` });
255
- }
256
- return { text: applyEdits(text, edits), manual, refused };
257
- }
258
-
259
- /** @param {string} root @returns {Promise<{rewritten: string[], notRewritten: {file: string, reason: string}[]}>} */
260
- export default async function registryKeyReads(root) {
261
- const rewritten = [];
262
- const notRewritten = [];
263
- const name = (file) => relative(root, file).split(sep).join("/");
264
- for (const file of await sourceFiles(root)) {
265
- const text = await readFile(file, "utf8");
266
- const result = rewrite(text, file);
267
- if (result === null) continue;
268
- if (result.text !== null && result.text !== text) {
269
- await writeFile(file, result.text, "utf8");
270
- rewritten.push(name(file));
271
- }
272
- for (const reason of new Set(result.manual)) notRewritten.push({ file: name(file), reason: `Manual: ${reason}` });
273
- for (const reason of new Set(result.refused)) notRewritten.push({ file: name(file), reason });
274
- }
275
- return { rewritten, notRewritten };
276
- }
@@ -1,210 +0,0 @@
1
- // A select takes one options object, like every other slot builder.
2
- //
3
- // `select.of(values, opts)` and the display entry's positional `select(cases, opts)`
4
- // became the object form: `select({ label, options, … })` for a slot, a row field or a
5
- // list's item, and `select({ options, source, locked? })` under `display:`. Both old
6
- // forms emitted exactly what the object form does, so a rewritten section's schema is
7
- // unchanged.
8
- //
9
- // This is a codemod STEP, not a release's codemod: it shipped with the minor that
10
- // deprecated the old forms, which could ship no codemod of its own, and 7.0.0's
11
- // `object-form-only` codemod — the release that removed them — runs it in its own pass.
12
- // A workspace can also run it alone: it is not an export, so import this file by path
13
- // from the installed package
14
- // (`node_modules/@homepages/concrete/codemods/steps/select-object-form.mjs`) and call
15
- // its default export with the workspace root. It honors the contract a release codemod
16
- // does: `(root) => { rewritten, notRewritten }`.
17
- //
18
- // What it rewrites, in every `.ts` and `.tsx` under the workspace that imports `select`
19
- // from the framework:
20
- //
21
- // - `select.of(VALUES, { label, … })` → `select({ label, options: VALUES, … })`
22
- // - `select(CASES, { … })` → `select({ options: CASES, … })`
23
- // - `select(CASES)` → `select({ options: CASES })`
24
- //
25
- // What it leaves to you, reported per file: a call whose options argument is not an
26
- // object literal written in place (`select.of(VALUES, OPTS)`), since the options must
27
- // be merged into it by hand.
28
-
29
- import { readdir, readFile, writeFile } from "node:fs/promises";
30
- import { join, relative, sep } from "node:path";
31
-
32
- import ts from "typescript";
33
-
34
- const CONCRETE = "@homepages/concrete";
35
-
36
- const EXTENSIONS = [".ts", ".tsx"];
37
- const SKIP_DIRS = new Set(["node_modules", ".concrete", ".git", "dist", "build"]);
38
-
39
- async function sourceFiles(root) {
40
- const found = [];
41
- async function walk(dir) {
42
- for (const entry of await readdir(dir, { withFileTypes: true })) {
43
- if (entry.isDirectory()) {
44
- if (!SKIP_DIRS.has(entry.name)) await walk(join(dir, entry.name));
45
- } else if (EXTENSIONS.some((ext) => entry.name.endsWith(ext)) && !entry.name.endsWith(".d.ts")) {
46
- found.push(join(dir, entry.name));
47
- }
48
- }
49
- }
50
- await walk(root);
51
- return found.sort();
52
- }
53
-
54
- function lineOf(sf, pos) {
55
- return sf.getLineAndCharacterOfPosition(pos).line + 1;
56
- }
57
-
58
- /** The names this file reaches the framework's `select` by: `{ select }` / `{ select as s }`, or a namespace `c` (`c.select`). */
59
- function selectBindings(sf) {
60
- const locals = new Set();
61
- const namespaces = new Set();
62
- for (const statement of sf.statements) {
63
- if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly) continue;
64
- if (!ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== CONCRETE) continue;
65
- const bindings = statement.importClause?.namedBindings;
66
- if (bindings === undefined) continue;
67
- if (ts.isNamespaceImport(bindings)) {
68
- namespaces.add(bindings.name.text);
69
- continue;
70
- }
71
- for (const element of bindings.elements) {
72
- if (element.isTypeOnly) continue;
73
- if ((element.propertyName ?? element.name).text === "select") locals.add(element.name.text);
74
- }
75
- }
76
- return { locals, namespaces };
77
- }
78
-
79
- function isSelectRef(node, { locals, namespaces }) {
80
- if (ts.isIdentifier(node)) return locals.has(node.text);
81
- return (
82
- ts.isPropertyAccessExpression(node) &&
83
- node.name.text === "select" &&
84
- ts.isIdentifier(node.expression) &&
85
- namespaces.has(node.expression.text)
86
- );
87
- }
88
-
89
- /** The whitespace a line starts with. */
90
- function indentAt(text, pos) {
91
- const lineStart = text.lastIndexOf("\n", pos - 1) + 1;
92
- return /^[ \t]*/.exec(text.slice(lineStart))[0];
93
- }
94
-
95
- /**
96
- * The edit that writes `options: <choices>` into an object literal: after its `label`
97
- * when `afterLabel` and it has one, else as its first property — on a line of its own
98
- * when the literal spans lines, inline when it does not.
99
- */
100
- function insertOption(sf, literal, choices, afterLabel) {
101
- const text = sf.text;
102
- const entry = `options: ${choices}`;
103
- const multiline = text.slice(literal.getStart(sf), literal.getEnd()).includes("\n");
104
- const label = afterLabel
105
- ? literal.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText(sf) === "label")
106
- : undefined;
107
-
108
- if (label !== undefined) {
109
- let at = label.getEnd();
110
- const hasComma = text[at] === ",";
111
- if (!multiline) return { start: at, end: at, text: `, ${entry}` };
112
- if (hasComma) at += 1;
113
- return { start: at, end: at, text: `${hasComma ? "" : ","}\n${indentAt(text, label.getStart(sf))}${entry}${hasComma ? "," : ""}` };
114
- }
115
-
116
- const open = literal.getStart(sf) + 1;
117
- const first = literal.properties[0];
118
- if (first === undefined) return { start: open, end: literal.getEnd() - 1, text: ` ${entry} ` };
119
- if (!multiline) return { start: open, end: first.getStart(sf), text: ` ${entry}, ` };
120
- return { start: open, end: open, text: `\n${indentAt(text, first.getStart(sf))}${entry},` };
121
- }
122
-
123
- /** The edits that rewrite one old-form call, or the reason it is the author's. */
124
- function rewriteCall(sf, call, bindings) {
125
- const callee = call.expression;
126
- const selectOf =
127
- ts.isPropertyAccessExpression(callee) && callee.name.text === "of" && isSelectRef(callee.expression, bindings);
128
- const positional =
129
- !selectOf &&
130
- isSelectRef(callee, bindings) &&
131
- call.arguments.length >= 1 &&
132
- !ts.isObjectLiteralExpression(call.arguments[0]);
133
- if (!selectOf && !positional) return undefined;
134
-
135
- const [choices, options] = call.arguments;
136
- const what = selectOf ? "`select.of`" : "a positional `select`";
137
- if (choices === undefined || call.arguments.length > 2) {
138
- return { reason: `${what} on line ${lineOf(sf, call.getStart(sf))} has an unexpected argument list` };
139
- }
140
- const choicesText = choices.getText(sf);
141
- const edits = [];
142
- if (selectOf) edits.push({ start: callee.getStart(sf), end: callee.getEnd(), text: callee.expression.getText(sf) });
143
-
144
- if (options === undefined) {
145
- edits.push({ start: choices.getStart(sf), end: choices.getEnd(), text: `{ options: ${choicesText} }` });
146
- return { edits };
147
- }
148
- if (!ts.isObjectLiteralExpression(options)) {
149
- return {
150
- reason:
151
- `${what} on line ${lineOf(sf, call.getStart(sf))} passes its options as \`${options.getText(sf)}\`, ` +
152
- `not an object literal — write \`${selectOf ? "select({ …, options: <values> })" : "select({ options: <cases>, … })"}\` by hand`,
153
- };
154
- }
155
- // The choices argument and the separator after it, up to where the options begin.
156
- edits.push({ start: choices.getStart(sf), end: options.getStart(sf), text: "" });
157
- edits.push(insertOption(sf, options, choicesText, selectOf));
158
- return { edits };
159
- }
160
-
161
- function applyEdits(text, edits) {
162
- const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end);
163
- let out = text;
164
- let floor = Infinity;
165
- for (const edit of sorted) {
166
- if (edit.end > floor) throw new Error("overlapping select rewrites");
167
- out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
168
- floor = edit.start;
169
- }
170
- return out;
171
- }
172
-
173
- /** Rewrites one file's text; `undefined` when it holds no old-form select. */
174
- export function rewriteSource(fileName, text) {
175
- const kind = fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
176
- const sf = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, kind);
177
- const bindings = selectBindings(sf);
178
- if (bindings.locals.size === 0 && bindings.namespaces.size === 0) return undefined;
179
-
180
- const edits = [];
181
- const reasons = [];
182
- const visit = (node) => {
183
- if (ts.isCallExpression(node)) {
184
- const result = rewriteCall(sf, node, bindings);
185
- if (result?.edits !== undefined) edits.push(...result.edits);
186
- if (result?.reason !== undefined) reasons.push(result.reason);
187
- }
188
- ts.forEachChild(node, visit);
189
- };
190
- visit(sf);
191
- if (edits.length === 0 && reasons.length === 0) return undefined;
192
- return { text: edits.length > 0 ? applyEdits(text, edits) : text, changed: edits.length > 0, reasons };
193
- }
194
-
195
- export default async function selectObjectForm(root) {
196
- const rewritten = [];
197
- const notRewritten = [];
198
- for (const file of await sourceFiles(root)) {
199
- const before = await readFile(file, "utf8");
200
- const result = rewriteSource(file, before);
201
- if (result === undefined) continue;
202
- const rel = relative(root, file).split(sep).join("/");
203
- if (result.changed) {
204
- await writeFile(file, result.text, "utf8");
205
- rewritten.push(rel);
206
- }
207
- if (result.reasons.length > 0) notRewritten.push({ file: rel, reason: result.reasons.join("; ") });
208
- }
209
- return { rewritten, notRewritten };
210
- }