@kubohiroya/sb3-toolchain 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +30 -4
  2. package/README.ja.md +17 -1
  3. package/README.md +17 -1
  4. package/dist/archive.d.ts +1 -0
  5. package/dist/archive.js +16 -0
  6. package/dist/archive.js.map +1 -0
  7. package/dist/assert.d.ts +2 -0
  8. package/dist/assert.js +11 -0
  9. package/dist/assert.js.map +1 -0
  10. package/dist/bin.d.ts +1 -0
  11. package/dist/bin.js +12 -0
  12. package/dist/bin.js.map +1 -0
  13. package/dist/build.d.ts +23 -0
  14. package/dist/build.js +111 -0
  15. package/dist/build.js.map +1 -0
  16. package/dist/cli.d.ts +87 -0
  17. package/dist/cli.js +544 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/constants.d.ts +2 -0
  20. package/dist/constants.js +7 -0
  21. package/dist/constants.js.map +1 -0
  22. package/dist/extension-api-manifest.d.ts +65 -0
  23. package/dist/extension-api-manifest.js +231 -0
  24. package/dist/extension-api-manifest.js.map +1 -0
  25. package/dist/extension-bundle-archive.d.ts +36 -0
  26. package/dist/extension-bundle-archive.js +302 -0
  27. package/dist/extension-bundle-archive.js.map +1 -0
  28. package/dist/extension-bundle-configuration.d.ts +55 -0
  29. package/dist/extension-bundle-configuration.js +200 -0
  30. package/dist/extension-bundle-configuration.js.map +1 -0
  31. package/dist/extension-bundle.d.ts +39 -0
  32. package/dist/extension-bundle.js +580 -0
  33. package/dist/extension-bundle.js.map +1 -0
  34. package/dist/extension-dependencies.d.ts +18 -0
  35. package/dist/extension-dependencies.js +59 -0
  36. package/dist/extension-dependencies.js.map +1 -0
  37. package/dist/extension-id-migration.d.ts +83 -0
  38. package/dist/extension-id-migration.js +292 -0
  39. package/dist/extension-id-migration.js.map +1 -0
  40. package/dist/extension-sync.d.ts +111 -0
  41. package/dist/extension-sync.js +463 -0
  42. package/dist/extension-sync.js.map +1 -0
  43. package/dist/import.d.ts +39 -0
  44. package/dist/import.js +244 -0
  45. package/dist/import.js.map +1 -0
  46. package/dist/index.d.ts +31 -0
  47. package/dist/index.js +18 -0
  48. package/dist/npm-extension-source.d.ts +13 -0
  49. package/dist/npm-extension-source.js +63 -0
  50. package/dist/npm-extension-source.js.map +1 -0
  51. package/dist/output-safety.d.ts +29 -0
  52. package/dist/output-safety.js +213 -0
  53. package/dist/output-safety.js.map +1 -0
  54. package/dist/project-asset-additions.d.ts +29 -0
  55. package/dist/project-asset-additions.js +412 -0
  56. package/dist/project-asset-additions.js.map +1 -0
  57. package/dist/release-snapshot.d.ts +75 -0
  58. package/dist/release-snapshot.js +177 -0
  59. package/dist/release-snapshot.js.map +1 -0
  60. package/dist/source.d.ts +41 -0
  61. package/dist/source.js +282 -0
  62. package/dist/source.js.map +1 -0
  63. package/dist/turbowarp-clean-up.d.ts +18 -0
  64. package/dist/turbowarp-clean-up.js +266 -0
  65. package/dist/turbowarp-clean-up.js.map +1 -0
  66. package/dist/types.d.ts +80 -0
  67. package/package.json +31 -20
  68. package/bin/sb3-toolchain.mjs +0 -9
  69. package/src/archive.js +0 -35
  70. package/src/build.js +0 -188
  71. package/src/cli.js +0 -748
  72. package/src/constants.js +0 -4
  73. package/src/extension-api-manifest.js +0 -336
  74. package/src/extension-bundle-archive.js +0 -422
  75. package/src/extension-bundle-configuration.js +0 -265
  76. package/src/extension-bundle.js +0 -695
  77. package/src/extension-dependencies.js +0 -114
  78. package/src/extension-id-migration.js +0 -496
  79. package/src/extension-sync.js +0 -754
  80. package/src/import.js +0 -397
  81. package/src/index.js +0 -75
  82. package/src/npm-extension-source.js +0 -111
  83. package/src/output-safety.js +0 -322
  84. package/src/project-asset-additions.js +0 -560
  85. package/src/release-snapshot.js +0 -247
  86. package/src/source.js +0 -468
  87. package/src/turbowarp-clean-up.js +0 -295
@@ -0,0 +1,302 @@
1
+ import { assert, errorMessage } from "./assert.js";
2
+ import { validateArchiveEntryName } from "./archive.js";
3
+ import { extensionHeaderMetadata } from "./extension-dependencies.js";
4
+ import { extensionBundleRecoveryMarker } from "./extension-bundle.js";
5
+ import { fixedZipTimestamp } from "./source.js";
6
+ import { writeSb3Archive } from "./build.js";
7
+ import { decodeExtensionDataUrl } from "./import.js";
8
+ import path from "node:path";
9
+ import { lstat, readFile } from "node:fs/promises";
10
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
11
+ //#region src/extension-bundle-archive.ts
12
+ function isObject(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ function arraysEqual(left, right) {
16
+ return JSON.stringify(left) === JSON.stringify(right);
17
+ }
18
+ function validateId(id, description) {
19
+ assert(typeof id === "string" && /^[a-z0-9]+$/u.test(id), `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`);
20
+ return id;
21
+ }
22
+ function decodeBase64Json(payload, description) {
23
+ assert(typeof payload === "string" && /^[A-Za-z0-9+/]*={0,2}$/u.test(payload), `${description} contains invalid base64.`);
24
+ const unpadded = payload.replace(/=+$/u, "");
25
+ assert(unpadded.length % 4 !== 1, `${description} contains invalid base64.`);
26
+ try {
27
+ return JSON.parse(Buffer.from(unpadded.padEnd(Math.ceil(unpadded.length / 4) * 4, "="), "base64").toString("utf8"));
28
+ } catch (error) {
29
+ throw new Error(`${description} contains invalid JSON: ${errorMessage(error)}`, { cause: error });
30
+ }
31
+ }
32
+ function recoveryPayloadFromSource(source, requiredBundleId = void 0) {
33
+ const prefix = `// ${extensionBundleRecoveryMarker}: `;
34
+ const payloads = source.split(/\r?\n/u).filter((line) => line.startsWith(prefix)).map((line) => line.slice(prefix.length));
35
+ if (payloads.length === 0) {
36
+ assert(requiredBundleId === void 0, `Extension ${requiredBundleId} has no ${extensionBundleRecoveryMarker} recovery capsule.`);
37
+ return null;
38
+ }
39
+ assert(payloads.length === 1, "Bundled extension contains more than one recovery capsule.");
40
+ return payloads[0];
41
+ }
42
+ function validateOriginalOrder(value, description, nullable = false) {
43
+ if (nullable && value === null) return null;
44
+ assert(Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0), `Recovery capsule ${description} must be an array of IDs${nullable ? " or null" : ""}.`);
45
+ const ids = value;
46
+ assert(new Set(ids).size === ids.length, `Recovery capsule ${description} contains duplicate IDs.`);
47
+ return [...ids];
48
+ }
49
+ function readRecoveryCapsule(extensionId, dataUrl, required = false) {
50
+ assert(typeof dataUrl === "string", `Extension URL for ${extensionId} must be a string.`);
51
+ if (!dataUrl.startsWith("data:")) {
52
+ assert(!required, `Extension ${extensionId} is not embedded as a data URL.`);
53
+ return null;
54
+ }
55
+ const decodedBundle = decodeExtensionDataUrl(dataUrl);
56
+ const payload = recoveryPayloadFromSource(Buffer.from(decodedBundle.source).toString("utf8"), required ? extensionId : void 0);
57
+ if (payload === null) return null;
58
+ const capsule = decodeBase64Json(payload, `Extension ${extensionId} recovery capsule`);
59
+ assert(isObject(capsule), `Extension ${extensionId} recovery capsule must be an object.`);
60
+ assert(capsule.formatVersion === 1, `Unsupported extension bundle recovery format: ${capsule.formatVersion}`);
61
+ assert(isObject(capsule.bundle), `Extension ${extensionId} recovery capsule has no bundle.`);
62
+ const bundle = capsule.bundle;
63
+ const bundleId = validateId(bundle.id, "Recovery capsule bundle ID");
64
+ assert(bundleId === extensionId, `Recovery capsule bundle ID mismatch: expected ${extensionId}, got ${bundleId}.`);
65
+ assert(typeof bundle.name === "string" && bundle.name.length > 0, `Recovery capsule for ${extensionId} has no bundle name.`);
66
+ const bundleName = bundle.name;
67
+ assert(Array.isArray(capsule.components) && capsule.components.length >= 2, `Recovery capsule for ${extensionId} must contain at least two components.`);
68
+ const seenIds = /* @__PURE__ */ new Set();
69
+ const components = capsule.components.map((component, index) => {
70
+ assert(isObject(component), `Recovery component ${index} for ${extensionId} must be an object.`);
71
+ const componentId = validateId(component.id, `Recovery component ${index} ID`);
72
+ assert(!seenIds.has(componentId), `Recovery capsule repeats component: ${componentId}`);
73
+ seenIds.add(componentId);
74
+ const decoded = decodeExtensionDataUrl(component.dataUrl);
75
+ assert(decoded.mediaType === "text/javascript" || decoded.mediaType === "application/javascript", `Recovery component ${componentId} must contain JavaScript.`);
76
+ const metadata = extensionHeaderMetadata(decoded.source);
77
+ assert(metadata.id === componentId, `Recovery component header ID mismatch: expected ${componentId}, got ${metadata.id ?? "(missing)"}.`);
78
+ return {
79
+ dataUrl: component.dataUrl,
80
+ id: componentId
81
+ };
82
+ });
83
+ return {
84
+ bundle: {
85
+ id: bundleId,
86
+ name: bundleName
87
+ },
88
+ components,
89
+ members: components.map((component) => component.id),
90
+ originalExtensionIds: validateOriginalOrder(capsule.originalExtensionIds, "originalExtensionIds", true),
91
+ originalExtensionUrlIds: validateOriginalOrder(capsule.originalExtensionUrlIds, "originalExtensionUrlIds")
92
+ };
93
+ }
94
+ function collapseOrder(originalIds, bundles) {
95
+ const bundlesByMember = /* @__PURE__ */ new Map();
96
+ for (const bundle of bundles) for (const memberId of bundle.members) {
97
+ assert(!bundlesByMember.has(memberId), `Active extension bundles overlap at member: ${memberId}`);
98
+ bundlesByMember.set(memberId, bundle.bundle.id);
99
+ }
100
+ const emittedBundles = /* @__PURE__ */ new Set();
101
+ const output = [];
102
+ for (const id of originalIds) {
103
+ const bundleId = bundlesByMember.get(id);
104
+ if (!bundleId) output.push(id);
105
+ else if (!emittedBundles.has(bundleId)) {
106
+ emittedBundles.add(bundleId);
107
+ output.push(bundleId);
108
+ }
109
+ }
110
+ return output;
111
+ }
112
+ function replaceBundledStorage(storage, target, counts) {
113
+ if (!isObject(storage) || !Object.hasOwn(storage, target.bundle.id)) return storage;
114
+ const bundleStorage = storage[target.bundle.id];
115
+ assert(isObject(bundleStorage) && bundleStorage.formatVersion === 1 && isObject(bundleStorage.components), `Extension storage for ${target.bundle.id} is not a reversible format 1 bundle.`);
116
+ assert(Object.keys(bundleStorage).every((key) => key === "formatVersion" || key === "components"), `Extension storage for ${target.bundle.id} has unsupported bundle-level fields.`);
117
+ const bundleComponents = bundleStorage.components;
118
+ const memberIds = new Set(target.members);
119
+ for (const componentId of Object.keys(bundleComponents)) {
120
+ assert(memberIds.has(componentId), `Extension storage for ${target.bundle.id} contains unknown component: ${componentId}`);
121
+ assert(!Object.hasOwn(storage, componentId), `Cannot restore extension storage because member ID already exists: ${componentId}`);
122
+ }
123
+ const replacement = {};
124
+ for (const [id, value] of Object.entries(storage)) {
125
+ if (id !== target.bundle.id) {
126
+ replacement[id] = value;
127
+ continue;
128
+ }
129
+ for (const memberId of target.members) if (Object.hasOwn(bundleComponents, memberId)) replacement[memberId] = bundleComponents[memberId];
130
+ }
131
+ counts.extensionStorage += 1;
132
+ return replacement;
133
+ }
134
+ function restoreOpcodeValues(value, target, counts) {
135
+ if (!value || typeof value !== "object") return;
136
+ if (Array.isArray(value)) {
137
+ for (const entry of value) restoreOpcodeValues(entry, target, counts);
138
+ return;
139
+ }
140
+ const record = value;
141
+ for (const [key, entry] of Object.entries(record)) if (key === "opcode" && typeof entry === "string") {
142
+ const bundlePrefix = `${target.bundle.id}_`;
143
+ if (!entry.startsWith(bundlePrefix)) continue;
144
+ const localOpcode = entry.slice(bundlePrefix.length);
145
+ const memberId = target.members.find((id) => localOpcode.startsWith(`${id}__`));
146
+ assert(memberId, `Bundle opcode cannot be assigned to a recovery component: ${entry}`);
147
+ record[key] = `${memberId}_${localOpcode.slice(memberId.length + 2)}`;
148
+ counts.opcodes += 1;
149
+ } else restoreOpcodeValues(entry, target, counts);
150
+ }
151
+ function collectRemainingBundleReferences(value, bundleId) {
152
+ const references = [];
153
+ const prefix = `${bundleId}_`;
154
+ function visit(current, pointer) {
155
+ if (typeof current === "string") {
156
+ if (current.startsWith(prefix)) references.push(pointer || "/");
157
+ return;
158
+ }
159
+ if (!current || typeof current !== "object") return;
160
+ if (Array.isArray(current)) {
161
+ current.forEach((entry, index) => visit(entry, `${pointer}/${index}`));
162
+ return;
163
+ }
164
+ for (const [key, entry] of Object.entries(current)) visit(entry, `${pointer}/${key}`);
165
+ }
166
+ visit(value, "");
167
+ return references;
168
+ }
169
+ function restoreProject(project, target, activeBundles) {
170
+ const restored = structuredClone(project);
171
+ const counts = {
172
+ extensionStorage: 0,
173
+ extensionUrls: 0,
174
+ opcodes: 0,
175
+ projectExtensions: 0
176
+ };
177
+ const remainingBundles = activeBundles.filter((bundle) => bundle.bundle.id !== target.bundle.id);
178
+ assert(isObject(restored.extensionURLs), "SB3 project.json extensionURLs must be an object.");
179
+ const existingUrls = restored.extensionURLs;
180
+ const currentUrlIds = Object.keys(existingUrls);
181
+ const expectedUrlIds = collapseOrder(target.originalExtensionUrlIds, activeBundles);
182
+ assert(arraysEqual(currentUrlIds, expectedUrlIds), `Cannot safely restore extension URL order. Expected ${JSON.stringify(expectedUrlIds)}, got ${JSON.stringify(currentUrlIds)}.`);
183
+ const restoredUrlIds = collapseOrder(target.originalExtensionUrlIds, remainingBundles);
184
+ const componentUrls = new Map(target.components.map((component) => [component.id, component.dataUrl]));
185
+ restored.extensionURLs = Object.fromEntries(restoredUrlIds.map((id) => [id, componentUrls.has(id) ? componentUrls.get(id) : existingUrls[id]]));
186
+ counts.extensionUrls = target.members.length + 1;
187
+ if (target.originalExtensionIds === null) assert(restored.extensions === void 0, "Cannot safely restore project.extensions because it was added after bundling.");
188
+ else {
189
+ assert(Array.isArray(restored.extensions), "SB3 project.json extensions must be an array.");
190
+ const expectedIds = collapseOrder(target.originalExtensionIds, activeBundles);
191
+ assert(arraysEqual(restored.extensions, expectedIds), `Cannot safely restore project.extensions order. Expected ${JSON.stringify(expectedIds)}, got ${JSON.stringify(restored.extensions)}.`);
192
+ restored.extensions = collapseOrder(target.originalExtensionIds, remainingBundles);
193
+ counts.projectExtensions = target.members.length + 1;
194
+ }
195
+ restored.extensionStorage = replaceBundledStorage(restored.extensionStorage, target, counts);
196
+ for (const targetEntry of restored.targets ?? []) if (isObject(targetEntry)) targetEntry.extensionStorage = replaceBundledStorage(targetEntry.extensionStorage, target, counts);
197
+ restoreOpcodeValues(restored.targets, target, counts);
198
+ restoreOpcodeValues(restored.monitors, target, counts);
199
+ const remainingReferences = collectRemainingBundleReferences(restored, target.bundle.id);
200
+ assert(remainingReferences.length === 0, `Bundle ${target.bundle.id} has unsupported references at: ` + remainingReferences.slice(0, 8).join(", "));
201
+ return {
202
+ counts,
203
+ project: restored
204
+ };
205
+ }
206
+ function parseProject(projectEntry) {
207
+ try {
208
+ const project = JSON.parse(strFromU8(projectEntry));
209
+ assert(isObject(project), "SB3 project.json must contain an object.");
210
+ return project;
211
+ } catch (error) {
212
+ if (errorMessage(error) === "SB3 project.json must contain an object.") throw error;
213
+ throw new Error(`SB3 project.json is invalid JSON: ${errorMessage(error)}`, { cause: error });
214
+ }
215
+ }
216
+ async function createArchiveUnbundlePlan({ bundleId, inputPath, outputPath }) {
217
+ validateId(bundleId, "Extension bundle ID");
218
+ assert(typeof inputPath === "string", "Input SB3 path is required.");
219
+ assert(typeof outputPath === "string", "Unbundled SB3 output path is required.");
220
+ const resolvedInputPath = path.resolve(inputPath);
221
+ const resolvedOutputPath = path.resolve(outputPath);
222
+ assert(path.extname(resolvedInputPath).toLowerCase() === ".sb3", `Input path must use the .sb3 extension: ${resolvedInputPath}`);
223
+ assert(path.extname(resolvedOutputPath).toLowerCase() === ".sb3", `Output path must use the .sb3 extension: ${resolvedOutputPath}`);
224
+ const stats = await lstat(resolvedInputPath);
225
+ assert(stats.isFile() && !stats.isSymbolicLink(), `Input SB3 must be a regular file, not a symbolic link: ${resolvedInputPath}`);
226
+ const archiveEntries = unzipSync(new Uint8Array(await readFile(resolvedInputPath)));
227
+ const entries = Object.entries(archiveEntries);
228
+ assert(entries.length > 0, "SB3 archive is empty.");
229
+ for (const [entryName] of entries) {
230
+ validateArchiveEntryName(entryName);
231
+ assert(!/^(?:0|[1-9][0-9]*)$/u.test(entryName), `Integer-like ZIP entry names cannot preserve archive order: ${entryName}`);
232
+ }
233
+ assert(archiveEntries["project.json"], "SB3 archive does not contain project.json.");
234
+ const project = parseProject(archiveEntries["project.json"]);
235
+ assert(isObject(project.extensionURLs), "SB3 project.json extensionURLs must be an object.");
236
+ const activeBundles = [];
237
+ for (const [extensionId, dataUrl] of Object.entries(project.extensionURLs)) {
238
+ const recovery = readRecoveryCapsule(extensionId, dataUrl, extensionId === bundleId);
239
+ if (recovery) activeBundles.push(recovery);
240
+ }
241
+ const target = activeBundles.find((bundle) => bundle.bundle.id === bundleId);
242
+ assert(target, `Reversible extension bundle was not found: ${bundleId}`);
243
+ const restored = restoreProject(project, target, activeBundles);
244
+ const outputEntries = Object.fromEntries(entries.map(([entryName, contents]) => [entryName, entryName === "project.json" ? strToU8(`${JSON.stringify(restored.project)}\n`) : contents]));
245
+ return {
246
+ archive: zipSync(outputEntries, {
247
+ level: 6,
248
+ mtime: fixedZipTimestamp
249
+ }),
250
+ bundleId,
251
+ counts: restored.counts,
252
+ entryCount: entries.length,
253
+ inputPath: resolvedInputPath,
254
+ members: [...target.members],
255
+ outputPath: resolvedOutputPath
256
+ };
257
+ }
258
+ function publicArchivePlan(plan) {
259
+ return {
260
+ bundleId: plan.bundleId,
261
+ counts: plan.counts,
262
+ entryCount: plan.entryCount,
263
+ inputPath: plan.inputPath,
264
+ members: plan.members,
265
+ outputPath: plan.outputPath
266
+ };
267
+ }
268
+ async function planBundledSb3Unbundle(options) {
269
+ return {
270
+ applied: false,
271
+ changed: true,
272
+ ...publicArchivePlan(await createArchiveUnbundlePlan(options))
273
+ };
274
+ }
275
+ async function unbundleSb3({ bundleId, inputPath, outputPath, yes = false }) {
276
+ const plan = await createArchiveUnbundlePlan({
277
+ bundleId,
278
+ inputPath,
279
+ outputPath
280
+ });
281
+ const publicPlan = publicArchivePlan(plan);
282
+ if (!yes) return {
283
+ applied: false,
284
+ changed: true,
285
+ ...publicPlan,
286
+ rollbackCleanupWarning: null
287
+ };
288
+ const written = await writeSb3Archive({
289
+ archive: plan.archive,
290
+ outputPath: plan.outputPath,
291
+ yes
292
+ });
293
+ return {
294
+ applied: true,
295
+ ...publicPlan,
296
+ ...written
297
+ };
298
+ }
299
+ //#endregion
300
+ export { planBundledSb3Unbundle, unbundleSb3 };
301
+
302
+ //# sourceMappingURL=extension-bundle-archive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-bundle-archive.js","names":[],"sources":["../src/extension-bundle-archive.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {lstat, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strFromU8, strToU8, unzipSync, zipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {writeSb3Archive} from './build';\nimport {extensionBundleRecoveryMarker} from './extension-bundle';\nimport {extensionHeaderMetadata} from './extension-dependencies';\nimport {decodeExtensionDataUrl} from './import';\nimport {fixedZipTimestamp} from './source';\nimport type {ProjectJson, UnknownRecord} from './types';\n\ninterface RecoveryComponent {\n dataUrl: string;\n id: string;\n}\n\ninterface RecoveryCapsule {\n bundle: {id: string; name: string};\n components: RecoveryComponent[];\n members: string[];\n originalExtensionIds: string[] | null;\n originalExtensionUrlIds: string[];\n}\n\ninterface RestoreCounts {\n extensionStorage: number;\n extensionUrls: number;\n opcodes: number;\n projectExtensions: number;\n}\n\nexport interface BundledSb3UnbundleOptions {\n bundleId: string;\n inputPath: string;\n outputPath: string;\n yes?: boolean;\n}\n\nexport interface BundledSb3UnbundlePlan {\n bundleId: string;\n counts: RestoreCounts;\n entryCount: number;\n inputPath: string;\n members: string[];\n outputPath: string;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction arraysEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction validateId(id: unknown, description: string): string {\n assert(\n typeof id === 'string' && /^[a-z0-9]+$/u.test(id),\n `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`,\n );\n return id;\n}\n\nfunction decodeBase64Json(payload: unknown, description: string): unknown {\n assert(\n typeof payload === 'string' && /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),\n `${description} contains invalid base64.`,\n );\n const unpadded = payload.replace(/=+$/u, '');\n assert(unpadded.length % 4 !== 1, `${description} contains invalid base64.`);\n try {\n return JSON.parse(\n Buffer.from(unpadded.padEnd(Math.ceil(unpadded.length / 4) * 4, '='), 'base64').toString(\n 'utf8',\n ),\n );\n } catch (error) {\n throw new Error(`${description} contains invalid JSON: ${errorMessage(error)}`, {cause: error});\n }\n}\n\nfunction recoveryPayloadFromSource(\n source: string,\n requiredBundleId: string | undefined = undefined,\n): string | null {\n const prefix = `// ${extensionBundleRecoveryMarker}: `;\n const payloads = source\n .split(/\\r?\\n/u)\n .filter((line) => line.startsWith(prefix))\n .map((line) => line.slice(prefix.length));\n if (payloads.length === 0) {\n assert(\n requiredBundleId === undefined,\n `Extension ${requiredBundleId} has no ${extensionBundleRecoveryMarker} recovery capsule.`,\n );\n return null;\n }\n assert(payloads.length === 1, 'Bundled extension contains more than one recovery capsule.');\n return payloads[0];\n}\n\nfunction validateOriginalOrder(\n value: unknown,\n description: string,\n nullable = false,\n): string[] | null {\n if (nullable && value === null) return null;\n assert(\n Array.isArray(value) &&\n (value as unknown[]).every((id) => typeof id === 'string' && id.length > 0),\n `Recovery capsule ${description} must be an array of IDs${nullable ? ' or null' : ''}.`,\n );\n const ids = value as string[];\n assert(\n new Set(ids).size === ids.length,\n `Recovery capsule ${description} contains duplicate IDs.`,\n );\n return [...ids];\n}\n\nfunction readRecoveryCapsule(\n extensionId: string,\n dataUrl: unknown,\n required = false,\n): RecoveryCapsule | null {\n assert(typeof dataUrl === 'string', `Extension URL for ${extensionId} must be a string.`);\n if (!dataUrl.startsWith('data:')) {\n assert(!required, `Extension ${extensionId} is not embedded as a data URL.`);\n return null;\n }\n const decodedBundle = decodeExtensionDataUrl(dataUrl);\n const payload = recoveryPayloadFromSource(\n Buffer.from(decodedBundle.source).toString('utf8'),\n required ? extensionId : undefined,\n );\n if (payload === null) return null;\n const capsule = decodeBase64Json(payload, `Extension ${extensionId} recovery capsule`);\n assert(isObject(capsule), `Extension ${extensionId} recovery capsule must be an object.`);\n assert(\n capsule.formatVersion === 1,\n `Unsupported extension bundle recovery format: ${capsule.formatVersion}`,\n );\n assert(isObject(capsule.bundle), `Extension ${extensionId} recovery capsule has no bundle.`);\n const bundle = capsule.bundle;\n const bundleId = validateId(bundle.id, 'Recovery capsule bundle ID');\n assert(\n bundleId === extensionId,\n `Recovery capsule bundle ID mismatch: expected ${extensionId}, got ${bundleId}.`,\n );\n assert(\n typeof bundle.name === 'string' && bundle.name.length > 0,\n `Recovery capsule for ${extensionId} has no bundle name.`,\n );\n const bundleName = bundle.name;\n assert(\n Array.isArray(capsule.components) && capsule.components.length >= 2,\n `Recovery capsule for ${extensionId} must contain at least two components.`,\n );\n\n const seenIds = new Set<string>();\n const components = (capsule.components as unknown[]).map(\n (component, index): RecoveryComponent => {\n assert(\n isObject(component),\n `Recovery component ${index} for ${extensionId} must be an object.`,\n );\n const componentId = validateId(component.id, `Recovery component ${index} ID`);\n assert(!seenIds.has(componentId), `Recovery capsule repeats component: ${componentId}`);\n seenIds.add(componentId);\n const decoded = decodeExtensionDataUrl(component.dataUrl);\n assert(\n decoded.mediaType === 'text/javascript' || decoded.mediaType === 'application/javascript',\n `Recovery component ${componentId} must contain JavaScript.`,\n );\n const metadata = extensionHeaderMetadata(decoded.source);\n assert(\n metadata.id === componentId,\n `Recovery component header ID mismatch: expected ${componentId}, got ${metadata.id ?? '(missing)'}.`,\n );\n return {dataUrl: component.dataUrl as string, id: componentId};\n },\n );\n\n return {\n bundle: {id: bundleId, name: bundleName},\n components,\n members: components.map((component) => component.id),\n originalExtensionIds: validateOriginalOrder(\n capsule.originalExtensionIds,\n 'originalExtensionIds',\n true,\n ),\n originalExtensionUrlIds: validateOriginalOrder(\n capsule.originalExtensionUrlIds,\n 'originalExtensionUrlIds',\n ) as string[],\n };\n}\n\nfunction collapseOrder(originalIds: string[], bundles: RecoveryCapsule[]): string[] {\n const bundlesByMember = new Map<string, string>();\n for (const bundle of bundles) {\n for (const memberId of bundle.members) {\n assert(\n !bundlesByMember.has(memberId),\n `Active extension bundles overlap at member: ${memberId}`,\n );\n bundlesByMember.set(memberId, bundle.bundle.id);\n }\n }\n const emittedBundles = new Set<string>();\n const output: string[] = [];\n for (const id of originalIds) {\n const bundleId = bundlesByMember.get(id);\n if (!bundleId) {\n output.push(id);\n } else if (!emittedBundles.has(bundleId)) {\n emittedBundles.add(bundleId);\n output.push(bundleId);\n }\n }\n return output;\n}\n\nfunction replaceBundledStorage(\n storage: unknown,\n target: RecoveryCapsule,\n counts: RestoreCounts,\n): unknown {\n if (!isObject(storage) || !Object.hasOwn(storage, target.bundle.id)) return storage;\n const bundleStorage = storage[target.bundle.id];\n assert(\n isObject(bundleStorage) &&\n bundleStorage.formatVersion === 1 &&\n isObject(bundleStorage.components),\n `Extension storage for ${target.bundle.id} is not a reversible format 1 bundle.`,\n );\n assert(\n Object.keys(bundleStorage).every((key) => key === 'formatVersion' || key === 'components'),\n `Extension storage for ${target.bundle.id} has unsupported bundle-level fields.`,\n );\n const bundleComponents = bundleStorage.components as UnknownRecord;\n const memberIds = new Set(target.members);\n for (const componentId of Object.keys(bundleComponents)) {\n assert(\n memberIds.has(componentId),\n `Extension storage for ${target.bundle.id} contains unknown component: ${componentId}`,\n );\n assert(\n !Object.hasOwn(storage, componentId),\n `Cannot restore extension storage because member ID already exists: ${componentId}`,\n );\n }\n const replacement: UnknownRecord = {};\n for (const [id, value] of Object.entries(storage)) {\n if (id !== target.bundle.id) {\n replacement[id] = value;\n continue;\n }\n for (const memberId of target.members) {\n if (Object.hasOwn(bundleComponents, memberId)) {\n replacement[memberId] = bundleComponents[memberId];\n }\n }\n }\n counts.extensionStorage += 1;\n return replacement;\n}\n\nfunction restoreOpcodeValues(value: unknown, target: RecoveryCapsule, counts: RestoreCounts): void {\n if (!value || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const entry of value as unknown[]) restoreOpcodeValues(entry, target, counts);\n return;\n }\n const record = value as UnknownRecord;\n for (const [key, entry] of Object.entries(record)) {\n if (key === 'opcode' && typeof entry === 'string') {\n const bundlePrefix = `${target.bundle.id}_`;\n if (!entry.startsWith(bundlePrefix)) continue;\n const localOpcode = entry.slice(bundlePrefix.length);\n const memberId = target.members.find((id) => localOpcode.startsWith(`${id}__`));\n assert(memberId, `Bundle opcode cannot be assigned to a recovery component: ${entry}`);\n record[key] = `${memberId}_${localOpcode.slice(memberId.length + 2)}`;\n counts.opcodes += 1;\n } else {\n restoreOpcodeValues(entry, target, counts);\n }\n }\n}\n\nfunction collectRemainingBundleReferences(value: unknown, bundleId: string): string[] {\n const references: string[] = [];\n const prefix = `${bundleId}_`;\n function visit(current: unknown, pointer: string): void {\n if (typeof current === 'string') {\n if (current.startsWith(prefix)) references.push(pointer || '/');\n return;\n }\n if (!current || typeof current !== 'object') return;\n if (Array.isArray(current)) {\n (current as unknown[]).forEach((entry, index) => visit(entry, `${pointer}/${index}`));\n return;\n }\n for (const [key, entry] of Object.entries(current as UnknownRecord)) {\n visit(entry, `${pointer}/${key}`);\n }\n }\n visit(value, '');\n return references;\n}\n\nfunction restoreProject(\n project: ProjectJson,\n target: RecoveryCapsule,\n activeBundles: RecoveryCapsule[],\n): {counts: RestoreCounts; project: ProjectJson} {\n const restored = structuredClone(project);\n const counts: RestoreCounts = {\n extensionStorage: 0,\n extensionUrls: 0,\n opcodes: 0,\n projectExtensions: 0,\n };\n const remainingBundles = activeBundles.filter((bundle) => bundle.bundle.id !== target.bundle.id);\n\n assert(isObject(restored.extensionURLs), 'SB3 project.json extensionURLs must be an object.');\n const existingUrls = restored.extensionURLs;\n const currentUrlIds = Object.keys(existingUrls);\n const expectedUrlIds = collapseOrder(target.originalExtensionUrlIds, activeBundles);\n assert(\n arraysEqual(currentUrlIds, expectedUrlIds),\n `Cannot safely restore extension URL order. Expected ${JSON.stringify(expectedUrlIds)}, ` +\n `got ${JSON.stringify(currentUrlIds)}.`,\n );\n const restoredUrlIds = collapseOrder(target.originalExtensionUrlIds, remainingBundles);\n const componentUrls = new Map(\n target.components.map((component) => [component.id, component.dataUrl]),\n );\n restored.extensionURLs = Object.fromEntries(\n restoredUrlIds.map((id) => [\n id,\n componentUrls.has(id) ? componentUrls.get(id) : existingUrls[id],\n ]),\n );\n counts.extensionUrls = target.members.length + 1;\n\n if (target.originalExtensionIds === null) {\n assert(\n restored.extensions === undefined,\n 'Cannot safely restore project.extensions because it was added after bundling.',\n );\n } else {\n assert(Array.isArray(restored.extensions), 'SB3 project.json extensions must be an array.');\n const expectedIds = collapseOrder(target.originalExtensionIds, activeBundles);\n assert(\n arraysEqual(restored.extensions, expectedIds),\n `Cannot safely restore project.extensions order. Expected ${JSON.stringify(expectedIds)}, ` +\n `got ${JSON.stringify(restored.extensions)}.`,\n );\n restored.extensions = collapseOrder(target.originalExtensionIds, remainingBundles);\n counts.projectExtensions = target.members.length + 1;\n }\n\n restored.extensionStorage = replaceBundledStorage(restored.extensionStorage, target, counts);\n for (const targetEntry of (restored.targets as unknown[] | undefined) ?? []) {\n if (isObject(targetEntry)) {\n targetEntry.extensionStorage = replaceBundledStorage(\n targetEntry.extensionStorage,\n target,\n counts,\n );\n }\n }\n\n restoreOpcodeValues(restored.targets, target, counts);\n restoreOpcodeValues(restored.monitors, target, counts);\n const remainingReferences = collectRemainingBundleReferences(restored, target.bundle.id);\n assert(\n remainingReferences.length === 0,\n `Bundle ${target.bundle.id} has unsupported references at: ` +\n remainingReferences.slice(0, 8).join(', '),\n );\n return {counts, project: restored};\n}\n\nfunction parseProject(projectEntry: Uint8Array): ProjectJson {\n try {\n const project: unknown = JSON.parse(strFromU8(projectEntry));\n assert(isObject(project), 'SB3 project.json must contain an object.');\n return project;\n } catch (error) {\n if (errorMessage(error) === 'SB3 project.json must contain an object.') throw error;\n throw new Error(`SB3 project.json is invalid JSON: ${errorMessage(error)}`, {cause: error});\n }\n}\n\nasync function createArchiveUnbundlePlan({\n bundleId,\n inputPath,\n outputPath,\n}: Omit<BundledSb3UnbundleOptions, 'yes'>): Promise<\n BundledSb3UnbundlePlan & {archive: Uint8Array}\n> {\n validateId(bundleId, 'Extension bundle ID');\n assert(typeof inputPath === 'string', 'Input SB3 path is required.');\n assert(typeof outputPath === 'string', 'Unbundled SB3 output path is required.');\n const resolvedInputPath = path.resolve(inputPath);\n const resolvedOutputPath = path.resolve(outputPath);\n assert(\n path.extname(resolvedInputPath).toLowerCase() === '.sb3',\n `Input path must use the .sb3 extension: ${resolvedInputPath}`,\n );\n assert(\n path.extname(resolvedOutputPath).toLowerCase() === '.sb3',\n `Output path must use the .sb3 extension: ${resolvedOutputPath}`,\n );\n const stats = await lstat(resolvedInputPath);\n assert(\n stats.isFile() && !stats.isSymbolicLink(),\n `Input SB3 must be a regular file, not a symbolic link: ${resolvedInputPath}`,\n );\n const archiveEntries = unzipSync(new Uint8Array(await readFile(resolvedInputPath)));\n const entries = Object.entries(archiveEntries);\n assert(entries.length > 0, 'SB3 archive is empty.');\n for (const [entryName] of entries) {\n validateArchiveEntryName(entryName);\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve archive order: ${entryName}`,\n );\n }\n assert(archiveEntries['project.json'], 'SB3 archive does not contain project.json.');\n const project = parseProject(archiveEntries['project.json']);\n assert(isObject(project.extensionURLs), 'SB3 project.json extensionURLs must be an object.');\n\n const activeBundles: RecoveryCapsule[] = [];\n for (const [extensionId, dataUrl] of Object.entries(project.extensionURLs)) {\n const recovery = readRecoveryCapsule(extensionId, dataUrl, extensionId === bundleId);\n if (recovery) activeBundles.push(recovery);\n }\n const target = activeBundles.find((bundle) => bundle.bundle.id === bundleId);\n assert(target, `Reversible extension bundle was not found: ${bundleId}`);\n const restored = restoreProject(project, target, activeBundles);\n const outputEntries = Object.fromEntries(\n entries.map(([entryName, contents]) => [\n entryName,\n entryName === 'project.json' ? strToU8(`${JSON.stringify(restored.project)}\\n`) : contents,\n ]),\n );\n const archive = zipSync(outputEntries, {level: 6, mtime: fixedZipTimestamp});\n return {\n archive,\n bundleId,\n counts: restored.counts,\n entryCount: entries.length,\n inputPath: resolvedInputPath,\n members: [...target.members],\n outputPath: resolvedOutputPath,\n };\n}\n\nfunction publicArchivePlan(plan: BundledSb3UnbundlePlan): BundledSb3UnbundlePlan {\n return {\n bundleId: plan.bundleId,\n counts: plan.counts,\n entryCount: plan.entryCount,\n inputPath: plan.inputPath,\n members: plan.members,\n outputPath: plan.outputPath,\n };\n}\n\nexport async function planBundledSb3Unbundle(\n options: Omit<BundledSb3UnbundleOptions, 'yes'>,\n): Promise<BundledSb3UnbundlePlan & {applied: boolean; changed: boolean}> {\n const plan = await createArchiveUnbundlePlan(options);\n return {applied: false, changed: true, ...publicArchivePlan(plan)};\n}\n\nexport async function unbundleSb3({\n bundleId,\n inputPath,\n outputPath,\n yes = false,\n}: BundledSb3UnbundleOptions) {\n const plan = await createArchiveUnbundlePlan({bundleId, inputPath, outputPath});\n const publicPlan = publicArchivePlan(plan);\n if (!yes) {\n return {\n applied: false,\n changed: true,\n ...publicPlan,\n rollbackCleanupWarning: null,\n };\n }\n const written = await writeSb3Archive({archive: plan.archive, outputPath: plan.outputPath, yes});\n return {applied: true, ...publicPlan, ...written};\n}\n"],"mappings":";;;;;;;;;;;AAoDA,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,YAAY,MAAe,OAAyB;CAC3D,OAAO,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,KAAK;AACtD;AAEA,SAAS,WAAW,IAAa,aAA6B;CAC5D,OACE,OAAO,OAAO,YAAY,eAAe,KAAK,EAAE,GAChD,GAAG,YAAY,0CAA0C,KAAK,UAAU,EAAE,GAC5E;CACA,OAAO;AACT;AAEA,SAAS,iBAAiB,SAAkB,a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Q;CAC3E,OAAO,QAAQ,8CAA8C,UAAU;CACvE,MAAM,WAAW,eAAe,SAAS,QAAQ,aAAa;CAC9D,MAAM,gBAAgB,OAAO,YAC3B,QAAQ,KAAK,CAAC,WAAW,cAAc,CACrC,WACA,cAAc,iBAAiB,QAAQ,GAAG,KAAK,UAAU,SAAS,OAAO,EAAE,GAAG,IAAI,QACpF,CAAC,CACH;CAEA,OAAO;EACL,SAFc,QAAQ,eAAe;GAAC,OAAO;GAAG,OAAO;EAAiB,CAExE;EACA;EACA,QAAQ,SAAS;EACjB,YAAY,QAAQ;EACpB,WAAW;EACX,SAAS,CAAC,GAAG,OAAO,OAAO;EAC3B,YAAY;CACd;AACF;AAEA,SAAS,kBAAkB,MAAsD;CAC/E,OAAO;EACL,UAAU,KAAK;EACf,QAAQ,KAAK;EACb,YAAY,KAAK;EACjB,WAAW,KAAK;EAChB,SAAS,KAAK;EACd,YAAY,KAAK;CACnB;AACF;AAEA,eAAsB,uBACpB,SACwE;CAExE,OAAO;EAAC,SAAS;EAAO,SAAS;EAAM,GAAG,kBAAkB,MADzC,0BAA0B,OAAO,CACY;CAAC;AACnE;AAEA,eAAsB,YAAY,EAChC,UACA,WACA,YACA,MAAM,SACsB;CAC5B,MAAM,OAAO,MAAM,0BAA0B;EAAC;EAAU;EAAW;CAAU,CAAC;CAC9E,MAAM,aAAa,kBAAkB,IAAI;CACzC,IAAI,CAAC,KACH,OAAO;EACL,SAAS;EACT,SAAS;EACT,GAAG;EACH,wBAAwB;CAC1B;CAEF,MAAM,UAAU,MAAM,gBAAgB;EAAC,SAAS,KAAK;EAAS,YAAY,KAAK;EAAY;CAAG,CAAC;CAC/F,OAAO;EAAC,SAAS;EAAM,GAAG;EAAY,GAAG;CAAO;AAClD"}
@@ -0,0 +1,55 @@
1
+ import { ExtensionBundlePlan } from './extension-bundle';
2
+ import { DirectoryComparison } from './output-safety';
3
+ interface ExtensionBundleComponentMetadata {
4
+ author: string | null;
5
+ description: string | null;
6
+ id: string | null;
7
+ license: string | null;
8
+ name: string | null;
9
+ }
10
+ export interface ExtensionBundleConfigurationInput {
11
+ bundleId: string;
12
+ bundleName: string;
13
+ extensionIds?: string[];
14
+ recoveryCapsule?: boolean;
15
+ sourceDirectory: string;
16
+ yes?: boolean;
17
+ }
18
+ export interface ExtensionBundlePlanResult {
19
+ applied: boolean;
20
+ bundleId: string;
21
+ bundleName: string;
22
+ changed: boolean;
23
+ components: ExtensionBundleComponentMetadata[];
24
+ counts: ExtensionBundlePlan['counts'];
25
+ members: string[];
26
+ recoveryCapsule: boolean;
27
+ sourceDirectory: string;
28
+ }
29
+ export interface ExtensionBundleApplyResult extends ExtensionBundlePlanResult {
30
+ comparison?: DirectoryComparison;
31
+ rollbackCleanupWarning: string | null;
32
+ }
33
+ export interface ExtensionUnbundlePlanResult {
34
+ applied: boolean;
35
+ bundleId: string;
36
+ changed: boolean;
37
+ members: string[];
38
+ sourceDirectory: string;
39
+ }
40
+ export interface ExtensionUnbundleApplyResult extends ExtensionUnbundlePlanResult {
41
+ comparison?: DirectoryComparison;
42
+ rollbackCleanupWarning: string | null;
43
+ }
44
+ export declare function planExtensionBundle({ bundleId, bundleName, extensionIds, recoveryCapsule, sourceDirectory, }: ExtensionBundleConfigurationInput): Promise<ExtensionBundlePlanResult>;
45
+ export declare function bundleExtensions({ bundleId, bundleName, extensionIds, recoveryCapsule, sourceDirectory, yes, }: ExtensionBundleConfigurationInput): Promise<ExtensionBundleApplyResult>;
46
+ export declare function planExtensionUnbundle({ bundleId, sourceDirectory, }: {
47
+ bundleId: string;
48
+ sourceDirectory: string;
49
+ }): Promise<ExtensionUnbundlePlanResult>;
50
+ export declare function unbundleExtensions({ bundleId, sourceDirectory, yes, }: {
51
+ bundleId: string;
52
+ sourceDirectory: string;
53
+ yes?: boolean;
54
+ }): Promise<ExtensionUnbundleApplyResult>;
55
+ export {};
@@ -0,0 +1,200 @@
1
+ import { assert } from "./assert.js";
2
+ import { assertNoInterruptedRollback, compareDirectories, pathExists, replaceDirectoryTransactionally } from "./output-safety.js";
3
+ import { buildExtensionBundles, validateBundleId, validateBundleName, validateExtensionBundleConfigurations } from "./extension-bundle.js";
4
+ import { createDeterministicSb3, inspectSb3SourceForExtensionSync } from "./source.js";
5
+ import path from "node:path";
6
+ import { cp, lstat, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
7
+ //#region src/extension-bundle-configuration.ts
8
+ async function inspectConfigurationSource(sourceDirectory, willReplace) {
9
+ const resolvedSourceDirectory = path.resolve(sourceDirectory);
10
+ if (willReplace) {
11
+ assert(resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root, "Refusing to replace a filesystem root while configuring extension bundles.");
12
+ assert(!await pathExists(path.join(resolvedSourceDirectory, ".git")), "Refusing to replace a Git repository root while configuring extension bundles.");
13
+ }
14
+ const stats = await lstat(resolvedSourceDirectory);
15
+ assert(stats.isDirectory() && !stats.isSymbolicLink(), `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`);
16
+ if (willReplace) await assertNoInterruptedRollback(resolvedSourceDirectory);
17
+ return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);
18
+ }
19
+ async function readExtensionManifest(source) {
20
+ const manifestPath = path.join(source.resolvedSourceDirectory, source.sourceManifest.embeddedExtensions);
21
+ return JSON.parse(await readFile(manifestPath, "utf8"));
22
+ }
23
+ async function configurationContext({ bundleId, bundleName, extensionIds, recoveryCapsule, sourceDirectory, willReplace }) {
24
+ validateBundleId(bundleId);
25
+ validateBundleName(bundleName);
26
+ assert(typeof recoveryCapsule === "boolean", "recoveryCapsule must be a boolean.");
27
+ const source = await inspectConfigurationSource(sourceDirectory, willReplace);
28
+ const extensionManifest = await readExtensionManifest(source);
29
+ const existingBundles = validateExtensionBundleConfigurations(extensionManifest.extensionBundles, extensionManifest.extensions);
30
+ assert(!existingBundles.some((bundle) => bundle.id === bundleId), `Extension bundle already exists: ${bundleId}`);
31
+ const alreadyBundled = new Set(existingBundles.flatMap((bundle) => bundle.members));
32
+ const members = extensionIds && extensionIds.length > 0 ? [...extensionIds] : source.extensions.map((extension) => extension.id).filter((extensionId) => !alreadyBundled.has(extensionId));
33
+ const candidateManifest = structuredClone(extensionManifest);
34
+ candidateManifest.extensionBundles = [...existingBundles, {
35
+ id: bundleId,
36
+ members,
37
+ name: bundleName,
38
+ ...recoveryCapsule === true ? { recoveryCapsule: true } : {}
39
+ }];
40
+ const extensionBundles = validateExtensionBundleConfigurations(candidateManifest.extensionBundles, candidateManifest.extensions);
41
+ const buildPlan = buildExtensionBundles({
42
+ extensionBundles,
43
+ extensionContents: source.extensionContents,
44
+ extensions: source.extensions,
45
+ project: source.project
46
+ });
47
+ const configuredBundle = buildPlan.bundlePlans.find((plan) => plan.bundle.id === bundleId);
48
+ assert(configuredBundle, `Extension bundle plan was not produced: ${bundleId}`);
49
+ return {
50
+ buildPlan,
51
+ candidateManifest,
52
+ configuredBundle,
53
+ extensionManifest,
54
+ source
55
+ };
56
+ }
57
+ async function planExtensionBundle({ bundleId, bundleName, extensionIds, recoveryCapsule = false, sourceDirectory }) {
58
+ const context = await configurationContext({
59
+ bundleId,
60
+ bundleName,
61
+ extensionIds,
62
+ recoveryCapsule,
63
+ sourceDirectory,
64
+ willReplace: false
65
+ });
66
+ return {
67
+ applied: false,
68
+ bundleId,
69
+ bundleName,
70
+ changed: true,
71
+ components: context.configuredBundle.components.map((component) => component.metadata),
72
+ counts: context.configuredBundle.counts,
73
+ members: [...context.configuredBundle.bundle.members],
74
+ recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,
75
+ sourceDirectory: context.source.resolvedSourceDirectory
76
+ };
77
+ }
78
+ async function installManifestConfiguration(context, operation) {
79
+ const initialComparison = await compareDirectories(context.source.resolvedSourceDirectory, context.source.resolvedSourceDirectory);
80
+ assert(initialComparison.identical && initialComparison.existingFingerprint === initialComparison.candidateFingerprint, `SB3 source changed while its initial ${operation} state was inspected.`);
81
+ const parentDirectory = path.dirname(context.source.resolvedSourceDirectory);
82
+ const candidateDirectory = await mkdtemp(path.join(parentDirectory, `.${path.basename(context.source.resolvedSourceDirectory)}.bundle-`));
83
+ let installed = false;
84
+ try {
85
+ await cp(context.source.resolvedSourceDirectory, candidateDirectory, {
86
+ preserveTimestamps: true,
87
+ recursive: true,
88
+ verbatimSymlinks: true
89
+ });
90
+ await writeFile(path.join(candidateDirectory, context.source.sourceManifest.embeddedExtensions), `${JSON.stringify(context.candidateManifest, null, 2)}\n`);
91
+ await createDeterministicSb3(candidateDirectory);
92
+ const comparison = await compareDirectories(context.source.resolvedSourceDirectory, candidateDirectory);
93
+ assert(comparison.existingFingerprint === initialComparison.existingFingerprint, `SB3 source changed while the ${operation} candidate was prepared; refusing to replace it.`);
94
+ assert(!comparison.identical, `Extension bundle ${operation} produced no source changes.`);
95
+ const latestComparison = await compareDirectories(context.source.resolvedSourceDirectory, candidateDirectory);
96
+ assert(latestComparison.existingFingerprint === comparison.existingFingerprint && latestComparison.candidateFingerprint === comparison.candidateFingerprint, `SB3 source or ${operation} candidate changed during the operation; refusing to replace it.`);
97
+ const replacement = await replaceDirectoryTransactionally(candidateDirectory, context.source.resolvedSourceDirectory);
98
+ installed = true;
99
+ return {
100
+ comparison,
101
+ ...replacement
102
+ };
103
+ } finally {
104
+ if (!installed) await rm(candidateDirectory, {
105
+ recursive: true,
106
+ force: true
107
+ });
108
+ }
109
+ }
110
+ async function bundleExtensions({ bundleId, bundleName, extensionIds, recoveryCapsule = false, sourceDirectory, yes = false }) {
111
+ const context = await configurationContext({
112
+ bundleId,
113
+ bundleName,
114
+ extensionIds,
115
+ recoveryCapsule,
116
+ sourceDirectory,
117
+ willReplace: yes
118
+ });
119
+ const plan = {
120
+ bundleId,
121
+ bundleName,
122
+ components: context.configuredBundle.components.map((component) => component.metadata),
123
+ counts: context.configuredBundle.counts,
124
+ members: [...context.configuredBundle.bundle.members],
125
+ recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,
126
+ sourceDirectory: context.source.resolvedSourceDirectory
127
+ };
128
+ if (!yes) return {
129
+ applied: false,
130
+ changed: true,
131
+ ...plan,
132
+ rollbackCleanupWarning: null
133
+ };
134
+ return {
135
+ applied: true,
136
+ changed: true,
137
+ ...await installManifestConfiguration(context, "configuration"),
138
+ ...plan
139
+ };
140
+ }
141
+ async function unbundleContext({ bundleId, sourceDirectory, willReplace }) {
142
+ validateBundleId(bundleId);
143
+ const source = await inspectConfigurationSource(sourceDirectory, willReplace);
144
+ const extensionManifest = await readExtensionManifest(source);
145
+ const extensionBundles = validateExtensionBundleConfigurations(extensionManifest.extensionBundles, extensionManifest.extensions);
146
+ const removedBundle = extensionBundles.find((bundle) => bundle.id === bundleId);
147
+ assert(removedBundle, `Extension bundle was not found: ${bundleId}`);
148
+ const candidateManifest = structuredClone(extensionManifest);
149
+ const remainingBundles = extensionBundles.filter((bundle) => bundle.id !== bundleId);
150
+ if (remainingBundles.length === 0) delete candidateManifest.extensionBundles;
151
+ else candidateManifest.extensionBundles = remainingBundles;
152
+ return {
153
+ candidateManifest,
154
+ extensionManifest,
155
+ removedBundle,
156
+ source
157
+ };
158
+ }
159
+ async function planExtensionUnbundle({ bundleId, sourceDirectory }) {
160
+ const context = await unbundleContext({
161
+ bundleId,
162
+ sourceDirectory,
163
+ willReplace: false
164
+ });
165
+ return {
166
+ applied: false,
167
+ bundleId,
168
+ changed: true,
169
+ members: [...context.removedBundle.members],
170
+ sourceDirectory: context.source.resolvedSourceDirectory
171
+ };
172
+ }
173
+ async function unbundleExtensions({ bundleId, sourceDirectory, yes = false }) {
174
+ const context = await unbundleContext({
175
+ bundleId,
176
+ sourceDirectory,
177
+ willReplace: yes
178
+ });
179
+ const plan = {
180
+ bundleId,
181
+ members: [...context.removedBundle.members],
182
+ sourceDirectory: context.source.resolvedSourceDirectory
183
+ };
184
+ if (!yes) return {
185
+ applied: false,
186
+ changed: true,
187
+ ...plan,
188
+ rollbackCleanupWarning: null
189
+ };
190
+ return {
191
+ applied: true,
192
+ changed: true,
193
+ ...await installManifestConfiguration(context, "removal"),
194
+ ...plan
195
+ };
196
+ }
197
+ //#endregion
198
+ export { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions };
199
+
200
+ //# sourceMappingURL=extension-bundle-configuration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-bundle-configuration.js","names":[],"sources":["../src/extension-bundle-configuration.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {cp, lstat, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert} from './assert';\nimport {\n buildExtensionBundles,\n validateBundleId,\n validateBundleName,\n validateExtensionBundleConfigurations,\n} from './extension-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n assertNoInterruptedRollback,\n compareDirectories,\n pathExists,\n replaceDirectoryTransactionally,\n} from './output-safety';\nimport type {DirectoryComparison} from './output-safety';\nimport {createDeterministicSb3, inspectSb3SourceForExtensionSync} from './source';\nimport type {InspectedSb3Source} from './source';\nimport type {EmbeddedExtensionManifest, ExtensionBundleConfiguration} from './types';\n\ninterface ExtensionBundleComponentMetadata {\n author: string | null;\n description: string | null;\n id: string | null;\n license: string | null;\n name: string | null;\n}\n\ninterface ConfigurationContext {\n buildPlan: ReturnType<typeof buildExtensionBundles>;\n candidateManifest: EmbeddedExtensionManifest;\n configuredBundle: ExtensionBundlePlan;\n extensionManifest: EmbeddedExtensionManifest;\n source: InspectedSb3Source;\n}\n\ninterface UnbundleContext {\n candidateManifest: EmbeddedExtensionManifest;\n extensionManifest: EmbeddedExtensionManifest;\n removedBundle: ExtensionBundleConfiguration;\n source: InspectedSb3Source;\n}\n\nexport interface ExtensionBundleConfigurationInput {\n bundleId: string;\n bundleName: string;\n extensionIds?: string[];\n recoveryCapsule?: boolean;\n sourceDirectory: string;\n yes?: boolean;\n}\n\nexport interface ExtensionBundlePlanResult {\n applied: boolean;\n bundleId: string;\n bundleName: string;\n changed: boolean;\n components: ExtensionBundleComponentMetadata[];\n counts: ExtensionBundlePlan['counts'];\n members: string[];\n recoveryCapsule: boolean;\n sourceDirectory: string;\n}\n\nexport interface ExtensionBundleApplyResult extends ExtensionBundlePlanResult {\n comparison?: DirectoryComparison;\n rollbackCleanupWarning: string | null;\n}\n\nexport interface ExtensionUnbundlePlanResult {\n applied: boolean;\n bundleId: string;\n changed: boolean;\n members: string[];\n sourceDirectory: string;\n}\n\nexport interface ExtensionUnbundleApplyResult extends ExtensionUnbundlePlanResult {\n comparison?: DirectoryComparison;\n rollbackCleanupWarning: string | null;\n}\n\nasync function inspectConfigurationSource(\n sourceDirectory: string,\n willReplace: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n if (willReplace) {\n assert(\n resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root,\n 'Refusing to replace a filesystem root while configuring extension bundles.',\n );\n assert(\n !(await pathExists(path.join(resolvedSourceDirectory, '.git'))),\n 'Refusing to replace a Git repository root while configuring extension bundles.',\n );\n }\n const stats = await lstat(resolvedSourceDirectory);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`,\n );\n if (willReplace) await assertNoInterruptedRollback(resolvedSourceDirectory);\n return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);\n}\n\nasync function readExtensionManifest(\n source: InspectedSb3Source,\n): Promise<EmbeddedExtensionManifest> {\n const manifestPath = path.join(\n source.resolvedSourceDirectory,\n source.sourceManifest.embeddedExtensions,\n );\n return JSON.parse(await readFile(manifestPath, 'utf8')) as EmbeddedExtensionManifest;\n}\n\nasync function configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n willReplace,\n}: Required<\n Pick<\n ExtensionBundleConfigurationInput,\n 'bundleId' | 'bundleName' | 'recoveryCapsule' | 'sourceDirectory'\n >\n> & {\n extensionIds?: string[];\n willReplace: boolean;\n}): Promise<ConfigurationContext> {\n validateBundleId(bundleId);\n validateBundleName(bundleName);\n assert(typeof recoveryCapsule === 'boolean', 'recoveryCapsule must be a boolean.');\n const source = await inspectConfigurationSource(sourceDirectory, willReplace);\n const extensionManifest = await readExtensionManifest(source);\n const existingBundles = validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensionManifest.extensions,\n );\n assert(\n !existingBundles.some((bundle) => bundle.id === bundleId),\n `Extension bundle already exists: ${bundleId}`,\n );\n const alreadyBundled = new Set(existingBundles.flatMap((bundle) => bundle.members));\n const members =\n extensionIds && extensionIds.length > 0\n ? [...extensionIds]\n : source.extensions\n .map((extension) => extension.id)\n .filter((extensionId) => !alreadyBundled.has(extensionId));\n const candidateManifest = structuredClone(extensionManifest);\n candidateManifest.extensionBundles = [\n ...existingBundles,\n {\n id: bundleId,\n members,\n name: bundleName,\n ...(recoveryCapsule === true ? {recoveryCapsule: true} : {}),\n },\n ];\n const extensionBundles = validateExtensionBundleConfigurations(\n candidateManifest.extensionBundles,\n candidateManifest.extensions,\n );\n const buildPlan = buildExtensionBundles({\n extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n const configuredBundle = buildPlan.bundlePlans.find((plan) => plan.bundle.id === bundleId);\n assert(configuredBundle, `Extension bundle plan was not produced: ${bundleId}`);\n return {buildPlan, candidateManifest, configuredBundle, extensionManifest, source};\n}\n\nexport async function planExtensionBundle({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule = false,\n sourceDirectory,\n}: ExtensionBundleConfigurationInput): Promise<ExtensionBundlePlanResult> {\n const context = await configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n willReplace: false,\n });\n return {\n applied: false,\n bundleId,\n bundleName,\n changed: true,\n components: context.configuredBundle.components.map((component) => component.metadata),\n counts: context.configuredBundle.counts,\n members: [...context.configuredBundle.bundle.members],\n recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n}\n\nasync function installManifestConfiguration(\n context: ConfigurationContext | UnbundleContext,\n operation: string,\n): Promise<{comparison: DirectoryComparison; rollbackCleanupWarning: string | null}> {\n const initialComparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n context.source.resolvedSourceDirectory,\n );\n assert(\n initialComparison.identical &&\n initialComparison.existingFingerprint === initialComparison.candidateFingerprint,\n `SB3 source changed while its initial ${operation} state was inspected.`,\n );\n const parentDirectory = path.dirname(context.source.resolvedSourceDirectory);\n const candidateDirectory = await mkdtemp(\n path.join(parentDirectory, `.${path.basename(context.source.resolvedSourceDirectory)}.bundle-`),\n );\n let installed = false;\n try {\n await cp(context.source.resolvedSourceDirectory, candidateDirectory, {\n preserveTimestamps: true,\n recursive: true,\n verbatimSymlinks: true,\n });\n await writeFile(\n path.join(candidateDirectory, context.source.sourceManifest.embeddedExtensions),\n `${JSON.stringify(context.candidateManifest, null, 2)}\\n`,\n );\n await createDeterministicSb3(candidateDirectory);\n const comparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n candidateDirectory,\n );\n assert(\n comparison.existingFingerprint === initialComparison.existingFingerprint,\n `SB3 source changed while the ${operation} candidate was prepared; refusing to replace it.`,\n );\n assert(!comparison.identical, `Extension bundle ${operation} produced no source changes.`);\n const latestComparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n candidateDirectory,\n );\n assert(\n latestComparison.existingFingerprint === comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === comparison.candidateFingerprint,\n `SB3 source or ${operation} candidate changed during the operation; refusing to replace it.`,\n );\n const replacement = await replaceDirectoryTransactionally(\n candidateDirectory,\n context.source.resolvedSourceDirectory,\n );\n installed = true;\n return {comparison, ...replacement};\n } finally {\n if (!installed) await rm(candidateDirectory, {recursive: true, force: true});\n }\n}\n\nexport async function bundleExtensions({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule = false,\n sourceDirectory,\n yes = false,\n}: ExtensionBundleConfigurationInput): Promise<ExtensionBundleApplyResult> {\n const context = await configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n willReplace: yes,\n });\n const plan = {\n bundleId,\n bundleName,\n components: context.configuredBundle.components.map((component) => component.metadata),\n counts: context.configuredBundle.counts,\n members: [...context.configuredBundle.bundle.members],\n recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n if (!yes) {\n return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};\n }\n const installation = await installManifestConfiguration(context, 'configuration');\n return {applied: true, changed: true, ...installation, ...plan};\n}\n\nasync function unbundleContext({\n bundleId,\n sourceDirectory,\n willReplace,\n}: {\n bundleId: string;\n sourceDirectory: string;\n willReplace: boolean;\n}): Promise<UnbundleContext> {\n validateBundleId(bundleId);\n const source = await inspectConfigurationSource(sourceDirectory, willReplace);\n const extensionManifest = await readExtensionManifest(source);\n const extensionBundles = validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensionManifest.extensions,\n );\n const removedBundle = extensionBundles.find((bundle) => bundle.id === bundleId);\n assert(removedBundle, `Extension bundle was not found: ${bundleId}`);\n const candidateManifest = structuredClone(extensionManifest);\n const remainingBundles = extensionBundles.filter((bundle) => bundle.id !== bundleId);\n if (remainingBundles.length === 0) {\n delete candidateManifest.extensionBundles;\n } else {\n candidateManifest.extensionBundles = remainingBundles;\n }\n return {candidateManifest, extensionManifest, removedBundle, source};\n}\n\nexport async function planExtensionUnbundle({\n bundleId,\n sourceDirectory,\n}: {\n bundleId: string;\n sourceDirectory: string;\n}): Promise<ExtensionUnbundlePlanResult> {\n const context = await unbundleContext({bundleId, sourceDirectory, willReplace: false});\n return {\n applied: false,\n bundleId,\n changed: true,\n members: [...context.removedBundle.members],\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n}\n\nexport async function unbundleExtensions({\n bundleId,\n sourceDirectory,\n yes = false,\n}: {\n bundleId: string;\n sourceDirectory: string;\n yes?: boolean;\n}): Promise<ExtensionUnbundleApplyResult> {\n const context = await unbundleContext({bundleId, sourceDirectory, willReplace: yes});\n const plan = {\n bundleId,\n members: [...context.removedBundle.members],\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n if (!yes) {\n return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};\n }\n const installation = await installManifestConfiguration(context, 'removal');\n return {applied: true, changed: true, ...installation, ...plan};\n}\n"],"mappings":";;;;;;;AAsFA,eAAe,2BACb,iBACA,aAC6B;CAC7B,MAAM,0BAA0B,KAAK,QAAQ,eAAe;CAC5D,IAAI,aAAa;EACf,OACE,4BAA4B,KAAK,MAAM,uBAAuB,CAAC,CAAC,MAChE,4EACF;EACA,OACE,CAAE,MAAM,WAAW,KAAK,KAAK,yBAAyB,MAAM,CAAC,GAC7D,gFACF;CACF;CACA,MAAM,QAAQ,MAAM,MAAM,uBAAuB;CACjD,OACE,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAC7C,gEAAgE,yBAClE;CACA,IAAI,aAAa,MAAM,4BAA4B,uBAAuB;CAC1E,OAAO,iCAAiC,uBAAuB;AACjE;AAEA,eAAe,sBACb,QACoC;CACpC,MAAM,eAAe,KAAK,KACxB,OAAO,yBACP,OAAO,eAAe,kBACxB;CACA,OAAO,KAAK,MAAM,MAAM,SAAS,cAAc,MAAM,CAAC;AACxD;AAEA,eAAe,qBAAqB,EAClC,UACA,YACA,cACA,iBACA,iBACA,eASgC;CAChC,iBAAiB,QAAQ;CACzB,mBAAmB,UAAU;CAC7B,OAAO,OAAO,oBAAoB,WAAW,oCAAoC;CACjF,MAAM,SAAS,MAAM,2BAA2B,iBAAiB,WAAW;CAC5E,MAAM,oBAAoB,MAAM,sBAAsB,MAAM;CAC5D,MAAM,kBAAkB,sCACtB,kBAAkB,kBAClB,kBAAkB,UACpB;CACA,OACE,CAAC,gBAAgB,MAAM,WAAW,OAAO,OAAO,QAAQ,GACxD,oCAAoC,UACtC;CACA,MAAM,iB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