-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathverify-tokens.js
More file actions
217 lines (185 loc) · 7.59 KB
/
verify-tokens.js
File metadata and controls
217 lines (185 loc) · 7.59 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env node
import { readFileSync, writeFileSync, rmSync, existsSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { execSync } from 'child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log('🔍 Verifying generated tokens against DDG repository\n');
// Step 1: Clone or update DDG repository
const repoPath = '/tmp/ddg-repo-verify';
try {
if (existsSync(repoPath)) {
// Repository exists, fetch and reset to latest (better for shallow clones)
console.log('📥 Updating DDG repository...');
execSync('git fetch origin main && git reset --hard origin/main', {
cwd: repoPath,
stdio: 'pipe',
encoding: 'utf8',
});
console.log('✅ Repository updated\n');
} else {
// Repository doesn't exist, clone it
console.log('📥 Cloning DDG repository (shallow)...');
execSync(`git clone --depth 1 git@dub.duckduckgo.com:duckduckgo/ddg.git ${repoPath}`, {
stdio: 'pipe',
encoding: 'utf8',
});
console.log('✅ Repository cloned\n');
}
} catch (error) {
console.error('❌ Error with repository:', error.message);
process.exit(1);
}
// Step 2: Extract tokens from DDG repository
console.log('📤 Extracting tokens from DDG repository...');
const tokensPath = `${repoPath}/www-release/frontend/react/src/design-system/tokens/tokens.ts`;
let expectedData;
try {
// Create a temporary extraction script
const extractScript = `
import { dsTokensLight, dsTokensDark } from '${tokensPath}';
const output = {
dsTokensLight,
dsTokensDark
};
console.log(JSON.stringify(output, null, 2));
`.trim();
const tempScriptPath = '/tmp/extract-tokens-verify.ts';
writeFileSync(tempScriptPath, extractScript);
// Execute with tsx
const result = execSync(`npx tsx ${tempScriptPath}`, {
cwd: `${repoPath}/www-release/frontend/react`,
encoding: 'utf8',
maxBuffer: 10 * 1024 * 1024, // 10MB buffer
stdio: 'pipe',
});
expectedData = JSON.parse(result);
console.log(
`✅ Extracted ${Object.keys(expectedData.dsTokensLight).length} light tokens and ${Object.keys(expectedData.dsTokensDark).length} dark tokens\n`,
);
// Clean up temp script
rmSync(tempScriptPath, { force: true });
} catch (error) {
console.error('❌ Error extracting tokens:', error.message);
process.exit(1);
}
// Step 3: Read the generated tokens
const generatedPath = join(__dirname, 'build/serp/tokens-themes.json');
let generatedData;
try {
generatedData = JSON.parse(readFileSync(generatedPath, 'utf8'));
} catch (error) {
console.error('❌ Error: Could not read generated tokens file');
console.error(` Expected file at: ${generatedPath}`);
console.error(` Error: ${error.message}`);
process.exit(1);
}
// Step 4: Verification function
function verifyTokens(themeName, expectedTokens, generatedTokens) {
const errors = [];
const missing = [];
const mismatched = [];
// Check each expected token
for (const [key, expectedValue] of Object.entries(expectedTokens)) {
if (!(key in generatedTokens)) {
missing.push(key);
} else if (generatedTokens[key] !== expectedValue) {
mismatched.push({
key,
expected: expectedValue,
actual: generatedTokens[key],
});
}
}
return { missing, mismatched };
}
console.log('🔍 Verifying generated tokens...\n');
// Verify light theme
console.log('Checking dsTokensLight...');
const lightResults = verifyTokens('dsTokensLight', expectedData.dsTokensLight, generatedData.dsTokensLight);
// Verify dark theme
console.log('Checking dsTokensDark...');
const darkResults = verifyTokens('dsTokensDark', expectedData.dsTokensDark, generatedData.dsTokensDark);
// Report results
let hasErrors = false;
if (lightResults.missing.length > 0) {
hasErrors = true;
console.error('\n❌ Missing tokens in dsTokensLight:');
lightResults.missing.forEach((key) => console.error(` - ${key}`));
}
if (lightResults.mismatched.length > 0) {
hasErrors = true;
console.error('\n❌ Mismatched values in dsTokensLight:');
lightResults.mismatched.forEach(({ key, expected, actual }) => {
console.error(` - ${key}`);
console.error(` Expected: ${expected}`);
console.error(` Actual: ${actual}`);
});
}
if (darkResults.missing.length > 0) {
hasErrors = true;
console.error('\n❌ Missing tokens in dsTokensDark:');
darkResults.missing.forEach((key) => console.error(` - ${key}`));
}
if (darkResults.mismatched.length > 0) {
hasErrors = true;
console.error('\n❌ Mismatched values in dsTokensDark:');
darkResults.mismatched.forEach(({ key, expected, actual }) => {
console.error(` - ${key}`);
console.error(` Expected: ${expected}`);
console.error(` Actual: ${actual}`);
});
}
// Count additional tokens (not an error, just informational)
const expectedLightKeys = Object.keys(expectedData.dsTokensLight);
const generatedLightKeys = Object.keys(generatedData.dsTokensLight);
const additionalLightTokens = generatedLightKeys.filter((key) => !expectedLightKeys.includes(key));
const expectedDarkKeys = Object.keys(expectedData.dsTokensDark);
const generatedDarkKeys = Object.keys(generatedData.dsTokensDark);
const additionalDarkTokens = generatedDarkKeys.filter((key) => !expectedDarkKeys.includes(key));
if (additionalLightTokens.length > 0 || additionalDarkTokens.length > 0) {
console.log('\nℹ️ Additional tokens in generated output (this is OK):');
if (additionalLightTokens.length > 0) {
console.log(` dsTokensLight: ${additionalLightTokens.length} additional tokens`);
}
if (additionalDarkTokens.length > 0) {
console.log(` dsTokensDark: ${additionalDarkTokens.length} additional tokens`);
}
// Display the additional tokens grouped by category
console.log('\n📝 Additional tokens by category:\n');
const byCategory = {};
additionalLightTokens.forEach((token) => {
// Extract category (e.g., --sds-color-white -> color)
const parts = token.replace('--sds-', '').split('-');
const category = parts[0];
if (!byCategory[category]) {
byCategory[category] = [];
}
byCategory[category].push(token);
});
// Display grouped
Object.keys(byCategory)
.sort()
.forEach((category) => {
console.log(`${category.toUpperCase()} (${byCategory[category].length} tokens):`);
byCategory[category].forEach((token) => {
const value = generatedData.dsTokensLight[token];
const displayValue = typeof value === 'string' && value.length > 50 ? value.substring(0, 47) + '...' : value;
console.log(` ${token.replace('--sds-', '')}: ${displayValue}`);
});
console.log();
});
}
// Final result
if (hasErrors) {
console.error('\n❌ Verification FAILED: Some tokens are missing or have incorrect values\n');
process.exit(1);
} else {
console.log('\n✅ Verification PASSED: All required tokens match expected values');
console.log(` (Verified against live DDG repository)\n`);
console.log(` dsTokensLight: ${expectedLightKeys.length} tokens verified`);
console.log(` dsTokensDark: ${expectedDarkKeys.length} tokens verified`);
console.log(` Total generated: ${generatedLightKeys.length} light, ${generatedDarkKeys.length} dark\n`);
process.exit(0);
}