-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJitEnv.js
354 lines (296 loc) · 10.9 KB
/
JitEnv.js
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
const { cyanBright } = require('chalk');
const chokidar = require('chokidar');
const fs = require('fs');
const path = require('path');
/**
* Generate inject target script
* @param {...string} after - Anything to inject after the injection point
* @returns The inject target script
*/
const pageScript = (...after) => `<meta name="jit-env-data" content="___INJECT_ENV___">
<script>
፡// jit-env
፡window.env = window.document.head.querySelector('meta[name="jit-env-data"]').content;${after.reduce((a, b) => `${a}\n፡${b}`, '')}
፡if (/_{3}INJECT_ENV_{3}/.test(window.env)) {
፡፡delete window.env;
፡፡throw new Error("[JIT-ENV] Missing env");
፡} else {
፡፡try {
፡፡፡window.env = atob(window.env); // Decode base64 data
፡፡፡window.env = JSON.parse(window.env); // Parse JSON data
፡፡} catch (e) {
፡፡፡console.error(e);
፡፡፡console.log("[JIT-ENV] Tried to parse:", window.env);
፡፡፡delete window.env;
፡፡፡throw new Error("[JIT-ENV] Failed to parse");
፡፡}
፡}
</script>`;
/**
* Base file format for env type declaration file
* @param {string} t - Type data
* @returns
*/
const typeDeclarationTemplate = (t) => `// This file was generated by JitEnv.
//
// If this file causes linting issues, you can pass a linting disable string
// with the emitTypesPrefix option.
if (window.env === undefined) {
throw new Error("[JIT-ENV] Missing env");
}
export const env: Window['env'] = window.env;
declare global {
interface Window {
env: ${t.replace(/\n/g, '\n ')};
}
}
`;
/**
* Options for jit-env
* @typedef {Object} JitEnvOptions
* @property {string} [defaultEnv] a fallback env file to use
* @property {string} [userEnv] the user's env path
* @property {string} [emitTypes] emit a TypeScript types file based on defaultEnv
* @property {string} [emitTypesPrefix] add something to the beginning of the emitTypes file (usefull to disable linters etc.)
* @property {boolean} [emitTypesNonOptional] emit the types as non-optional type definitions (i.e. instead of prop?: Type, we emit prop: Type)
*/
module.exports = class JitEnv {
// Sanitized options
defaultEnv = undefined;
userEnv = undefined;
emitTypes = undefined;
emitTypesPrefix = undefined;
emitTypesNonOptional = undefined;
// Raw user options (for logging)
_defaultEnv = undefined;
_userEnv = undefined;
_emitTypes = undefined;
_emitTypesNonOptional = undefined;
// File watchers
watching = new Map();
// Blocker flag for init
finalized = false;
/**
* Create a plugin instance
* @param {JitEnvOptions} options
*/
constructor(options = {}, requestUpdate) {
// Save raw options
this._defaultEnv = options.defaultEnv;
this._userEnv = options.userEnv;
this._emitTypes = options.emitTypes;
this._emitTypesNonOptional = options.emitTypesNonOptional;
// Save instance options
this.defaultEnv = JitEnv.fullPath(options.defaultEnv);
this.userEnv = JitEnv.fullPath(options.userEnv);
this.emitTypes = JitEnv.fullPath(options.emitTypes);
this.emitTypesPrefix = options.emitTypesPrefix;
this.emitTypesNonOptional = !!this._emitTypesNonOptional;
// Ensure update hook
if (typeof requestUpdate !== 'function') {
throw new Error(`Unexpected missing JitEnv hook: requestUpdate`);
}
// Register update hook
this.requestUpdate = requestUpdate;
// Watch default env
if (this.defaultEnv !== undefined) {
this.watch(this.defaultEnv);
}
// Watch user env
if (this.userEnv !== undefined) {
this.watch(this.userEnv);
}
// Mark JitEnv ready
this.finalized = true;
}
/**
* Hook for JitEnv to queue an update of the HTML file(s) to be called internally
*/
internalRequestUpdate = (path) => {
if (this.finalized) {
const splitPath = path.split(process.cwd());
const cleanPath = splitPath.length > 1 ? splitPath[1].replace(/^[\\\/]?/, '') : splitPath[0];
console.log(`${cyanBright('File changed:')} ${cleanPath}`);
this.requestUpdate();
}
}
/**
* Hook for JitEnv to queue an update of the HTML file(s)
*/
requestUpdate() {
throw new Error(`Unexpected missing JitEnv hook: requestUpdate`);
}
/**
* Transform hook to be called externally to add the injection point to the provided html
* @param {string} html - HTML input
* @returns {string} - Transformed HTML output
*/
transform = (html) => this.addEnvInjection(html);
/**
* Hook for JitEnv to watch a file (will only be called once per path)
* @param {string} path
*/
watch(path) {
if (!this.watching.has(path)) {
const watcher = chokidar.watch(path, { ignoreInitial: true });
// Save watcher
this.watching.set(path, watcher);
// Add watch handlers
watcher.on('change', this.internalRequestUpdate);
watcher.on('add', this.internalRequestUpdate);
watcher.on('unlink', this.internalRequestUpdate);
}
}
/**
* Resolve a user supplied path to a full path
* @param {string} p - Input path
* @returns {string}
*/
static fullPath(p) {
return typeof p === "string" ? path.resolve(process.cwd(), p) : undefined;
}
/****************************************************
* OLD PLUGIN STUFF BELOW *
****************************************************/
addEnvInjection = (html) => {
// Get indentation data
const indentation = this.getIndentation(html);
// Generate indentation strings
const indentString = Array(indentation.head - indentation.preHead + 1).join(indentation.char);
const indentPre = Array(indentation.head + 1).join(indentation.char);
// Save warnings for console and browser console
const warnings = [];
// Pick env data to inject
let envData;
if (this.userEnv) {
// Use user env if exists
if (fs.existsSync(this.userEnv)) {
const data = fs.readFileSync(this.userEnv, 'utf8');
try {
envData = JSON.parse(data);
} catch (_) {
warnings.push(`Could not parse user env from ${JSON.stringify(this._userEnv)} (invalid JSON)`);
}
} else {
warnings.push(`Could not find user env at ${JSON.stringify(this._userEnv)}`);
}
}
if (envData === undefined && this.defaultEnv) {
// Fall back to default env
if (fs.existsSync(this.defaultEnv)) {
const data = fs.readFileSync(this.defaultEnv, 'utf8');
try {
envData = JSON.parse(data);
} catch (_) {
warnings.push(`Could not parse default env from ${JSON.stringify(this._defaultEnv)} (invalid JSON)`);
}
} else {
warnings.push(`Could not find default env at ${JSON.stringify(this._defaultEnv)}`);
}
}
// Emit types if relevant
warnings.push(...this.tryEmitTypes());
// Get script to inject into page
const pageInjectable = pageScript(
...warnings.map((w) => `console.warn(${JSON.stringify(`[JIT-ENV] ${w}`)});`),
);
// Print warnings to console
warnings.forEach((w) => {
console.warn(w);
});
// Add injectable
let injectable = `${indentPre}${pageInjectable.replace(/\n/g, `\n${indentPre}`)}`;
if (envData !== undefined) {
const envString = Buffer.from(JSON.stringify(envData)).toString('base64');
injectable = injectable.replace(/___INJECT_ENV___/, envString);
}
// Return script
return html.replace(/(<head.*?>)/, `$1\n${injectable.replace(/፡/g, indentString)}`);
}
envToTypeReviver = (_, v) => {
if (typeof v === "object") {
if (Array.isArray(v)) {
return v.map(
(n) => JSON.stringify(n),
).filter(
(n, i, a) => a.indexOf(n) === i,
).sort().map(
(n) => JSON.parse(n),
);
}
return v;
}
return typeof v;
};
tryEmitTypes = () => {
if (!this.emitTypes) {
return [];
}
if (!this.defaultEnv) {
return ['Could not emit types because defaultEnv is not configured.'];
}
if (!fs.existsSync(this.defaultEnv)) {
return ['Could not emit types because default env could not be found.'];
}
const data = fs.readFileSync(this.defaultEnv, 'utf8');
let defaultEnv;
try {
defaultEnv = JSON.parse(data, this.envToTypeReviver);
} catch (e) {
return ['Could not emit types because default env could not be parsed.']
}
let types = typeDeclarationTemplate(this.typeObjToTypedef(defaultEnv));
if (this.emitTypesPrefix !== undefined) {
types = `${this.emitTypesPrefix}\n${types}`;
}
let prevTypes;
try {
prevTypes = fs.readFileSync(this.emitTypes).toString();
} catch (e) {
console.warn(`File ${JSON.stringify(this._emitTypes)} not found. Creating it now...`);
};
if (prevTypes !== types) {
fs.writeFileSync(this.emitTypes, types);
}
return [];
}
typeObjToTypedef = (o) => {
if (typeof o === "string") {
return o;
}
if (Array.isArray(o)) {
if (o.length === 0) {
return '[]';
}
if (o.length === 1) {
return `${this.typeObjToTypedef(o[0])}[]`;
}
return `(${o.map((v) => this.typeObjToTypedef(v)).join(' | ')})[]`;
}
if (typeof o === "object") {
if (o === null) {
return 'null';
}
if (Object.keys(o) === 0) {
return '{}';
}
return '{\n' + Object.keys(o).map((k) => ` "${k}"${this.emitTypesNonOptional ? '' : '?'}: ${this.typeObjToTypedef(o[k]).replace(/\n/g, '\n ')}`).join(';\n') + ';\n}';
}
throw new Error(`Unexpected typeof typeObj: ${typeof o}`);
}
getIndentation = (html) => {
const results = /([\t ]*)<head.*?>.*?\n([\t ]*)</.exec(html);
if (!results || results[1] === undefined || results[2] === undefined) {
return {
preHead: 0,
head: 4,
char: ' ',
};
}
return {
preHead: results[1].length,
head: results[2].length,
char: results[2].length > 0 ? results[2][0] : ' ',
}
}
};