-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesbuild.config.mjs
179 lines (156 loc) · 4.88 KB
/
esbuild.config.mjs
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
import esbuild from "esbuild";
import process from "process";
import builtins from "builtin-modules";
import { config } from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
import {
existsSync,
writeFileSync,
readFileSync,
copyFileSync
} from "fs";
const banner =
`/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;
const prod = process.argv.includes('production');
const shouldLog = process.argv.includes('logger');
let logs = [];
// Correctly handle the file URL to path conversion
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load the package.json file
const packageJsonPath = path.join(__dirname, 'package.json');
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
const manifestJsonPath = path.join(__dirname, 'manifest.json');
const manifestJson = JSON.parse(readFileSync(manifestJsonPath, 'utf-8'));
if (!existsSync(`${__dirname}/data.json`)) {
writeFileSync(`${__dirname}/data.json`, "{}", 'utf-8');
}
const dataJsonPath = path.join(__dirname, 'data.json');
const dataJson = JSON.parse(readFileSync(dataJsonPath, 'utf-8'));
// Retrieve the name of the package
const packageName = packageJson.name;
const packageVersion = packageJson.version;
const packageMain = prod ? "dist/build/main.js" : "dist/dev/main.js";
packageJson.main = packageMain;
writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 4), 'utf-8');
logs.push('Package Name:', packageName);
logs.push(`Set main.js directory to ${packageJson.main}`);
// Function to find .env file by traversing upward
function findEnvFile(startDir) {
let currentDir = startDir;
while (currentDir !== path.parse(currentDir).root) {
try {
const envPath = path.join(currentDir, '.env');
if (existsSync(envPath)) {
return envPath;
}
currentDir = path.dirname(currentDir);
logs.push(`CURRENT DIR: ${currentDir}`);
} catch (err) {
logs.push(`Error in findEnvFile: ${err}`);
return null;
}
}
return null;
}
// Start searching from the current directory
const dirYielder = path.resolve(path.dirname(import.meta.url));
let envFilePath = findEnvFile(dirYielder);
if (!envFilePath) {
envFilePath = `${dirYielder.split('/file:')[0]}/.env`;
writeFileSync(envFilePath, '');
}
logs.push(`Found .env file at ${envFilePath}`);
const { pluginRoot, projectRoot, vaultRoot, envPath } = {
pluginRoot: `${path.dirname(dirYielder.split('/file:')[0])}/${packageName}`,
projectRoot: decodeURI(dirYielder.split('/file:')[1]),
vaultRoot: decodeURI(dirYielder.split('/file:')[1].replace(/\/\.obsidian.*/, '')),
envPath: envFilePath
};
logs.push(`pluginRoot: ${pluginRoot}\nprojectRoot: ${projectRoot}\nvaultRoot: ${vaultRoot}\nenvPath: ${envPath}`);
const vaultName = decodeURI(vaultRoot.split('/').pop().trim());
let parsedEnv = {};
if (envFilePath) {
const envConfig = config({ path: envFilePath });
if (envConfig.parsed) {
logs.push(`Loaded .env file from ${envFilePath}`);
parsedEnv = envConfig.parsed;
parsedEnv["envPath"] = envPath;
parsedEnv["pluginRoot"] = pluginRoot;
parsedEnv["pluginManifest"] = manifestJson;
parsedEnv["pluginSettingsPath"] = dataJsonPath;
parsedEnv["pluginSettings"] = dataJson;
parsedEnv["pluginVersion"] = packageVersion;
parsedEnv["projectRoot"] = projectRoot;
parsedEnv["vaultRoot"] = vaultRoot;
parsedEnv["vaultName"] = vaultName;
logs.push(`parsedEnv: ${JSON.stringify(parsedEnv, null, 4)}`);
} else {
logs.push(`WARNING: Unable to parse .env file: ${envConfig.error}`);
}
}
const sourcePath = path.resolve(`${pluginRoot}/${packageMain}`);
const targetPath = path.resolve(`${pluginRoot}/main.js`);
logs.push(`Source Path: ${sourcePath}`);
logs.push(`Target Path: ${targetPath}`);
const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["src/main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtins
],
define: {
"Process.env": JSON.stringify(parsedEnv),
},
platform: "node",
format: "cjs",
target: "es2021",
logLevel: "info",
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: packageMain,
minify: prod,
}).catch((error) => {
console.error(error);
process.exit(1);
});
function copyMainJs() {
try {
copyFileSync(sourcePath, targetPath);
logs.push(`Copied file: ${sourcePath} -> ${targetPath}`);
logs = logs.join('\n');
if (shouldLog) console.log(logs);
} catch (error) {
console.error(`Error creating symlink: ${error}\nLogs:\n${logs.join('\n')}`);
process.exit(1);
}
}
if (prod) {
await context.rebuild();
copyMainJs();
await context.dispose();
} else {
copyMainJs();
await context.watch();
}