-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbuild.ts
86 lines (71 loc) · 2.75 KB
/
build.ts
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
const fs = require('node:fs');
const path = require('node:path');
const fse = require('fs-extra');
const cp = require("child_process");
function copyCurrentDirectoryToDist(filePath: string) {
fse.copySync(filePath, filePath + '.original');
const content = fse.readFileSync(filePath, "utf8");
const isServerActionFile = content.startsWith('\'use server\'');
const splits = content.split(/'use php'/);
let result = splits[0];
for (let i = 1; i < splits.length; i++) {
const endOfPhpCode = findClosingBrace(splits[i]);
const phpCode = splits[i].slice(0, endOfPhpCode);
if (!isServerActionFile) {
result += `"use server";\n`;
}
result += `return require('child_process').spawnSync('php', ['-r', \`${phpCode}\`]).stdout.toString()`
result += splits[i].slice(endOfPhpCode, splits[i].length);
}
fse.writeFileSync(filePath, result, "utf8")
}
function findClosingBrace(string: String) {
let codeBlocksCounter = 0;
let characterCounter = 0;
while (characterCounter < string.length) {
const ch = string[characterCounter];
if (ch === "{") codeBlocksCounter++;
else if (ch === "}") codeBlocksCounter--;
if (codeBlocksCounter == -1) return characterCounter;
characterCounter++;
}
return null;
}
function resetToOriginalState(filePath: string) {
const path = require('node:path');
const fse = require('fs-extra');
const finalFileName = filePath.replace('.original', '');
fse.removeSync(finalFileName);
fse.moveSync(filePath, finalFileName);
}
function build() {
fromDir(path.join(__dirname, 'src'), '.js', copyCurrentDirectoryToDist);
fromDir(path.join(__dirname, 'src'), '.tsx', copyCurrentDirectoryToDist);
try {
const output = cp.spawnSync('next', ['build']);
console.log(output.stdout.toString());
} catch (e) {
console.log(e);
} finally {
console.log('cleanup');
fromDir(path.join(__dirname, 'src'), '.js.original', resetToOriginalState);
fromDir(path.join(__dirname, 'src'), '.tsx.original', resetToOriginalState);
}
}
function fromDir(startPath: any, filter: any, callback: any) {
if (!fs.existsSync(startPath)) {
console.log("no dir ", startPath);
return;
}
var files = fs.readdirSync(startPath);
for (var i = 0; i < files.length; i++) {
var filename = path.join(startPath, files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory() && filename.startsWith('node_modules') === false && filename.startsWith('.next') === false) {
fromDir(filename, filter, callback); //recurse
} else if (filename.endsWith(filter)) {
callback(filename);
};
};
};
build();