-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconst-declaration-updater.js
More file actions
189 lines (151 loc) · 4.3 KB
/
Copy pathconst-declaration-updater.js
File metadata and controls
189 lines (151 loc) · 4.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const fs = require("node:fs").promises;
class ConstDeclarationUpdater {
constructor({ fileSystem } = {}) {
this.fileSystem = fileSystem ?? fs;
}
async update(filePath, declarations) {
if (!Array.isArray(declarations)) {
throw new Error(
"ConstDeclarationUpdater expected 'declarations' to be an array.",
);
}
if (declarations.length === 0) {
return false;
}
const originalContent = await this.fileSystem.readFile(filePath, "utf8");
let updatedContent = originalContent;
let hasChanges = false;
for (const declaration of declarations) {
const serializedValue = this.resolveSerializedValue(declaration);
const nextContent = replaceConstDeclaration(
updatedContent,
declaration.name,
serializedValue,
);
if (nextContent !== updatedContent) {
hasChanges = true;
updatedContent = nextContent;
}
}
if (hasChanges) {
await this.fileSystem.writeFile(filePath, updatedContent, "utf8");
}
return hasChanges;
}
resolveSerializedValue(declaration) {
if (!declaration || typeof declaration !== "object") {
throw new Error(
"ConstDeclarationUpdater expected each declaration to be an object.",
);
}
const { name, serializedValue } = declaration;
if (!name) {
throw new Error(
"Const declaration update requires a declaration 'name'.",
);
}
if (typeof serializedValue === "string") {
return serializedValue;
}
if ("value" in declaration) {
const serializer =
typeof declaration.serialize === "function"
? declaration.serialize
: (value) => serializeForTs(value);
const serialized = serializer(declaration.value);
if (typeof serialized !== "string") {
throw new Error(`Serializer for '${name}' must return a string.`);
}
return serialized;
}
throw new Error(
`Const declaration update for '${name}' requires either 'value' or 'serializedValue'.`,
);
}
}
function replaceConstDeclaration(source, name, serializedValue) {
const pattern = new RegExp(
`(?<indent>^\\s*)(?<exportKeyword>export\\s+)?const ${name}(?<annotation>:[^=]+)? = [\\s\\S]*?;`,
"m",
);
const match = pattern.exec(source);
if (!match) {
throw new Error(
`Unable to locate '${name}' declaration in source file for update.`,
);
}
const {
indent = "",
annotation = "",
exportKeyword = "",
} = match.groups ?? {};
const indentedValue = applyIndent(serializedValue, indent);
const replacement = `${indent}${
exportKeyword ?? ""
}const ${name}${annotation} = ${indentedValue};`;
return (
source.slice(0, match.index) +
replacement +
source.slice(match.index + match[0].length)
);
}
function applyIndent(value, indent) {
if (!indent) {
return value;
}
return value
.split("\n")
.map((line, index) => (index === 0 ? line : `${indent}${line}`))
.join("\n");
}
function serializeForTs(value, indentLevel = 0) {
const indent = " ".repeat(indentLevel);
if (Array.isArray(value)) {
if (value.length === 0) {
return "[]";
}
const items = value
.map((item) => serializeForTs(item, indentLevel + 1))
.map((item) => `${" ".repeat(indentLevel + 1)}${item}`)
.join(",\n");
return `[\n${items}\n${indent}]`;
}
if (value && typeof value === "object") {
const entries = Object.entries(value);
if (entries.length === 0) {
return "{}";
}
const body = entries
.map(
([key, val]) =>
`${" ".repeat(indentLevel + 1)}${key}: ${serializeForTs(
val,
indentLevel + 1,
)}`,
)
.join(",\n");
return `{\n${body}\n${indent}}`;
}
if (typeof value === "string") {
return `'${escapeString(value)}'`;
}
if (typeof value === "number" || typeof value === "boolean") {
return String(value);
}
if (value === null) {
return "null";
}
throw new Error(`Unsupported value type for serialization: ${typeof value}`);
}
function escapeString(value) {
return value
.replace(/\\/g, "\\\\")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/'/g, "\\'");
}
module.exports = {
ConstDeclarationUpdater,
serializeForTs,
};