This repository has been archived by the owner on Jul 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbundler_old.js
346 lines (331 loc) · 11.2 KB
/
bundler_old.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
const consoleFormat = {
RESET: "\x1b[0m", INVISIBLE: "\x1b[8m",
BOLD: "\x1b[1m", LIGHT: "\x1b[2m", ITALIC: "\x1b[3m", UNDERLINE: "\x1b[4m",
SLOW_BLINK: "\x1b[5m", FAST_BLINK: "\x1b[6m",
BLACK: "\x1b[30m", RED: "\x1b[31m", GREEN: "\x1b[32m", YELLOW: "\x1b[33m", BLUE: "\x1b[34m", PINK: "\x1b[35m",AQUA: "\x1b[36m", GRAY: "\x1b[37m",
}; // prettier-ignore
function say(message) {
console.error(`${formatMessage(message)}`);
}
function warn(message) {
console.warn(`${formatMessage(message, "warn")}`);
}
function error(message) {
console.error(`${formatMessage(message, "error")}`);
}
function fatal(message) {
console.error(`${formatMessage(message, "fatal")}`);
process.exit();
}
function formatMessage(message, type) {
const prefixes = {
tag: `${consoleFormat.BLUE}AUAUST${consoleFormat.GRAY}`,
types: {
default: ` ${consoleFormat.RESET}OK! ${consoleFormat.GRAY}`,
warn: ` ${consoleFormat.YELLOW}WRN ${consoleFormat.GRAY}`,
error: ` ${consoleFormat.RED}ERR ${consoleFormat.GRAY}`,
fatal: ` ${consoleFormat.RED}FATAL ERROR! ${consoleFormat.GRAY}`,
},
};
if (typeof message !== "string") {
message = `${JSON.stringify(message, "", 2)}`;
}
const prefix = `${prefixes.tag} ${timeTagNow()}${
prefixes.types[type] ?? prefixes.types.default
}`;
// return message.replace("\n, " ———— ")
return `${prefix}${message.replace(/[\n\r]+/g, `\n${prefix} `)}`;
}
function areArraysTheSame(...arrays) {
const sortedArrays = arrays.slice().map((array) => array.slice().sort());
const refArray = JSON.stringify(sortedArrays.pop());
return sortedArrays.every((array) => refArray === JSON.stringify(array));
}
function arraysDifference(arrayA, arrayB) {
let onlyInArrayA = [];
let onlyInArrayB = [];
arrayA.forEach((value) => {
if (!arrayB.includes(value)) onlyInArrayA.push(value);
});
arrayB.forEach((value) => {
if (!arrayA.includes(value)) onlyInArrayB.push(value);
});
return { onlyFirstArray: onlyInArrayA, onlyLastArray: onlyInArrayB };
}
function initIndex() {
INDEX.content = null;
GLOBALS.required = [];
LOCALS.before.required = [];
LOCALS.after.required = [];
let indexContent = "";
try {
indexContent = fs.readFileSync(INDEX.path, "utf-8");
} catch (e) {
fatal(`COULDN'T FIND THE INDEX AT ${INDEX.path}`);
}
if (firstTime) {
firstTime = false;
say(`${consoleFormat.AQUA}INDEX FILE FOUND!`);
}
INDEX.content = indexContent;
let readingHeader = false;
for (const line of indexContent.split("\n")) {
if (line.startsWith("/* AUAUST") && !line.includes("*/")) {
readingHeader = true;
continue;
}
if (readingHeader) {
if (line.includes("*/")) {
readingHeader = false;
continue;
}
// matches anything[(.*)] after {^}<start of string>{\s*}<0 or more spaces>{[*]}<an asterisk>{\s*}<0 or more spaces>
let instruction = line.match(/^\s*[*]\s*(?<instruction>.*)/); // prettier-ignore
// if the instruction is null, undefined or an empty string, ignore the line
if (!instruction) {
continue;
}
instruction = instruction.groups.instruction;
const [command, ...arguments] = instruction.split(" ");
switch (command.toLowerCase()) {
case "useglobal":
for (const index in arguments) {
const argument = arguments[index];
if (GLOBALS.required.includes(argument))
warn(`Global script ${argument} is declared multiple times.`);
else GLOBALS.required.push(argument);
}
break;
case "uselocal":
const position = arguments.find(argument => argument.startsWith('@')); // prettier-ignore
if (position) {
const index = arguments.indexOf(position);
arguments.splice(index, 1);
} else {
error(
`Declared an "useLocal" rule without specifying "@before", "@after" or "@here". Ignoring the declaration.`
);
break;
}
switch (position) {
case "@before":
for (const index in arguments) {
const argument = arguments[index];
// Check if it is present for the SAME position
if (LOCALS.before.required.includes(argument)) {
warn(`File "${argument}" is declared multiple times with the @before position in an "useLocal" rule.`); // prettier-ignore
}
// Otherwise add it
else {
LOCALS.before.required.push(argument);
}
// Check it it it present for the OTHER position to log a warn
if (LOCALS.after.required.includes(argument)) {
warn(`File "${argument}" is declared with the @before AND @after positions in an "useLocal" rule. Added twice, be aware of errors.`); // prettier-ignore
}
}
break;
case "@after":
for (const index in arguments) {
const argument = arguments[index];
// Check if it is present for the SAME position
if (LOCALS.after.required.includes(argument)) {
warn(`File "${argument}" is declared multiple times with the @after position in an "useLocal" rule.`); // prettier-ignore
}
// Otherwise add it
else {
LOCALS.after.required.push(argument);
}
// Check it it it present for the OTHER position to log a warn
if (LOCALS.before.required.includes(argument)) {
warn(`File "${argument} "is declared with the @after AND @before positions in an "useLocal" rule. Added twice, be aware of errors.`); // prettier-ignore
}
}
break;
default:
error(
`The only @ arguments allowed are "@before", "@after" and “@here". The rule has been ignored.`
);
break;
}
default:
break;
}
}
}
let somethingChanged = false;
const objectsToLook = [
{
object: LOCALS.before,
path: LOCALS.path,
},
{
object: LOCALS.after,
path: LOCALS.path,
},
{
object: GLOBALS,
path: GLOBALS.path,
},
];
objectsToLook.forEach((data) => {
if (!areArraysTheSame(data.object.required, data.object.imported)) {
somethingChanged = true;
const differences = arraysDifference(data.object.required, data.object.imported); // prettier-ignore
const mustAdd = differences.onlyFirstArray;
const mustRemove = differences.onlyLastArray;
mustAdd.forEach((fileName) => {
addFileWatcher(fileName, data.path, data.object);
getAndCacheContent({
path: data.path,
fileName: fileName,
object: data.object,
});
});
mustRemove.forEach((fileName) => {
removeFileWatcher(fileName, data.path, data.object);
});
}
});
if (somethingChanged) {
say(`${consoleFormat.AQUA}INDEX DEPENDENCIES UPDATED !`);
}
}
function addFileWatcher(fileName, path, object) {
const fullName = `${path}${fileName}.js`;
fs.watchFile(fullName, { interval: 5000 }, (current, previous) =>
fileWatcher({
current: current,
previous: previous,
fileName: fileName,
path: path,
object: object,
})
);
object.watchers.push(fileName);
say(`STARTED WATCHING FOR ${fullName} !`);
}
function removeFileWatcher(fileName, path, object) {
const fullName = `${path}${fileName}.js`;
fs.unwatchFile(fullName);
say(`STOPPED WATCHING FOR ${fullName} !`);
}
function fileWatcher({ current, previous, fileName, path, object }) {
if (current.mtime !== previous.mtime) {
getAndCacheContent({ path: path, fileName: fileName, object: object });
updateBundle(`${path}${fileName}.js`);
}
}
function getAndCacheContent({ path, fileName, object }) {
try {
object.contents[fileName] = fs.readFileSync(
`${path}${fileName}.js`,
"utf-8"
);
} catch (e) {
object.contents[
fileName
] = `/* File ${fileName} is empty or doesn't exist. */\n`;
error(`ERROR TRYING TO READ ${e.path} ! Error code: ${e.code}.`);
}
}
function timeTagNow() {
const date = new Date();
return `${
String(date.getFullYear()).padStart(2, "0")
}${
String(date.getMonth() + 1).padStart(2, "0")
}${
String(date.getDay() + 1).padStart(2, "0")
}-${
String(date.getHours()).padStart(2, "0")
}${
String(date.getMinutes()).padStart(2, "0")
}${
String(date.getSeconds()).padStart(2, "0")
}`; // prettier-ignore
}
function updateBundle(source) {
let bundleContents = "";
GLOBALS.imported = [];
Object.keys(GLOBALS.required).forEach((index) => {
const fileName = GLOBALS.required[index];
bundleContents +=
GLOBALS.contents[fileName] ||
`/* File ${fileName} is empty or doesn't exist. */\n`;
GLOBALS.imported.push(fileName);
});
LOCALS.before.imported = [];
Object.keys(LOCALS.before.required).forEach((index) => {
const fileName = LOCALS.before.required[index];
bundleContents +=
LOCALS.before.contents[fileName] ||
`/* File ${fileName} is empty or doesn't exist. */\n`;
LOCALS.before.imported.push(fileName);
});
bundleContents += INDEX.content;
LOCALS.after.imported = [];
Object.keys(LOCALS.after.required).forEach((index) => {
const fileName = LOCALS.after.required[index];
bundleContents +=
LOCALS.after.contents[fileName] ||
`/* File ${fileName} is empty or doesn't exist. */\n`;
LOCALS.after.imported.push(fileName);
});
bundleContents = bundleContents
.replace(/^\s*(\/\/.*)?$/gm, "")
.replace(/\n+/g, "\n");
const bundleFullName = `${ENV.path}/BUNDLES/${ENV.projectName}.idjs`;
fs.writeFile(bundleFullName, bundleContents, (error) => {
if (error) {
error(error);
return;
}
say(
`BUNDLED AND APPLIED CHANGES TO ${bundleFullName} ! (Source of change: ${
source ?? "unknown"
})`
);
});
}
const fs = require("fs");
const dotenv = require("dotenv").config();
const ENV = {
path: process.env.PWD,
scriptName: process.mainModule.filename.split("/").pop(),
projectName: process.env.CURRENT_PROJECT ?? null,
projetPath: null,
};
if (ENV.projectName == null) {
fatal(
`Please provide a project name by setting CURRENT_PROJECT=<id> in .env file.`
);
}
ENV.projetPath = `${ENV.path}/PROJECTS/${ENV.projectName}`;
const INDEX = {
path: `${ENV.projetPath}/index.js`,
content: "",
};
const GLOBALS = {
path: `${ENV.path}/GLOBALS/`,
required: [],
imported: [],
watchers: [],
contents: {},
};
const LOCALS = {
path: `${ENV.projetPath}/IMPORTS/`,
before: { required: [], imported: [], watchers: [], contents: {} },
after: { required: [], imported: [], watchers: [], contents: {} },
};
let firstTime = true;
say(`${consoleFormat.GREEN}BUNDLER SCRIPT STARTED${consoleFormat.RESET} —— See debug information below.`); //prettier-ignore
fs.watchFile(INDEX.path, { interval: 4000 }, (current, previous) => {
if (current.mtime !== previous.mtime) {
initIndex();
updateBundle("index updated");
}
});
// Init and bundle once @ start
initIndex();
updateBundle("script start");