-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpublish-install-refs.mjs
More file actions
463 lines (423 loc) · 15.5 KB
/
Copy pathpublish-install-refs.mjs
File metadata and controls
463 lines (423 loc) · 15.5 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
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { readPluginWorkspaces } from "./plugin-workspaces.mjs";
import { validatePluginArtifacts } from "./validate-plugin-artifacts.mjs";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const releaseServerEntry = "./dist/install-server.mjs";
const releaseAppEntry = "./dist/install-app.mjs";
const releaseAppCss = "dist/install-app.css";
const serverBundleBanner = `${[
'import { createRequire as __createRequire } from "node:module";',
'import { dirname as __pathDirname } from "node:path";',
'import { fileURLToPath as __fileURLToPath } from "node:url";',
"const require = __createRequire(import.meta.url);",
"var __filename = __fileURLToPath(import.meta.url);",
"var __dirname = __pathDirname(__filename);",
].join("\n")}\n`;
const productionDependencyFields = [
"dependencies",
"optionalDependencies",
"peerDependencies",
];
const explicitlyRetiredInstallRefs = Object.freeze([
"plugin/omegacode",
"plugin/ui-patterns",
]);
function run(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd ?? root,
encoding: options.encoding ?? "utf8",
env: { ...process.env, ...options.env },
input: options.input,
maxBuffer: 64 * 1024 * 1024,
stdio: options.stdio ?? [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
});
if (result.error) throw result.error;
if (result.status !== 0 && options.allowFailure) return null;
if (result.status !== 0) {
throw new Error(
`${command} ${args.join(" ")} failed:\n${result.stderr || result.stdout}`,
);
}
return typeof result.stdout === "string" ? result.stdout.trim() : result.stdout;
}
function git(args, options = {}) {
return run("git", args, options);
}
function fullInstallRef(installRef) {
if (!/^plugin\/[a-z0-9]+(?:-[a-z0-9]+)*$/.test(installRef)) {
throw new Error(`invalid plugin install ref: ${installRef}`);
}
return `refs/heads/${installRef}`;
}
export function resolveRetiredInstallRefs(activeInstallRefs) {
const active = new Set(activeInstallRefs);
for (const installRef of explicitlyRetiredInstallRefs) {
fullInstallRef(installRef);
if (active.has(installRef)) {
throw new Error(`cannot retire active plugin install ref: ${installRef}`);
}
}
return [...explicitlyRetiredInstallRefs];
}
export function retiredInstallRefPushArgs(installRef, expectedCommit) {
const ref = fullInstallRef(installRef);
if (!/^[0-9a-f]{40}$/i.test(expectedCommit)) {
throw new Error(`invalid expected commit for ${installRef}: ${expectedCommit}`);
}
return [
"push",
`--force-with-lease=${ref}:${expectedCommit}`,
"origin",
`:${ref}`,
];
}
async function filesBelow(directory, prefix = "") {
const files = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const absolutePath = resolve(directory, entry.name);
const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
files.push(...(await filesBelow(absolutePath, relativePath)));
} else if (entry.isFile()) {
files.push({ absolutePath, relativePath });
}
}
return files;
}
export function releaseManifest(sourceManifest) {
const manifest = structuredClone(sourceManifest);
delete manifest.devDependencies;
delete manifest.scripts;
// Git installs rebuild their declared server entry. Point them at the
// self-contained release entry generated from the prebuilt bundle instead
// of authored TypeScript whose development dependencies are not shipped.
if (manifest.bb?.server) manifest.bb.server = releaseServerEntry;
// bb recompiles frontend entries for direct git installs. Point the
// release-only manifest at a self-contained wrapper around the prebuilt app
// so installation never depends on development node_modules. The wrapper
// also carries plugin-authored CSS through that second build.
if (manifest.bb?.app) manifest.bb.app = releaseAppEntry;
for (const field of productionDependencyFields) {
delete manifest[field];
}
return `${JSON.stringify(manifest, null, 2)}\n`;
}
export function releaseServerBundle(source) {
if (!source.startsWith(serverBundleBanner)) {
throw new Error("prebuilt server bundle is missing the expected Node ESM banner");
}
// The git installer adds the same compatibility banner when it rebuilds the
// release entry. Strip the authored-build copy so the installed bundle
// declares require/__filename/__dirname exactly once.
return source.slice(serverBundleBanner.length);
}
function addBlob(indexPath, repositoryPath, input) {
const blob = git(["hash-object", "-w", "--stdin"], { input });
git(
["update-index", "--add", "--cacheinfo", `100644,${blob},${repositoryPath}`],
{ env: { GIT_INDEX_FILE: indexPath } },
);
}
function addBlobFile(indexPath, repositoryPath, sourcePath) {
const blob = git(["hash-object", "-w", sourcePath]);
git(
["update-index", "--add", "--cacheinfo", `100644,${blob},${repositoryPath}`],
{ env: { GIT_INDEX_FILE: indexPath } },
);
}
async function createReleaseTree(plugin, sourceCommit) {
const pluginDirectory = resolve(root, plugin.source);
const sourceManifest = JSON.parse(
await readFile(resolve(pluginDirectory, "package.json"), "utf8"),
);
const stagingDirectory = await mkdtemp(
resolve(tmpdir(), `bb-plugin-ref-${plugin.slug}-`),
);
const indexPath = resolve(stagingDirectory, "index");
try {
git(["read-tree", sourceCommit], { env: { GIT_INDEX_FILE: indexPath } });
// Install refs are release artifacts, not development branches. Keep the
// imported source history on main, and never ship repository automation in
// a root-shaped plugin ref: GitHub Actions intentionally cannot create or
// update workflow files with a contents-only token.
const repositoryFiles = git(["ls-files"], {
env: { GIT_INDEX_FILE: indexPath },
})
.split("\n")
.filter(Boolean);
for (const repositoryPath of repositoryFiles) {
if (repositoryPath === ".github" || repositoryPath.startsWith(".github/")) {
git(["update-index", "--force-remove", repositoryPath], {
env: { GIT_INDEX_FILE: indexPath },
});
}
}
for (const file of await filesBelow(resolve(pluginDirectory, "dist"))) {
addBlobFile(indexPath, `dist/${file.relativePath}`, file.absolutePath);
}
if (sourceManifest.bb?.server) {
const serverBundle = await readFile(
resolve(pluginDirectory, "dist/server.js"),
"utf8",
);
addBlob(
indexPath,
releaseServerEntry.replace(/^\.\//, ""),
releaseServerBundle(serverBundle),
);
}
if (sourceManifest.bb?.app) {
const authoredCss = await readFile(resolve(pluginDirectory, "app.css"), "utf8").catch(
(error) => {
if (error?.code === "ENOENT") return null;
throw error;
},
);
const wrapper = [
'export { default } from "./app.js";',
'export * from "./app.js";',
];
if (authoredCss !== null) {
wrapper.push('import "./install-app.css";');
addBlob(
indexPath,
releaseAppCss,
`[data-bb-plugin-release-style="${plugin.pluginId}"] { --bb-plugin-release-style: 1; }\n${authoredCss}`,
);
}
addBlob(indexPath, releaseAppEntry.replace(/^\.\//, ""), `${wrapper.join("\n")}\n`);
}
addBlob(
indexPath,
"package.json",
releaseManifest(sourceManifest),
);
return git(["write-tree"], { env: { GIT_INDEX_FILE: indexPath } });
} finally {
await rm(stagingDirectory, { recursive: true, force: true });
}
}
function createReleaseCommit(plugin, tree, sourceRevision) {
return git(
[
"commit-tree",
tree,
"-m",
`build: publish ${plugin.name} from ${sourceRevision}`,
],
{
env: {
GIT_AUTHOR_NAME: "bb-plugins release",
GIT_AUTHOR_EMAIL: "bb-plugins@users.noreply.github.com",
GIT_COMMITTER_NAME: "bb-plugins release",
GIT_COMMITTER_EMAIL: "bb-plugins@users.noreply.github.com",
},
},
);
}
function localRefCommit(ref) {
return git(["rev-parse", "--verify", ref], { allowFailure: true });
}
function hasOrigin() {
return git(["remote", "get-url", "origin"], { allowFailure: true }) !== null;
}
function remoteInstallRefCommit(installRef) {
const ref = fullInstallRef(installRef);
const output = git(["ls-remote", "--heads", "origin", ref], {
allowFailure: true,
});
if (!output) return null;
const commit = output.split(/\s+/)[0];
if (!commit) return null;
git([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+${ref}:refs/remotes/origin/${installRef}`,
]);
return commit;
}
function currentReleaseCommit(plugin, push) {
const ref = `refs/heads/${plugin.installRef}`;
if (push) {
if (!hasOrigin()) throw new Error("cannot push install refs without an origin remote");
return remoteInstallRefCommit(plugin.installRef);
}
return (
localRefCommit(ref) ??
localRefCommit(`refs/remotes/origin/${plugin.installRef}`) ??
(hasOrigin() ? remoteInstallRefCommit(plugin.installRef) : null)
);
}
function retireInstallRefs(plugins, push) {
const retiredInstallRefs = resolveRetiredInstallRefs(
plugins.map((plugin) => plugin.installRef),
);
if (push && !hasOrigin()) {
throw new Error("cannot retire install refs without an origin remote");
}
for (const installRef of retiredInstallRefs) {
const currentCommit = hasOrigin()
? remoteInstallRefCommit(installRef)
: localRefCommit(`refs/remotes/origin/${installRef}`);
if (!currentCommit) {
console.log(`${installRef} already retired`);
continue;
}
if (!push) {
console.log(`${installRef} ${currentCommit} pending retirement`);
continue;
}
git(retiredInstallRefPushArgs(installRef, currentCommit));
console.log(`${installRef} ${currentCommit} retired`);
}
}
export function assertPublishWorktreeClean(
dirty = git(["status", "--porcelain=v1", "--untracked-files=all"]),
) {
if (dirty) {
throw new Error(
`refusing to push install refs from a dirty worktree:\n${dirty}`,
);
}
}
async function verifyReleaseCommit(plugin, releaseCommit) {
const checkoutRoot = await mkdtemp(
resolve(tmpdir(), `bb-plugin-install-${plugin.slug}-`),
);
const checkout = resolve(checkoutRoot, "checkout");
const indexPath = resolve(checkoutRoot, "index");
try {
await mkdir(checkout);
git(["read-tree", releaseCommit], { env: { GIT_INDEX_FILE: indexPath } });
git(["checkout-index", "--all", "--force", `--prefix=${checkout}/`], {
env: { GIT_INDEX_FILE: indexPath },
});
const manifestPath = resolve(checkout, "package.json");
const manifestRaw = await readFile(manifestPath, "utf8");
const manifest = JSON.parse(manifestRaw);
if (manifest.devDependencies || manifest.scripts) {
throw new Error(`${plugin.installRef}: release manifest contains development-only fields`);
}
for (const field of productionDependencyFields) {
if (manifest[field] !== undefined) {
throw new Error(
`${plugin.installRef}: release manifest contains ${field}`,
);
}
}
if (manifest.bb?.app && manifest.bb.app !== releaseAppEntry) {
throw new Error(`${plugin.installRef}: release app entry is not the prebuilt wrapper`);
}
if (manifest.bb?.server && manifest.bb.server !== releaseServerEntry) {
throw new Error(`${plugin.installRef}: release server entry is not the prebuilt bundle`);
}
await validatePluginArtifacts(checkout, {
expectedId: plugin.pluginId,
expectedName: plugin.name,
});
// Check both the canonical artifact and the release-only server entry
// before exercising the same rebuild that a direct git install performs.
run(process.execPath, ["--check", resolve(checkout, "dist/server.js")]);
run(process.execPath, ["--check", resolve(checkout, releaseServerEntry)]);
// Direct git installs rebuild both declared entries. The release wrappers
// are self-contained, so this mirrors the host path without development
// node_modules.
const hasAuthoredCss = await stat(resolve(checkout, releaseAppCss))
.then((details) => details.isFile())
.catch((error) => {
if (error?.code === "ENOENT") return false;
throw error;
});
run(process.execPath, [resolve(root, "tooling/build-plugin.mjs"), checkout], {
cwd: root,
});
const rebuiltServer = await readFile(resolve(checkout, "dist/server.js"), "utf8");
const bannerDeclarations = rebuiltServer.match(
/import \{ createRequire as __createRequire \} from "node:module";/gu,
);
if (bannerDeclarations?.length !== 1) {
throw new Error(`${plugin.installRef}: install build duplicated the server banner`);
}
if (hasAuthoredCss) {
const rebuiltCss = await readFile(resolve(checkout, "dist/app.css"), "utf8");
if (!rebuiltCss.includes("bb-plugin-release-style")) {
throw new Error(`${plugin.installRef}: install build dropped plugin-authored CSS`);
}
}
run(
"npm",
[
"install",
"--omit=dev",
"--ignore-scripts",
"--package-lock=false",
"--audit=false",
"--fund=false",
],
{ cwd: checkout },
);
await validatePluginArtifacts(checkout, {
expectedId: plugin.pluginId,
expectedName: plugin.name,
});
} finally {
await rm(checkoutRoot, { recursive: true, force: true });
}
}
export async function publishInstallRefs(options = {}) {
const push = options.push ?? false;
const plugins = await readPluginWorkspaces(root);
if (push) assertPublishWorktreeClean();
const sourceRevision = git(["rev-parse", "HEAD"]);
for (const plugin of plugins) {
const pluginDirectory = resolve(root, plugin.source);
await validatePluginArtifacts(pluginDirectory, {
expectedId: plugin.pluginId,
expectedName: plugin.name,
});
const sourceCommit = git([
"subtree",
"split",
`--prefix=${plugin.source}`,
sourceRevision,
])
.split("\n")
.at(-1);
if (!sourceCommit) throw new Error(`no subtree commit produced for ${plugin.slug}`);
const candidateTree = await createReleaseTree(plugin, sourceCommit);
const currentCommit = currentReleaseCommit(plugin, push);
const currentTree = currentCommit
? git(["rev-parse", `${currentCommit}^{tree}`])
: null;
if (currentCommit && currentTree === candidateTree) {
await verifyReleaseCommit(plugin, currentCommit);
console.log(`${plugin.installRef} ${currentCommit} unchanged and verified`);
continue;
}
const releaseCommit = createReleaseCommit(plugin, candidateTree, sourceRevision);
const ref = `refs/heads/${plugin.installRef}`;
await verifyReleaseCommit(plugin, releaseCommit);
git(["update-ref", ref, releaseCommit]);
if (push) {
git([
"push",
"origin",
`${releaseCommit}:${ref}`,
`--force-with-lease=${ref}:${currentCommit ?? ""}`,
]);
}
console.log(
`${plugin.installRef} ${releaseCommit} verified${push ? " and pushed" : ""}`,
);
}
retireInstallRefs(plugins, push);
}
if (resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) {
await publishInstallRefs({ push: process.argv.includes("--push") });
}