-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile-smartcode.js
More file actions
84 lines (74 loc) · 2.28 KB
/
Copy pathcompile-smartcode.js
File metadata and controls
84 lines (74 loc) · 2.28 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
/**
* Minifies src/smartCode.js and emits src/smartCode.generated.ts
* for import from WingifyScript (no backtick payload in the React file).
*/
const fs = require('fs');
const path = require('path');
const { minify } = require('terser');
const ROOT = path.join(__dirname, '..');
const SOURCE = path.join(ROOT, 'src/smartCode.js');
const OUTPUT = path.join(ROOT, 'src/smartCode.generated.ts');
const PLACEHOLDERS = {
accountId: '__WINGIFY_ACCOUNT_ID__',
settingsTimeout: '__WINGIFY_SETTINGS_TIMEOUT__',
hideElement: '__WINGIFY_HIDE_ELEMENT__',
hideElementStyle: '__WINGIFY_HIDE_ELEMENT_STYLE__',
};
async function main() {
const source = fs.readFileSync(SOURCE, 'utf8');
const result = await minify(source, {
// sequences:false keeps `function d()` at the bottom (original SmartCode order).
compress: { defaults: true, sequences: false },
mangle: true,
format: { comments: false },
// Browser snippet, not an ES module
module: false,
ecma: 5,
});
if (result.error) {
throw result.error;
}
if (!result.code) {
throw new Error('terser produced empty output for smartCode.js');
}
for (const token of Object.values(PLACEHOLDERS)) {
if (!result.code.includes(token)) {
throw new Error(
`Placeholder ${token} missing after minify — check src/smartCode.js`
);
}
}
const templateLiteral = JSON.stringify(result.code);
const out = `/* Generated by scripts/compile-smartcode.js — do not edit. */
export interface SmartCodeParams {
accountId: string;
settingsTimeout: number;
hideElement: string;
hideElementStyle: string;
}
const SMART_CODE_TEMPLATE = ${templateLiteral};
export function buildSmartCode(p: SmartCodeParams): string {
return SMART_CODE_TEMPLATE.replace(
/${PLACEHOLDERS.accountId}/g,
p.accountId
)
.replace(/${PLACEHOLDERS.settingsTimeout}/g, String(p.settingsTimeout))
.replace(
/["']${PLACEHOLDERS.hideElement}["']/g,
JSON.stringify(p.hideElement)
)
.replace(
/["']${PLACEHOLDERS.hideElementStyle}["']/g,
JSON.stringify(p.hideElementStyle)
);
}
`;
fs.writeFileSync(OUTPUT, out);
console.log(
`Wrote ${path.relative(ROOT, OUTPUT)} (${result.code.length} chars minified)`
);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});