-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathesbuild.config.mjs
More file actions
259 lines (240 loc) · 7.37 KB
/
Copy pathesbuild.config.mjs
File metadata and controls
259 lines (240 loc) · 7.37 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
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
import esbuild from "esbuild";
import process from "process";
import { builtinModules } from "node:module";
import esbuildSvelte from "esbuild-svelte";
import sveltePreprocess from "svelte-preprocess";
import { execSync } from "child_process";
import chokidar from "chokidar";
import path from "path";
import fs, { mkdirSync } from "fs";
import crypto from "crypto";
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 runBuildMetadataCommand = (command) => execSync(command, {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
const getGitTag = () => {
try {
return runBuildMetadataCommand("git describe --tags --always").trim();
} catch (e) {
return "dev";
}
};
const gitTag = getGitTag();
const develop = process.argv[2] === "develop";
const staging = process.argv[2] === "staging";
const watch = process.argv[2] === "watch" || process.argv.includes("--watch");
const debug = process.argv[2] === "debug" || watch || staging || develop;
const positionalArgs = process.argv.slice(3).filter((a) => !a.startsWith("--"));
const out = positionalArgs[0] || ".";
const outfile = out + "/main.js";
const tld = staging ? "dev" : "md";
const apiUrl = `https://api.system3.${tld}`;
const authUrl = `https://auth.system3.${tld}`;
const healthUrl = `${apiUrl}/health?version=${gitTag}`;
console.log("git tag:", gitTag);
console.log("health URL", healthUrl);
// Fingerprint the working tree: HEAD commit + hash of uncommitted changes.
// Recompute this to check if a build artifact is stale.
const getSourceFingerprint = () => {
try {
const head = runBuildMetadataCommand("git rev-parse --short HEAD").trim();
const diff = runBuildMetadataCommand("git diff HEAD");
if (!diff) return head;
const diffHash = crypto.createHash("sha1").update(diff).digest("hex").slice(0, 8);
return `${head}+${diffHash}`;
} catch (e) {
return "unknown";
}
};
const writeBuildStatus = (build, result) => {
const outdir = build.initialOptions.outfile;
// Derive vault name from outdir (e.g. "vaults/live1/.obsidian/..." → "live1")
const match = outdir.match(/vaults\/([^/]+)\//);
const name = match ? match[1] : path.basename(path.dirname(outdir));
const statusDir = ".build-status";
fs.mkdirSync(statusDir, { recursive: true });
const timestamp = new Date().toLocaleTimeString("en-GB", { hour12: false });
const fingerprint = getSourceFingerprint();
if (result.errors.length > 0) {
const errors = result.errors.map(e => e.text).join("\n");
fs.writeFileSync(`${statusDir}/${name}.log`, `FAIL ${timestamp} src:${fingerprint}\n${errors}\n`);
} else {
const stat = fs.statSync(outdir);
const kb = Math.round(stat.size / 1024);
fs.writeFileSync(`${statusDir}/${name}.log`, `OK ${timestamp} main.js ${kb}kb src:${fingerprint} → ${outdir}\n`);
}
};
const NotifyPlugin = {
name: "on-end",
setup(build) {
build.onEnd((result) => {
if (result.errors.length > 0) {
execSync(`notify-send "Build Failed"`);
if (staging) {
writeBuildStatus(build, result);
}
} else if (watch) {
const tag = getGitTag();
const outfile = build.initialOptions.outfile;
const content = fs.readFileSync(outfile, "utf8");
fs.writeFileSync(outfile, content.replace(/__GIT_TAG__/g, tag));
console.log(`GIT_TAG: ${tag}`);
if (staging) {
writeBuildStatus(build, result);
}
}
});
},
};
const YjsInternalsPlugin = {
name: "yjs-internals",
setup(build) {
// Keep public Yjs imports and internal helper imports on the same
// module graph so Item/GC instanceof checks agree in the bundle.
build.onResolve({ filter: /^yjs$/ }, args => {
return {
path: path.resolve("node_modules/yjs/src/index.js"),
};
});
build.onResolve({ filter: /^yjs\/dist\/src\/internals$/ }, args => {
return {
path: path.resolve("node_modules/yjs/src/internals.js"),
};
});
},
};
const SvelteTrustedTypesPlugin = {
name: "svelte-trusted-types",
setup(build) {
build.onLoad({ filter: /[\\/]svelte[\\/]src[\\/]internal[\\/]client[\\/]dom[\\/]reconciler\.js$/ }, async (args) => {
const source = await fs.promises.readFile(args.path, "utf8");
const callback = /createHTML: \(html\) => \{\s*return html;\s*\}/;
if (!callback.test(source)) {
throw new Error("Svelte's Trusted Types callback changed; update the realm-neutral rewrite");
}
return {
contents: source.replace(callback, "createHTML: String"),
loader: "js",
};
});
},
};
const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["src/main.ts"],
bundle: true,
external: [
"obsidian",
"moment",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtinModules,
],
format: "cjs",
plugins: [
SvelteTrustedTypesPlugin,
esbuildSvelte({
compilerOptions: {
css: "injected",
compatibility: { componentApi: 4 },
},
preprocess: sveltePreprocess(),
}),
YjsInternalsPlugin,
NotifyPlugin,
],
target: "es2018",
minify: !debug,
logLevel: "info",
sourcemap: debug ? "inline" : false,
define: {
BUILD_TYPE: debug ? '"debug"' : '"prod"',
GIT_TAG: watch ? '"__GIT_TAG__"' : `"${gitTag}"`,
HEALTH_URL: `"${healthUrl}"`,
API_URL: `"${apiUrl}"`,
AUTH_URL: `"${authUrl}"`,
REPOSITORY: `"No-Instructions/Relay"`,
},
treeShaking: true,
outfile,
});
const copyFile = (src, dest) => {
if (src === dest) {
return;
}
fs.copyFileSync(src, dest);
console.log(`Copied ${src} to ${dest}`);
};
const assertRealmNeutralSveltePolicy = () => {
const bundle = fs.readFileSync(outfile, "utf8");
const realmNeutralPolicy = /createPolicy\(["']svelte-trusted-html["'],\s*\{[\s\S]{0,100}createHTML:\s*String\s*\}/;
if (!realmNeutralPolicy.test(bundle)) {
throw new Error("Built bundle does not use the realm-neutral Svelte Trusted Types callback");
}
};
const watchAndMove = (fnames, mapping) => {
// only usable on top level directory
const watcher = chokidar.watch(fnames, {
ignored: /(^|[\/\\])\./, // ignore dotfiles
persistent: true,
});
watcher.on("change", (filePath) => {
const destName = mapping[filePath] || filePath;
const destPath = path.join(out, path.basename(destName));
copyFile(filePath, destPath);
});
};
const mapping = {};
const manifest = "manifest.json";
const files = ["styles.css", manifest];
const updateManifest = (manifest) => {
const manifestPath = path.join(out, path.basename("manifest.json"));
const raw_manifest = fs.readFileSync(manifestPath);
const parsed = JSON.parse(raw_manifest);
parsed.version = gitTag;
const new_manifest = JSON.stringify(parsed, null, 2);
console.log(`Set ${manifest} version to ${gitTag}`);
fs.writeFileSync(manifestPath, new_manifest);
};
const move = (fnames, mapping) => {
// only usable on top level directory
mkdirSync(out, { recursive: true });
for (const fname of fnames) {
const destName = mapping[fname] || fname;
const destPath = path.join(out, path.basename(destName));
copyFile(fname, destPath);
}
};
if (watch) {
await context.watch();
move(files, mapping);
if (!develop) {
updateManifest();
}
watchAndMove(files, mapping);
} else {
await context.rebuild();
assertRealmNeutralSveltePolicy();
move(files, mapping);
if (!develop && out !== ".") {
updateManifest();
}
process.exit(0);
}