@kubohiroya/sb3-toolchain 0.16.0 → 0.17.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.
@@ -0,0 +1,266 @@
1
+ import { assert } from "./assert.js";
2
+ import { extensionIntegrity, unsandboxedRequirement } from "./extension-dependencies.js";
3
+ import { buildExtensionBundles, bundleHeader, bundleUnsandboxedRequirement, createStaticExtensionBundle, extensionBundleRecoveryMarker, readBundleComponents, sandboxedGuardSource, sandboxedNotice } from "./extension-bundle.js";
4
+ import { findPackageDirectory, readNpmExtensionSource, readPackageArtifact } from "./npm-extension-source.js";
5
+ import path from "node:path";
6
+ import { readFile, realpath } from "node:fs/promises";
7
+ import { builtinModules } from "node:module";
8
+ import { satisfies, valid, validRange } from "semver";
9
+ //#region src/extension-module-bundle.ts
10
+ function within(root, file) {
11
+ const relative = path.relative(root, file);
12
+ return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
13
+ }
14
+ function compare(left, right) {
15
+ return left < right ? -1 : left > right ? 1 : 0;
16
+ }
17
+ async function dependencyLock(directory) {
18
+ let current = path.resolve(directory);
19
+ while (true) {
20
+ const found = [];
21
+ for (const file of ["pnpm-lock.yaml", "package-lock.json"]) try {
22
+ found.push({
23
+ file,
24
+ integrity: extensionIntegrity(await readFile(path.join(current, file)))
25
+ });
26
+ } catch (error) {
27
+ if (error.code !== "ENOENT") throw error;
28
+ }
29
+ assert(found.length < 2, `Module build has ambiguous dependency locks in ${current}.`);
30
+ if (found.length) return found[0];
31
+ const parent = path.dirname(current);
32
+ assert(parent !== current, "Module builds require pnpm-lock.yaml or package-lock.json in the project.");
33
+ current = parent;
34
+ }
35
+ }
36
+ /** Parse and bundle installed ESM only; no owner module or project build configuration is executed. */
37
+ async function compileExtensionModuleBundle(bundle, components, project, sourceDirectory) {
38
+ const lock = await dependencyLock(sourceDirectory);
39
+ const manifests = /* @__PURE__ */ new Map();
40
+ const packageCache = /* @__PURE__ */ new Map();
41
+ async function owner(file) {
42
+ const directory = path.dirname(file);
43
+ let promise = packageCache.get(directory);
44
+ if (!promise) {
45
+ promise = (async () => {
46
+ try {
47
+ const manifestFile = await realpath(path.join(directory, "package.json"));
48
+ const manifestContents = await readFile(manifestFile);
49
+ manifests.set(manifestFile, manifestContents);
50
+ const metadata = JSON.parse(manifestContents.toString("utf8"));
51
+ if (metadata.name === void 0 && metadata.version === void 0) {
52
+ assert(path.dirname(directory) !== directory, `Module has no owning npm package: ${file}`);
53
+ return owner(directory);
54
+ }
55
+ assert(typeof metadata.name === "string" && !!valid(metadata.version), `Invalid installed package metadata: ${directory}`);
56
+ return {
57
+ ...metadata,
58
+ root: await realpath(directory)
59
+ };
60
+ } catch (error) {
61
+ if (error.code !== "ENOENT") throw error;
62
+ assert(path.dirname(directory) !== directory, `Module has no owning npm package: ${file}`);
63
+ return owner(directory);
64
+ }
65
+ })();
66
+ packageCache.set(directory, promise);
67
+ }
68
+ return promise;
69
+ }
70
+ const entries = [];
71
+ const members = [];
72
+ const effectiveComponents = [];
73
+ for (const component of components) {
74
+ const source = component.extension.source;
75
+ assert(source?.provider === "npm" && source.module, `Module bundle member ${component.extension.id} needs an npm source.module entry.`);
76
+ const installed = await readNpmExtensionSource(component.extension, sourceDirectory, {
77
+ maximumArtifactBytes: 20971520,
78
+ maximumManifestBytes: 2097152
79
+ });
80
+ assert(Buffer.from(installed.contents).equals(component.originalContents), `Installed classic artifact differs for module member ${component.extension.id}. Sync the pinned package first.`);
81
+ const bytes = await readPackageArtifact(installed.packageDirectory, source.module.artifact, 20971520, `Module entry ${component.extension.id}`);
82
+ assert(extensionIntegrity(bytes) === source.module.integrity, `Module integrity mismatch: ${component.extension.id}`);
83
+ const declared = unsandboxedRequirement(component.metadata);
84
+ assert(declared === null || declared === source.module.unsandboxed, `Module sandbox declaration disagrees with classic header: ${component.extension.id}`);
85
+ entries.push(await realpath(path.join(installed.packageDirectory, source.module.artifact)));
86
+ members.push({
87
+ id: component.extension.id,
88
+ package: source.package,
89
+ version: installed.version,
90
+ artifact: source.module.artifact,
91
+ integrity: source.module.integrity
92
+ });
93
+ effectiveComponents.push({
94
+ ...component,
95
+ metadata: {
96
+ ...component.metadata,
97
+ unsandboxed: source.module.unsandboxed
98
+ }
99
+ });
100
+ }
101
+ const selected = /* @__PURE__ */ new Map();
102
+ for (const [name, version] of Object.entries(bundle.sharedDependencies ?? {}).sort(([a], [b]) => compare(a, b))) {
103
+ assert(valid(version) === version, `Shared dependency ${name} requires an exact semantic version.`);
104
+ const directory = await findPackageDirectory(sourceDirectory, name);
105
+ const installed = await owner(path.join(directory, "package.json"));
106
+ assert(installed.name === name && installed.version === version, `Shared dependency ${name}: expected ${version}, installed ${installed.version}.`);
107
+ selected.set(name, installed);
108
+ }
109
+ const virtualEntry = `\0sb3-module-bundle:${bundle.id}`;
110
+ const bindings = components.map((_, index) => `sb3Module${index}`);
111
+ const runtime = createStaticExtensionBundle(bundle, effectiveComponents, project, bindings).toString("utf8");
112
+ const entrySource = `${entries.map((file, index) => `import * as ${bindings[index]} from ${JSON.stringify(file)};`).join("\n")}\n${runtime}`;
113
+ const loaded = /* @__PURE__ */ new Map();
114
+ const nativeModules = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));
115
+ const resolutionAnchor = path.join(sourceDirectory, "__sb3_shared_dependencies__.js");
116
+ const plugin = {
117
+ name: "sb3-module-inputs",
118
+ async resolveId(request, importer) {
119
+ if (request === virtualEntry) return virtualEntry;
120
+ assert(!nativeModules.has(request) && !/^(?:https?|data|file):/u.test(request), `Module bundle cannot use a native or remote import: ${request}`);
121
+ const match = [...selected].find(([name]) => request === name || request.startsWith(`${name}/`));
122
+ if (match) {
123
+ const [name, installed] = match;
124
+ if (importer && !importer.startsWith("\0")) {
125
+ const caller = await owner(importer);
126
+ if (caller.root !== installed.root) {
127
+ const range = caller.dependencies?.[name] ?? caller.optionalDependencies?.[name] ?? caller.peerDependencies?.[name];
128
+ assert(range && validRange(range) && satisfies(installed.version, range), `Incompatible shared dependency ${name}@${installed.version}: ${caller.name}@${caller.version} requires ${range ?? "(undeclared)"}.`);
129
+ }
130
+ }
131
+ const resolved = await this.resolve(request, resolutionAnchor, { skipSelf: true });
132
+ assert(resolved && !resolved.external && within(installed.root, await realpath(resolved.id)), `Shared dependency resolved outside pinned package: ${request}`);
133
+ return resolved;
134
+ }
135
+ return null;
136
+ },
137
+ async load(id) {
138
+ if (id === virtualEntry) return entrySource;
139
+ if (id.startsWith("\0")) return null;
140
+ assert(path.isAbsolute(id), `Module input must resolve to an installed file: ${id}`);
141
+ const file = await realpath(id);
142
+ const installed = await owner(file);
143
+ assert(file.includes(`${path.sep}node_modules${path.sep}`), `Module input is outside installed npm packages: ${file}`);
144
+ const shared = selected.get(installed.name);
145
+ if (shared) {
146
+ assert(shared.root === installed.root, `Duplicate shared dependency in module graph: ${installed.name}`);
147
+ if (installed.name === "yaml") assert(within(path.join(shared.root, "browser"), file) || file === path.join(shared.root, "package.json"), "Shared yaml must use the browser entry exclusively; node/browser module mixing is unsupported.");
148
+ }
149
+ const contents = await readFile(file);
150
+ loaded.set(file, {
151
+ package: installed,
152
+ contents
153
+ });
154
+ return null;
155
+ }
156
+ };
157
+ const { rolldown, VERSION } = await import("rolldown");
158
+ const build = await rolldown({
159
+ input: virtualEntry,
160
+ cwd: sourceDirectory,
161
+ platform: "browser",
162
+ resolve: {
163
+ conditionNames: [
164
+ "browser",
165
+ "import",
166
+ "default"
167
+ ],
168
+ symlinks: true
169
+ },
170
+ transform: { target: "es2020" },
171
+ tsconfig: false,
172
+ plugins: [plugin],
173
+ onwarn(warning, defaultHandler) {
174
+ assert(warning.code !== "UNRESOLVED_IMPORT", warning.message);
175
+ defaultHandler(warning);
176
+ }
177
+ });
178
+ try {
179
+ const { output } = await build.generate({
180
+ format: "iife",
181
+ codeSplitting: false,
182
+ sourcemap: false,
183
+ minify: false,
184
+ strictExecutionOrder: true,
185
+ comments: { legal: true }
186
+ });
187
+ assert(output.length === 1 && output[0].type === "chunk", "Module bundle must emit exactly one JavaScript chunk.");
188
+ const chunk = output[0];
189
+ assert(chunk.imports.length === 0 && chunk.dynamicImports.length === 0, "Module bundle has unresolved runtime imports.");
190
+ const sharedDependencies = [];
191
+ for (const [name, installed] of selected) {
192
+ const matches = [...loaded.values()].filter((input) => input.package.name === name);
193
+ const roots = new Set(matches.map((input) => input.package.root));
194
+ assert(roots.size <= 1 && [...roots].every((root) => root === installed.root), `Duplicate shared dependency in module graph: ${name}`);
195
+ if (name === "yaml") assert([...loaded].filter(([, input]) => input.package.name === name).every(([file]) => within(path.join(installed.root, "browser"), file) || file === path.join(installed.root, "package.json")), "Shared yaml must use the browser entry exclusively; node/browser module mixing is unsupported.");
196
+ sharedDependencies.push({
197
+ package: name,
198
+ version: installed.version,
199
+ moduleCount: matches.length,
200
+ copies: roots.size
201
+ });
202
+ }
203
+ const inputs = [...loaded].map(([file, input]) => ({
204
+ package: input.package.name,
205
+ version: input.package.version,
206
+ file: path.relative(input.package.root, file).split(path.sep).join("/"),
207
+ integrity: extensionIntegrity(input.contents)
208
+ }));
209
+ for (const [file, contents] of manifests) {
210
+ const installed = await owner(file);
211
+ inputs.push({
212
+ package: installed.name,
213
+ version: installed.version,
214
+ file: path.relative(installed.root, file).split(path.sep).join("/"),
215
+ integrity: extensionIntegrity(contents)
216
+ });
217
+ }
218
+ inputs.sort((a, b) => compare(JSON.stringify(a), JSON.stringify(b)));
219
+ const settings = {
220
+ formatVersion: 1,
221
+ bundler: {
222
+ name: "rolldown",
223
+ version: VERSION
224
+ },
225
+ platform: "browser",
226
+ target: "es2020",
227
+ lock,
228
+ members,
229
+ inputs,
230
+ sharedDependencies
231
+ };
232
+ const report = {
233
+ ...settings,
234
+ inputIntegrity: extensionIntegrity(JSON.stringify(settings))
235
+ };
236
+ const requirement = bundleUnsandboxedRequirement(effectiveComponents);
237
+ const notice = sandboxedNotice(bundle, requirement);
238
+ const guard = sandboxedGuardSource(requirement, notice);
239
+ const code = chunk.code.replace(/^[\t ]*\/\/#(?:end)?region[^\r\n]*(?:\r?\n|$)/gm, "");
240
+ const capsule = bundle.recoveryCapsule ? runtime.split("\n").find((line) => line.startsWith(`// ${extensionBundleRecoveryMarker}: `)) : void 0;
241
+ return {
242
+ contents: Buffer.from(`${bundleHeader(bundle, effectiveComponents)}// Module build inputs: ${report.inputIntegrity}\n(function (Scratch) {\n'use strict';\nconst BUNDLE_ID = ${JSON.stringify(bundle.id)};\nconst BUNDLE_NAME = ${JSON.stringify(bundle.name)};\n${guard}\n${code}\n})(Scratch);\n${capsule ? `${capsule}\n` : ""}`),
243
+ report
244
+ };
245
+ } finally {
246
+ await build.close();
247
+ }
248
+ }
249
+ /** Asynchronous opt-in layer; the synchronous classic API remains unchanged. */
250
+ async function buildExtensionBundlesWithModules(input) {
251
+ const moduleBuilds = /* @__PURE__ */ new Map();
252
+ const extensions = new Map(input.extensions.map((extension) => [extension.id, extension]));
253
+ for (const bundle of input.extensionBundles) {
254
+ if (bundle.buildMode !== "module") continue;
255
+ const components = readBundleComponents(bundle, extensions, input.extensionContents);
256
+ moduleBuilds.set(bundle.id, await compileExtensionModuleBundle(bundle, components, input.project, input.sourceDirectory));
257
+ }
258
+ return buildExtensionBundles({
259
+ ...input,
260
+ moduleBuilds
261
+ });
262
+ }
263
+ //#endregion
264
+ export { buildExtensionBundlesWithModules, compileExtensionModuleBundle };
265
+
266
+ //# sourceMappingURL=extension-module-bundle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-module-bundle.js","names":[],"sources":["../src/extension-module-bundle.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {builtinModules} from 'node:module';\nimport {readFile, realpath} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type {Plugin} from 'rolldown';\nimport {satisfies, valid, validRange} from 'semver';\n\nimport {assert} from './assert';\nimport {\n buildExtensionBundles,\n bundleHeader,\n bundleUnsandboxedRequirement,\n createStaticExtensionBundle,\n extensionBundleRecoveryMarker,\n readBundleComponents,\n sandboxedGuardSource,\n sandboxedNotice,\n} from './extension-bundle';\nimport type {\n BuildExtensionBundlesInput,\n BuildExtensionBundlesResult,\n ExtensionBundleComponent,\n} from './extension-bundle';\nimport {extensionIntegrity, unsandboxedRequirement} from './extension-dependencies';\nimport {\n findPackageDirectory,\n readNpmExtensionSource,\n readPackageArtifact,\n} from './npm-extension-source';\nimport type {ExtensionBundleConfiguration, ProjectJson} from './types';\n\ninterface InstalledPackage {\n root: string;\n name: string;\n version: string;\n dependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n}\n\nexport interface ExtensionModuleBuildReport {\n formatVersion: 1;\n bundler: {name: 'rolldown'; version: string};\n platform: 'browser';\n target: 'es2020';\n lock: {file: string; integrity: string};\n members: {id: string; package: string; version: string; artifact: string; integrity: string}[];\n inputs: {package: string; version: string; file: string; integrity: string}[];\n sharedDependencies: {package: string; version: string; moduleCount: number; copies: number}[];\n inputIntegrity: string;\n}\n\nexport interface ExtensionModuleBuild {\n contents: Buffer;\n report: ExtensionModuleBuildReport;\n}\n\nfunction within(root: string, file: string): boolean {\n const relative = path.relative(root, file);\n return (\n relative === '' ||\n (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))\n );\n}\n\nfunction compare(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nasync function dependencyLock(directory: string): Promise<{file: string; integrity: string}> {\n let current = path.resolve(directory);\n while (true) {\n const found: {file: string; integrity: string}[] = [];\n for (const file of ['pnpm-lock.yaml', 'package-lock.json']) {\n try {\n found.push({file, integrity: extensionIntegrity(await readFile(path.join(current, file)))});\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n }\n assert(found.length < 2, `Module build has ambiguous dependency locks in ${current}.`);\n if (found.length) return found[0];\n const parent = path.dirname(current);\n assert(\n parent !== current,\n 'Module builds require pnpm-lock.yaml or package-lock.json in the project.',\n );\n current = parent;\n }\n}\n\n/** Parse and bundle installed ESM only; no owner module or project build configuration is executed. */\nexport async function compileExtensionModuleBundle(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n project: ProjectJson,\n sourceDirectory: string,\n): Promise<ExtensionModuleBuild> {\n const lock = await dependencyLock(sourceDirectory);\n const manifests = new Map<string, Buffer>();\n const packageCache = new Map<string, Promise<InstalledPackage>>();\n async function owner(file: string): Promise<InstalledPackage> {\n const directory = path.dirname(file);\n let promise = packageCache.get(directory);\n if (!promise) {\n promise = (async () => {\n try {\n const manifestFile = await realpath(path.join(directory, 'package.json'));\n const manifestContents = await readFile(manifestFile);\n manifests.set(manifestFile, manifestContents);\n const metadata = JSON.parse(manifestContents.toString('utf8')) as Omit<\n InstalledPackage,\n 'root'\n >;\n if (metadata.name === undefined && metadata.version === undefined) {\n assert(\n path.dirname(directory) !== directory,\n `Module has no owning npm package: ${file}`,\n );\n return owner(directory);\n }\n assert(\n typeof metadata.name === 'string' && !!valid(metadata.version),\n `Invalid installed package metadata: ${directory}`,\n );\n return {...metadata, root: await realpath(directory)};\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n assert(\n path.dirname(directory) !== directory,\n `Module has no owning npm package: ${file}`,\n );\n return owner(directory);\n }\n })();\n packageCache.set(directory, promise);\n }\n return promise;\n }\n\n const entries: string[] = [];\n const members: ExtensionModuleBuildReport['members'] = [];\n const effectiveComponents: ExtensionBundleComponent[] = [];\n for (const component of components) {\n const source = component.extension.source;\n assert(\n source?.provider === 'npm' && source.module,\n `Module bundle member ${component.extension.id} needs an npm source.module entry.`,\n );\n const installed = await readNpmExtensionSource(component.extension, sourceDirectory, {\n maximumArtifactBytes: 20 * 1024 * 1024,\n maximumManifestBytes: 2 * 1024 * 1024,\n });\n assert(\n Buffer.from(installed.contents).equals(component.originalContents),\n `Installed classic artifact differs for module member ${component.extension.id}. Sync the pinned package first.`,\n );\n const bytes = await readPackageArtifact(\n installed.packageDirectory,\n source.module.artifact,\n 20 * 1024 * 1024,\n `Module entry ${component.extension.id}`,\n );\n assert(\n extensionIntegrity(bytes) === source.module.integrity,\n `Module integrity mismatch: ${component.extension.id}`,\n );\n const declared = unsandboxedRequirement(component.metadata);\n assert(\n declared === null || declared === source.module.unsandboxed,\n `Module sandbox declaration disagrees with classic header: ${component.extension.id}`,\n );\n entries.push(await realpath(path.join(installed.packageDirectory, source.module.artifact)));\n members.push({\n id: component.extension.id,\n package: source.package,\n version: installed.version,\n artifact: source.module.artifact,\n integrity: source.module.integrity,\n });\n effectiveComponents.push({\n ...component,\n metadata: {...component.metadata, unsandboxed: source.module.unsandboxed},\n });\n }\n\n const selected = new Map<string, InstalledPackage>();\n for (const [name, version] of Object.entries(bundle.sharedDependencies ?? {}).sort(([a], [b]) =>\n compare(a, b),\n )) {\n assert(\n valid(version) === version,\n `Shared dependency ${name} requires an exact semantic version.`,\n );\n const directory = await findPackageDirectory(sourceDirectory, name);\n const installed = await owner(path.join(directory, 'package.json'));\n assert(\n installed.name === name && installed.version === version,\n `Shared dependency ${name}: expected ${version}, installed ${installed.version}.`,\n );\n selected.set(name, installed);\n }\n\n const virtualEntry = `\\0sb3-module-bundle:${bundle.id}`;\n const bindings = components.map((_, index) => `sb3Module${index}`);\n const runtime = createStaticExtensionBundle(\n bundle,\n effectiveComponents,\n project,\n bindings,\n ).toString('utf8');\n const imports = entries\n .map((file, index) => `import * as ${bindings[index]} from ${JSON.stringify(file)};`)\n .join('\\n');\n const entrySource = `${imports}\\n${runtime}`;\n const loaded = new Map<string, {package: InstalledPackage; contents: Buffer}>();\n const nativeModules = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));\n const resolutionAnchor = path.join(sourceDirectory, '__sb3_shared_dependencies__.js');\n const plugin: Plugin = {\n name: 'sb3-module-inputs',\n async resolveId(request, importer) {\n if (request === virtualEntry) return virtualEntry;\n assert(\n !nativeModules.has(request) && !/^(?:https?|data|file):/u.test(request),\n `Module bundle cannot use a native or remote import: ${request}`,\n );\n const match = [...selected].find(\n ([name]) => request === name || request.startsWith(`${name}/`),\n );\n if (match) {\n const [name, installed] = match;\n if (importer && !importer.startsWith('\\0')) {\n const caller = await owner(importer);\n if (caller.root !== installed.root) {\n const range =\n caller.dependencies?.[name] ??\n caller.optionalDependencies?.[name] ??\n caller.peerDependencies?.[name];\n assert(\n range && validRange(range) && satisfies(installed.version, range),\n `Incompatible shared dependency ${name}@${installed.version}: ${caller.name}@${caller.version} requires ${range ?? '(undeclared)'}.`,\n );\n }\n }\n const resolved = await this.resolve(request, resolutionAnchor, {skipSelf: true});\n assert(\n resolved && !resolved.external && within(installed.root, await realpath(resolved.id)),\n `Shared dependency resolved outside pinned package: ${request}`,\n );\n return resolved;\n }\n return null;\n },\n async load(id) {\n if (id === virtualEntry) return entrySource;\n if (id.startsWith('\\0')) return null;\n assert(path.isAbsolute(id), `Module input must resolve to an installed file: ${id}`);\n const file = await realpath(id);\n const installed = await owner(file);\n assert(\n file.includes(`${path.sep}node_modules${path.sep}`),\n `Module input is outside installed npm packages: ${file}`,\n );\n const shared = selected.get(installed.name);\n if (shared) {\n assert(\n shared.root === installed.root,\n `Duplicate shared dependency in module graph: ${installed.name}`,\n );\n if (installed.name === 'yaml')\n assert(\n within(path.join(shared.root, 'browser'), file) ||\n file === path.join(shared.root, 'package.json'),\n 'Shared yaml must use the browser entry exclusively; node/browser module mixing is unsupported.',\n );\n }\n const contents = await readFile(file);\n loaded.set(file, {package: installed, contents});\n return null;\n },\n };\n // Keep the native bundler unloaded on the default classic path.\n const {rolldown, VERSION} = await import('rolldown');\n const build = await rolldown({\n input: virtualEntry,\n cwd: sourceDirectory,\n platform: 'browser',\n resolve: {conditionNames: ['browser', 'import', 'default'], symlinks: true},\n transform: {target: 'es2020'},\n tsconfig: false,\n plugins: [plugin],\n onwarn(warning, defaultHandler) {\n assert(warning.code !== 'UNRESOLVED_IMPORT', warning.message);\n defaultHandler(warning);\n },\n });\n try {\n const {output} = await build.generate({\n format: 'iife',\n codeSplitting: false,\n sourcemap: false,\n minify: false,\n strictExecutionOrder: true,\n comments: {legal: true},\n });\n assert(\n output.length === 1 && output[0].type === 'chunk',\n 'Module bundle must emit exactly one JavaScript chunk.',\n );\n const chunk = output[0];\n assert(\n chunk.imports.length === 0 && chunk.dynamicImports.length === 0,\n 'Module bundle has unresolved runtime imports.',\n );\n const sharedDependencies: ExtensionModuleBuildReport['sharedDependencies'] = [];\n for (const [name, installed] of selected) {\n const matches = [...loaded.values()].filter((input) => input.package.name === name);\n const roots = new Set(matches.map((input) => input.package.root));\n assert(\n roots.size <= 1 && [...roots].every((root) => root === installed.root),\n `Duplicate shared dependency in module graph: ${name}`,\n );\n if (name === 'yaml') {\n assert(\n [...loaded]\n .filter(([, input]) => input.package.name === name)\n .every(\n ([file]) =>\n within(path.join(installed.root, 'browser'), file) ||\n file === path.join(installed.root, 'package.json'),\n ),\n 'Shared yaml must use the browser entry exclusively; node/browser module mixing is unsupported.',\n );\n }\n sharedDependencies.push({\n package: name,\n version: installed.version,\n moduleCount: matches.length,\n copies: roots.size,\n });\n }\n const inputs = [...loaded].map(([file, input]) => ({\n package: input.package.name,\n version: input.package.version,\n file: path.relative(input.package.root, file).split(path.sep).join('/'),\n integrity: extensionIntegrity(input.contents),\n }));\n // Include manifests and nested type boundaries: they affect resolution and module interpretation.\n for (const [file, contents] of manifests) {\n const installed = await owner(file);\n inputs.push({\n package: installed.name,\n version: installed.version,\n file: path.relative(installed.root, file).split(path.sep).join('/'),\n integrity: extensionIntegrity(contents),\n });\n }\n inputs.sort((a, b) => compare(JSON.stringify(a), JSON.stringify(b)));\n const settings = {\n formatVersion: 1 as const,\n bundler: {name: 'rolldown' as const, version: VERSION},\n platform: 'browser' as const,\n target: 'es2020' as const,\n lock,\n members,\n inputs,\n sharedDependencies,\n };\n const report = {...settings, inputIntegrity: extensionIntegrity(JSON.stringify(settings))};\n const requirement = bundleUnsandboxedRequirement(effectiveComponents);\n const notice = sandboxedNotice(bundle, requirement);\n const guard = sandboxedGuardSource(requirement, notice);\n const code = chunk.code.replace(/^[\\t ]*\\/\\/#(?:end)?region[^\\r\\n]*(?:\\r?\\n|$)/gm, '');\n const capsule = bundle.recoveryCapsule\n ? runtime.split('\\n').find((line) => line.startsWith(`// ${extensionBundleRecoveryMarker}: `))\n : undefined;\n const contents = Buffer.from(\n `${bundleHeader(bundle, effectiveComponents)}// Module build inputs: ${report.inputIntegrity}\\n(function (Scratch) {\\n'use strict';\\nconst BUNDLE_ID = ${JSON.stringify(bundle.id)};\\nconst BUNDLE_NAME = ${JSON.stringify(bundle.name)};\\n${guard}\\n${code}\\n})(Scratch);\\n${capsule ? `${capsule}\\n` : ''}`,\n );\n return {contents, report};\n } finally {\n await build.close();\n }\n}\n\n/** Asynchronous opt-in layer; the synchronous classic API remains unchanged. */\nexport async function buildExtensionBundlesWithModules(\n input: BuildExtensionBundlesInput & {sourceDirectory: string},\n): Promise<BuildExtensionBundlesResult> {\n const moduleBuilds = new Map<string, ExtensionModuleBuild>();\n const extensions = new Map(input.extensions.map((extension) => [extension.id, extension]));\n for (const bundle of input.extensionBundles) {\n if (bundle.buildMode !== 'module') continue;\n const components = readBundleComponents(bundle, extensions, input.extensionContents);\n moduleBuilds.set(\n bundle.id,\n await compileExtensionModuleBundle(bundle, components, input.project, input.sourceDirectory),\n );\n }\n return buildExtensionBundles({...input, moduleBuilds});\n}\n"],"mappings":";;;;;;;;;AA2DA,SAAS,OAAO,MAAc,MAAuB;CACnD,MAAM,WAAW,KAAK,SAAS,MAAM,IAAI;CACzC,OACE,aAAa,MACZ,CAAC,SAAS,WAAW,KAAK,KAAK,KAAK,KAAK,aAAa,QAAQ,CAAC,KAAK,WAAW,QAAQ;AAE5F;AAEA,SAAS,QAAQ,MAAc,OAAuB;CACpD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD;AAEA,eAAe,eAAe,WAA+D;CAC3F,IAAI,UAAU,KAAK,QAAQ,SA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AO,kBACnB,QAAQ,MAAM,IAAI,CAAC,CAAC,MAAM,SAAS,KAAK,WAAW,MAAM,8BAA8B,GAAG,CAAC,IAC3F,KAAA;EAIJ,OAAO;GAAC,UAHS,OAAO,KACtB,GAAG,aAAa,QAAQ,mBAAmB,EAAE,0BAA0B,OAAO,eAAe,4DAA4D,KAAK,UAAU,OAAO,EAAE,EAAE,yBAAyB,KAAK,UAAU,OAAO,IAAI,EAAE,KAAK,MAAM,IAAI,KAAK,kBAAkB,UAAU,GAAG,QAAQ,MAAM,IAEnS;GAAU;EAAM;CAC1B,UAAU;EACR,MAAM,MAAM,MAAM;CACpB;AACF;;AAGA,eAAsB,iCACpB,OACsC;CACtC,MAAM,+BAAe,IAAI,IAAkC;CAC3D,MAAM,aAAa,IAAI,IAAI,MAAM,WAAW,KAAK,cAAc,CAAC,UAAU,IAAI,SAAS,CAAC,CAAC;CACzF,KAAK,MAAM,UAAU,MAAM,kBAAkB;EAC3C,IAAI,OAAO,cAAc,UAAU;EACnC,MAAM,aAAa,qBAAqB,QAAQ,YAAY,MAAM,iBAAiB;EACnF,aAAa,IACX,OAAO,IACP,MAAM,6BAA6B,QAAQ,YAAY,MAAM,SAAS,MAAM,eAAe,CAC7F;CACF;CACA,OAAO,sBAAsB;EAAC,GAAG;EAAO;CAAY,CAAC;AACvD"}
@@ -2,9 +2,9 @@ import { assert, errorMessage } from "./assert.js";
2
2
  import { assertNoInterruptedRollback, compareDirectories, pathExists, replaceDirectoryTransactionally } from "./output-safety.js";
3
3
  import { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestIntegrity, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
4
4
  import { extensionHeaderId, extensionIntegrity, validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
5
+ import { readNpmExtensionSource } from "./npm-extension-source.js";
5
6
  import { createDeterministicSb3, inspectSb3SourceForExtensionSync, validateSb3Source } from "./source.js";
6
7
  import { rewriteExtensionIdDocuments, validateNewExtensionId } from "./extension-id-migration.js";
7
- import { readNpmExtensionSource } from "./npm-extension-source.js";
8
8
  import path from "node:path";
9
9
  import { cp, lstat, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10
10
  //#region src/extension-sync.ts
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionEncoding, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types';
1
+ export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionEncoding, ExtensionModuleSource, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types';
2
2
  export { assert } from './assert';
3
3
  export { validateArchiveEntryName } from './archive';
4
4
  export { buildSb3 } from './build';
@@ -8,6 +8,8 @@ export { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, ext
8
8
  export { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions, } from './extension-bundle-configuration';
9
9
  export { planBundledSb3Unbundle, unbundleSb3 } from './extension-bundle-archive';
10
10
  export { buildExtensionBundles, createStaticExtensionBundle, bundleUnsandboxedRequirement, defaultSandboxedNotices, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations, } from './extension-bundle';
11
+ export { buildExtensionBundlesWithModules } from './extension-module-bundle';
12
+ export type { ExtensionModuleBuildReport } from './extension-module-bundle';
11
13
  export { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId, } from './extension-id-migration';
12
14
  export { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions, } from './extension-sync';
13
15
  export { decodeExtensionDataUrl, importSb3 } from './import';
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { validateArchiveEntryName } from "./archive.js";
4
4
  import { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, tryParseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
5
5
  import { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandboxedRequirement, unsandboxedRequirements, validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
6
6
  import { buildExtensionBundles, bundleUnsandboxedRequirement, createStaticExtensionBundle, defaultSandboxedNotices, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations } from "./extension-bundle.js";
7
+ import { buildExtensionBundlesWithModules } from "./extension-module-bundle.js";
7
8
  import { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion } from "./project-asset-additions.js";
8
9
  import { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from "./turbowarp-clean-up.js";
9
10
  import { createDeterministicSb3, fixedZipTimestamp, sourceFormatVersion, validateSb3Source } from "./source.js";
@@ -15,4 +16,4 @@ import { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleE
15
16
  import { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId } from "./extension-id-migration.js";
16
17
  import { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
17
18
  import { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate } from "./release-snapshot.js";
18
- export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
19
+ export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
@@ -10,4 +10,6 @@ export interface NpmExtensionSourceResult {
10
10
  packageDirectory: string;
11
11
  version: string;
12
12
  }
13
+ export declare function findPackageDirectory(sourceDirectory: string, packageName: string): Promise<string>;
14
+ export declare function readPackageArtifact(packageDirectory: string, artifact: string, maximumBytes: number, description: string): Promise<Buffer>;
13
15
  export declare function readNpmExtensionSource(extension: EmbeddedExtension, sourceDirectory: string, { allowVersionMismatch, maximumArtifactBytes, maximumManifestBytes, }: NpmExtensionSourceOptions): Promise<NpmExtensionSourceResult>;
@@ -58,6 +58,6 @@ async function readNpmExtensionSource(extension, sourceDirectory, { allowVersion
58
58
  };
59
59
  }
60
60
  //#endregion
61
- export { readNpmExtensionSource };
61
+ export { findPackageDirectory, readNpmExtensionSource, readPackageArtifact };
62
62
 
63
63
  //# sourceMappingURL=npm-extension-source.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"npm-extension-source.js","names":[],"sources":["../src/npm-extension-source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {lstat, readFile, realpath} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert, errorMessage} from './assert';\nimport {validateExtensionApiManifestSourceMetadata} from './extension-api-manifest';\nimport {extensionHeaderId, validateExtensionSourceMetadata} from './extension-dependencies';\nimport type {EmbeddedExtension} from './types';\n\nexport interface NpmExtensionSourceOptions {\n allowVersionMismatch?: boolean;\n maximumArtifactBytes: number;\n maximumManifestBytes: number;\n}\n\nexport interface NpmExtensionSourceResult {\n apiManifestContents: Buffer | null;\n contents: Buffer;\n packageDirectory: string;\n version: string;\n}\n\nfunction packageSegments(packageName: string): string[] {\n return packageName.startsWith('@') ? packageName.split('/') : [packageName];\n}\n\nasync function findPackageDirectory(sourceDirectory: string, packageName: string): Promise<string> {\n let current = path.resolve(sourceDirectory);\n while (true) {\n const candidate = path.join(current, 'node_modules', ...packageSegments(packageName));\n try {\n await lstat(path.join(candidate, 'package.json'));\n return candidate;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n throw new Error(\n `Installed npm package was not found for managed extension: ${packageName}. Run the project's package manager install command.`,\n );\n}\n\nasync function readPackageArtifact(\n packageDirectory: string,\n artifact: string,\n maximumBytes: number,\n description: string,\n): Promise<Buffer> {\n const [resolvedPackageDirectory, resolvedArtifact] = await Promise.all([\n realpath(packageDirectory),\n realpath(path.join(packageDirectory, ...artifact.split('/'))),\n ]);\n const relativeArtifact = path.relative(resolvedPackageDirectory, resolvedArtifact);\n assert(\n relativeArtifact !== '' &&\n relativeArtifact !== '..' &&\n !relativeArtifact.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativeArtifact),\n `${description} resolves outside its npm package: ${artifact}`,\n );\n const stats = await lstat(resolvedArtifact);\n assert(stats.isFile(), `${description} must be a regular file: ${artifact}`);\n assert(stats.size <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);\n return readFile(resolvedArtifact);\n}\n\nexport async function readNpmExtensionSource(\n extension: EmbeddedExtension,\n sourceDirectory: string,\n {\n allowVersionMismatch = false,\n maximumArtifactBytes,\n maximumManifestBytes,\n }: NpmExtensionSourceOptions,\n): Promise<NpmExtensionSourceResult> {\n const source = validateExtensionSourceMetadata(extension);\n assert(source?.provider === 'npm', `Extension is not managed by npm: ${extension.id}`);\n const packageDirectory = await findPackageDirectory(sourceDirectory, source.package);\n let packageManifest: {name?: unknown; version?: unknown};\n try {\n packageManifest = JSON.parse(\n await readFile(path.join(packageDirectory, 'package.json'), 'utf8'),\n );\n } catch (error) {\n throw new Error(\n `Invalid package.json for npm extension ${extension.id}: ${errorMessage(error)}`,\n {\n cause: error,\n },\n );\n }\n assert(\n packageManifest?.name === source.package,\n `npm package name mismatch for extension ${extension.id}: expected ${source.package}, got ${packageManifest?.name ?? '(missing)'}`,\n );\n assert(\n typeof packageManifest.version === 'string' &&\n /^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/u.test(\n packageManifest.version,\n ),\n `npm package has an invalid semantic version for extension ${extension.id}: ${packageManifest?.version ?? '(missing)'}`,\n );\n if (!allowVersionMismatch) {\n assert(\n packageManifest.version === source.version,\n `npm package version mismatch for extension ${extension.id}: expected ${source.version}, got ${packageManifest?.version ?? '(missing)'}`,\n );\n }\n const contents = await readPackageArtifact(\n packageDirectory,\n source.artifact,\n maximumArtifactBytes,\n `npm extension artifact for ${extension.id}`,\n );\n const actualId = extensionHeaderId(contents);\n assert(\n actualId === extension.id,\n `npm extension header ID mismatch for ${extension.id}: expected ${extension.id}, got ${actualId ?? '(missing)'}`,\n );\n const apiMetadata = validateExtensionApiManifestSourceMetadata(extension);\n const apiManifestContents = apiMetadata\n ? await readPackageArtifact(\n packageDirectory,\n apiMetadata.artifact,\n maximumManifestBytes,\n `npm extension API manifest for ${extension.id}`,\n )\n : null;\n return {\n apiManifestContents,\n contents,\n packageDirectory,\n version: packageManifest.version as string,\n };\n}\n"],"mappings":";;;;;;AAuBA,SAAS,gBAAgB,aAA+B;CACtD,OAAO,YAAY,WAAW,GAAG,IAAI,YAAY,MAAM,GAAG,IAAI,CAAC,WAAW;AAC5E;AAEA,eAAe,qBAAqB,iBAAyB,aAAsC;CACjG,IAAI,UAAU,KAAK,QAAQ,eAAe;CAC1C,OAAO,MAAM;EACX,MAAM,YAAY,KAAK,KAAK,SAAS,gBAAgB,GAAG,gBAAgB,WAAW,CAAC;EACpF,IAAI;GACF,MAAM,MAAM,KAAK,KAAK,WAAW,cAAc,CAAC;GAChD,OAAO;EACT,SAAS,OAAO;GACd,MAAM,OAAQ,OAAwC;GACtD,IAAI,SAAS,YAAY,SAAS,WAAW,MAAM;EACrD;EACA,MAAM,SAAS,KAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SAAS;EACxB,UAAU;CACZ;CACA,MAAM,IAAI,MACR,8DAA8D,YAAY,qDAC5E;AACF;AAEA,eAAe,oBACb,kBACA,UACA,cACA,aACiB;CACjB,MAAM,CAAC,0BAA0B,oBAAoB,MAAM,QAAQ,IAAI,CACrE,SAAS,gBAAgB,GACzB,SAAS,KAAK,KAAK,kBAAkB,GAAG,SAAS,MAAM,GAAG,CAAC,CAAC,CAC9D,CAAC;CACD,MAAM,mBAAmB,KAAK,SAAS,0BAA0B,gBAAgB;CACjF,OACE,qBAAqB,MACnB,qBAAqB,QACrB,CAAC,iBAAiB,WAAW,KAAK,KAAK,KAAK,KAC5C,CAAC,KAAK,WAAW,gBAAgB,GACnC,GAAG,YAAY,qCAAqC,UACtD;CACA,MAAM,QAAQ,MAAM,MAAM,gBAAgB;CAC1C,OAAO,MAAM,OAAO,GAAG,GAAG,YAAY,2BAA2B,UAAU;CAC3E,OAAO,MAAM,QAAQ,cA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],"sources":["../src/npm-extension-source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {lstat, readFile, realpath} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert, errorMessage} from './assert';\nimport {validateExtensionApiManifestSourceMetadata} from './extension-api-manifest';\nimport {extensionHeaderId, validateExtensionSourceMetadata} from './extension-dependencies';\nimport type {EmbeddedExtension} from './types';\n\nexport interface NpmExtensionSourceOptions {\n allowVersionMismatch?: boolean;\n maximumArtifactBytes: number;\n maximumManifestBytes: number;\n}\n\nexport interface NpmExtensionSourceResult {\n apiManifestContents: Buffer | null;\n contents: Buffer;\n packageDirectory: string;\n version: string;\n}\n\nfunction packageSegments(packageName: string): string[] {\n return packageName.startsWith('@') ? packageName.split('/') : [packageName];\n}\n\nexport async function findPackageDirectory(\n sourceDirectory: string,\n packageName: string,\n): Promise<string> {\n let current = path.resolve(sourceDirectory);\n while (true) {\n const candidate = path.join(current, 'node_modules', ...packageSegments(packageName));\n try {\n await lstat(path.join(candidate, 'package.json'));\n return candidate;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n throw new Error(\n `Installed npm package was not found for managed extension: ${packageName}. Run the project's package manager install command.`,\n );\n}\n\nexport async function readPackageArtifact(\n packageDirectory: string,\n artifact: string,\n maximumBytes: number,\n description: string,\n): Promise<Buffer> {\n const [resolvedPackageDirectory, resolvedArtifact] = await Promise.all([\n realpath(packageDirectory),\n realpath(path.join(packageDirectory, ...artifact.split('/'))),\n ]);\n const relativeArtifact = path.relative(resolvedPackageDirectory, resolvedArtifact);\n assert(\n relativeArtifact !== '' &&\n relativeArtifact !== '..' &&\n !relativeArtifact.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativeArtifact),\n `${description} resolves outside its npm package: ${artifact}`,\n );\n const stats = await lstat(resolvedArtifact);\n assert(stats.isFile(), `${description} must be a regular file: ${artifact}`);\n assert(stats.size <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);\n return readFile(resolvedArtifact);\n}\n\nexport async function readNpmExtensionSource(\n extension: EmbeddedExtension,\n sourceDirectory: string,\n {\n allowVersionMismatch = false,\n maximumArtifactBytes,\n maximumManifestBytes,\n }: NpmExtensionSourceOptions,\n): Promise<NpmExtensionSourceResult> {\n const source = validateExtensionSourceMetadata(extension);\n assert(source?.provider === 'npm', `Extension is not managed by npm: ${extension.id}`);\n const packageDirectory = await findPackageDirectory(sourceDirectory, source.package);\n let packageManifest: {name?: unknown; version?: unknown};\n try {\n packageManifest = JSON.parse(\n await readFile(path.join(packageDirectory, 'package.json'), 'utf8'),\n );\n } catch (error) {\n throw new Error(\n `Invalid package.json for npm extension ${extension.id}: ${errorMessage(error)}`,\n {\n cause: error,\n },\n );\n }\n assert(\n packageManifest?.name === source.package,\n `npm package name mismatch for extension ${extension.id}: expected ${source.package}, got ${packageManifest?.name ?? '(missing)'}`,\n );\n assert(\n typeof packageManifest.version === 'string' &&\n /^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/u.test(\n packageManifest.version,\n ),\n `npm package has an invalid semantic version for extension ${extension.id}: ${packageManifest?.version ?? '(missing)'}`,\n );\n if (!allowVersionMismatch) {\n assert(\n packageManifest.version === source.version,\n `npm package version mismatch for extension ${extension.id}: expected ${source.version}, got ${packageManifest?.version ?? '(missing)'}`,\n );\n }\n const contents = await readPackageArtifact(\n packageDirectory,\n source.artifact,\n maximumArtifactBytes,\n `npm extension artifact for ${extension.id}`,\n );\n const actualId = extensionHeaderId(contents);\n assert(\n actualId === extension.id,\n `npm extension header ID mismatch for ${extension.id}: expected ${extension.id}, got ${actualId ?? '(missing)'}`,\n );\n const apiMetadata = validateExtensionApiManifestSourceMetadata(extension);\n const apiManifestContents = apiMetadata\n ? await readPackageArtifact(\n packageDirectory,\n apiMetadata.artifact,\n maximumManifestBytes,\n `npm extension API manifest for ${extension.id}`,\n )\n : null;\n return {\n apiManifestContents,\n contents,\n packageDirectory,\n version: packageManifest.version as string,\n };\n}\n"],"mappings":";;;;;;AAuBA,SAAS,gBAAgB,aAA+B;CACtD,OAAO,YAAY,WAAW,GAAG,IAAI,YAAY,MAAM,GAAG,IAAI,CAAC,WAAW;AAC5E;AAEA,eAAsB,qBACpB,iBACA,aACiB;CACjB,IAAI,UAAU,KAAK,QAAQ,eAAe;CAC1C,OAAO,MAAM;EACX,MAAM,YAAY,KAAK,KAAK,SAAS,gBAAgB,GAAG,gBAAgB,WAAW,CAAC;EACpF,IAAI;GACF,MAAM,MAAM,KAAK,KAAK,WAAW,cAAc,CAAC;GAChD,OAAO;EACT,SAAS,OAAO;GACd,MAAM,OAAQ,OAAwC;GACtD,IAAI,SAAS,YAAY,SAAS,WAAW,MAAM;EACrD;EACA,MAAM,SAAS,KAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SAAS;EACxB,UAAU;CACZ;CACA,MAAM,IAAI,MACR,8DAA8D,YAAY,qDAC5E;AACF;AAEA,eAAsB,oBACpB,kBACA,UACA,cACA,aACiB;CACjB,MAAM,CAAC,0BAA0B,oBAAoB,MAAM,QAAQ,IAAI,CACrE,SAAS,gBAAgB,GACzB,SAAS,KAAK,KAAK,kBAAkB,GAAG,SAAS,MAAM,GAAG,CAAC,CAAC,CAC9D,CAAC;CACD,MAAM,mBAAmB,KAAK,SAAS,0BAA0B,gBAAgB;CACjF,OACE,qBAAqB,MACnB,qBAAqB,QACrB,CAAC,iBAAiB,WAAW,KAAK,KAAK,KAAK,KAC5C,CAAC,KAAK,WAAW,gBAAgB,GACnC,GAAG,YAAY,qCAAqC,UACtD;CACA,MAAM,QAAQ,MAAM,MAAM,gBAAgB;CAC1C,OAAO,MAAM,OAAO,GAAG,GAAG,YAAY,2BAA2B,UAAU;CAC3E,OAAO,MAAM,QAAQ,cAAc,GAAG,YAAY,eAAe,aAAa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
2
2
  import { validateArchiveEntryName } from "./archive.js";
3
3
  import { validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
4
4
  import { validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
5
- import { buildExtensionBundles, validateExtensionBundleConfigurations } from "./extension-bundle.js";
5
+ import { validateExtensionBundleConfigurations } from "./extension-bundle.js";
6
+ import { buildExtensionBundlesWithModules } from "./extension-module-bundle.js";
6
7
  import { applyProjectAssetAdditions } from "./project-asset-additions.js";
7
8
  import { cleanUpTurboWarpBlocks } from "./turbowarp-clean-up.js";
8
9
  import path from "node:path";
@@ -199,7 +200,8 @@ async function inspectSb3SourceForExtensionSync(sourceDirectory) {
199
200
  }
200
201
  async function validateSb3Source(sourceDirectory) {
201
202
  const source = await inspectSb3Source(sourceDirectory, true);
202
- buildExtensionBundles({
203
+ await buildExtensionBundlesWithModules({
204
+ sourceDirectory: source.resolvedSourceDirectory,
203
205
  extensionBundles: source.extensionBundles,
204
206
  extensionContents: source.extensionContents,
205
207
  extensions: source.extensions,
@@ -212,7 +214,7 @@ async function createDeterministicSb3(sourceDirectory, options = {}) {
212
214
  assert(typeof cleanUpBlocks === "boolean", "cleanUpBlocks must be a boolean.");
213
215
  assert(Array.isArray(allowedAssetRoots), "allowedAssetRoots must be an array.");
214
216
  assert(projectAssetsPath === void 0 || typeof projectAssetsPath === "string", "projectAssetsPath must be a string when provided.");
215
- const source = await validateSb3Source(sourceDirectory);
217
+ const source = await inspectSb3Source(sourceDirectory, true);
216
218
  const projectAssets = projectAssetsPath ? await applyProjectAssetAdditions({
217
219
  allowedAssetRoots,
218
220
  assetContents: source.assetContents,
@@ -226,7 +228,8 @@ async function createDeterministicSb3(sourceDirectory, options = {}) {
226
228
  project: source.project,
227
229
  summary: null
228
230
  };
229
- const bundled = buildExtensionBundles({
231
+ const bundled = await buildExtensionBundlesWithModules({
232
+ sourceDirectory: source.resolvedSourceDirectory,
230
233
  extensionBundles: source.extensionBundles,
231
234
  extensionContents: source.extensionContents,
232
235
  extensions: source.extensions,
@@ -1 +1 @@
1
- {"version":3,"file":"source.js","names":[],"sources":["../src/source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readdir, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strToU8, zipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {buildExtensionBundles, validateExtensionBundleConfigurations} from './extension-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {applyProjectAssetAdditions} from './project-asset-additions';\nimport type {ProjectAssetAdditionsSummary} from './project-asset-additions';\nimport {cleanUpTurboWarpBlocks} from './turbowarp-clean-up';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectAssetReference,\n ProjectJson,\n Sb3SourceManifest,\n UnknownRecord,\n} from './types';\n\nexport const sourceFormatVersion = 1;\nexport const fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);\n\nexport interface InspectedSb3Source {\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n extensions: EmbeddedExtension[];\n extensionApiManifestContents: Map<string, Uint8Array>;\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n project: ProjectJson;\n resolvedSourceDirectory: string;\n sourceManifest: Sb3SourceManifest;\n}\n\nexport interface BlockCleanUpSummary {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n targetCount: number;\n}\n\nexport interface DeterministicSb3Options {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n projectAssetsPath?: string;\n}\n\nexport interface DeterministicSb3 {\n archive: Uint8Array;\n assetCount: number;\n assetReferenceCount: number;\n blockCleanUp: BlockCleanUpSummary | null;\n bundlePlans: ExtensionBundlePlan[];\n embeddedExtensionCount: number;\n entryCount: number;\n projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;\n source: InspectedSb3Source;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readJson(filePath: string, description: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, {\n cause: error,\n });\n }\n}\n\nasync function assertDirectory(directoryPath: string, description: string): Promise<void> {\n const stats = await lstat(directoryPath);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `${description} must be a directory, not a file or symbolic link: ${directoryPath}`,\n );\n}\n\nasync function listRegularFiles(rootDirectory: string, description: string): Promise<string[]> {\n await assertDirectory(rootDirectory, description);\n const files: string[] = [];\n\n async function visit(directory: string, relativeDirectory: string): Promise<void> {\n const entries = await readdir(directory, {withFileTypes: true});\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? path.posix.join(relativeDirectory, entry.name)\n : entry.name;\n const absolutePath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n await visit(absolutePath, relativePath);\n } else {\n assert(\n entry.isFile(),\n `${description} contains a symbolic link or unsupported entry: ${relativePath}`,\n );\n files.push(relativePath);\n }\n }\n }\n\n await visit(rootDirectory, '');\n return files;\n}\n\nfunction assertSameFileSet(\n actualFiles: string[],\n expectedFiles: string[],\n description: string,\n): void {\n const actual = new Set(actualFiles);\n const expected = new Set(expectedFiles);\n const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();\n const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();\n assert(\n missing.length === 0 && extra.length === 0,\n `${description} does not match its manifest. Missing: ${missing.join(', ') || '(none)'}. ` +\n `Extra: ${extra.join(', ') || '(none)'}.`,\n );\n}\n\nfunction md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\n}\n\nfunction validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest {\n assert(isObject(manifest), 'sb3-source.json must contain an object.');\n assert(\n manifest.formatVersion === sourceFormatVersion,\n `Unsupported SB3 source format version: ${manifest.formatVersion}`,\n );\n assert(\n manifest.project === 'project.source.json',\n 'SB3 source format 1 requires project.source.json.',\n );\n assert(\n manifest.embeddedExtensions === 'embedded-extensions.json',\n 'SB3 source format 1 requires embedded-extensions.json.',\n );\n assert(\n manifest.assetsDirectory === 'assets',\n 'SB3 source format 1 requires the assets directory.',\n );\n assert(\n Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0,\n 'sb3-source.json archiveEntries must be a non-empty array.',\n );\n\n const seenEntries = new Set<string>();\n let projectEntryCount = 0;\n for (const rawEntryName of manifest.archiveEntries as unknown[]) {\n const entryName = validateArchiveEntryName(rawEntryName);\n assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);\n assert(\n !entryName.endsWith('/'),\n `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`,\n );\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`,\n );\n seenEntries.add(entryName);\n if (entryName === 'project.json') {\n projectEntryCount += 1;\n }\n }\n assert(projectEntryCount === 1, 'archiveEntries must contain project.json exactly once.');\n}\n\nfunction validateExtensionManifest(\n extensionManifest: unknown,\n project: ProjectJson,\n extensionFiles: string[],\n): {extensionBundles: ExtensionBundleConfiguration[]; extensions: EmbeddedExtension[]} {\n assert(isObject(extensionManifest), 'embedded-extensions.json must contain an object.');\n assert(\n extensionManifest.formatVersion === sourceFormatVersion,\n `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`,\n );\n assert(\n Array.isArray(extensionManifest.extensions),\n 'embedded-extensions.json extensions must be an array.',\n );\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n assert(\n isObject(extensionUrls),\n 'project.source.json extensionURLs must be an object when present.',\n );\n const extensionsById = new Map<string, EmbeddedExtension>();\n const expectedFiles: string[] = [];\n const extensions: EmbeddedExtension[] = [];\n\n for (const entry of extensionManifest.extensions as unknown[]) {\n assert(isObject(entry), 'Each embedded extension manifest entry must be an object.');\n const extension = entry as unknown as EmbeddedExtension;\n assert(\n typeof extension.id === 'string' && /^[A-Za-z0-9._-]+$/u.test(extension.id),\n `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`,\n );\n assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);\n const expectedPath = `extensions/${extension.id}.js`;\n assert(\n extension.path === expectedPath,\n `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`,\n );\n assert(\n typeof extension.mediaType === 'string' &&\n extension.mediaType.length > 0 &&\n !/[;,\\r\\n]/u.test(extension.mediaType),\n `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`,\n );\n assert(\n Array.isArray(extension.parameters) &&\n extension.parameters.every(\n (parameter) =>\n typeof parameter === 'string' && parameter.length > 0 && !/[;,\\r\\n]/u.test(parameter),\n ),\n `Invalid data URL parameters for embedded extension ${extension.id}.`,\n );\n assert(\n extension.encoding === 'base64' || extension.encoding === 'percent',\n `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`,\n );\n assert(\n extensionUrls[extension.id] === `embedded-extension:${extension.path}`,\n `project.source.json mapping does not match embedded extension ${extension.id}.`,\n );\n validateExtensionSourceMetadata(extension);\n extensionsById.set(extension.id, extension);\n extensions.push(extension);\n expectedFiles.push(`${extension.id}.js`);\n if (extension.source?.apiManifest) {\n expectedFiles.push(path.posix.relative('extensions', extension.source.apiManifest.path));\n }\n }\n\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n assert(\n typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:'),\n `project.source.json still contains an embedded data URL: ${extensionId}`,\n );\n if (typeof extensionUrl === 'string' && extensionUrl.startsWith('embedded-extension:')) {\n assert(\n extensionsById.has(extensionId),\n `project.source.json has no metadata for embedded extension ${extensionId}.`,\n );\n }\n }\n\n assertSameFileSet(extensionFiles, expectedFiles, 'Embedded extension files');\n return {\n extensionBundles: validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensions,\n ),\n extensions,\n };\n}\n\nfunction collectAssetReferences(\n project: ProjectJson,\n): {asset: ProjectAssetReference; description: string}[] {\n assert(Array.isArray(project.targets), 'project.source.json targets must be an array.');\n const references: {asset: ProjectAssetReference; description: string}[] = [];\n for (const [targetIndex, target] of (project.targets as unknown[]).entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n for (const [collectionName, kind] of [\n ['costumes', 'costume'],\n ['sounds', 'sound'],\n ] as const) {\n const assets: unknown = target[collectionName] ?? [];\n assert(\n Array.isArray(assets),\n `Project target ${targetIndex} ${collectionName} must be an array.`,\n );\n for (const [assetIndex, asset] of (assets as unknown[]).entries()) {\n assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);\n references.push({asset, description: `${kind} ${targetIndex}:${assetIndex}`});\n }\n }\n }\n return references;\n}\n\nfunction percentEncode(contents: Uint8Array): string {\n return [...contents]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction encodeExtensionDataUrl(extension: EmbeddedExtension, contents: Uint8Array): string {\n const metadata = [extension.mediaType, ...extension.parameters].join(';');\n if (extension.encoding === 'base64') {\n return `data:${metadata};base64,${Buffer.from(contents).toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(contents)}`;\n}\n\nasync function inspectSb3Source(\n sourceDirectory: string,\n validateManagedExtensions: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n await assertDirectory(resolvedSourceDirectory, 'SB3 source');\n const sourceManifest = await readJson(\n path.join(resolvedSourceDirectory, 'sb3-source.json'),\n 'SB3 source manifest',\n );\n validateSourceManifest(sourceManifest);\n const assetEntries = sourceManifest.archiveEntries.filter(\n (entryName) => entryName !== 'project.json',\n );\n const project: unknown = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.project),\n 'SB3 project source',\n );\n assert(isObject(project), 'project.source.json must contain an object.');\n const extensionManifest = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions),\n 'Embedded extension manifest',\n );\n\n const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);\n const extensionsDirectory = path.join(resolvedSourceDirectory, 'extensions');\n const [assetFiles, extensionFiles] = await Promise.all([\n listRegularFiles(assetsDirectory, 'Assets directory'),\n listRegularFiles(extensionsDirectory, 'Extensions directory'),\n ]);\n assertSameFileSet(assetFiles, assetEntries, 'Asset files');\n const {extensionBundles, extensions} = validateExtensionManifest(\n extensionManifest,\n project,\n extensionFiles,\n );\n\n const assetContents = new Map<string, Uint8Array>();\n await Promise.all(\n assetFiles.map(async (assetPath) => {\n assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));\n }),\n );\n const referencedAssets = new Set<string>();\n const references = collectAssetReferences(project);\n for (const {asset, description} of references) {\n assert(\n typeof asset.assetId === 'string' && /^[a-f0-9]{32}$/u.test(asset.assetId),\n `Invalid assetId for ${description}: ${asset.assetId}`,\n );\n assert(\n typeof asset.dataFormat === 'string' && /^[A-Za-z0-9]+$/u.test(asset.dataFormat),\n `Invalid dataFormat for ${description}: ${asset.dataFormat}`,\n );\n const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;\n assert(\n asset.md5ext === expectedFilename,\n `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`,\n );\n const contents = assetContents.get(expectedFilename);\n assert(contents, `Referenced asset is missing for ${description}: ${expectedFilename}`);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === asset.assetId,\n `Asset content hash mismatch for ${description}: expected ${asset.assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(expectedFilename);\n }\n const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));\n assert(\n unreferencedAssets.length === 0,\n `Asset manifest contains unreferenced files: ${unreferencedAssets.join(', ')}`,\n );\n\n const extensionContents = new Map<string, Uint8Array>();\n const extensionApiManifestContents = new Map<string, Uint8Array>();\n await Promise.all(\n extensions.map(async (extension) => {\n const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));\n if (validateManagedExtensions) {\n validateManagedExtensionContents(extension, contents);\n }\n extensionContents.set(extension.id, contents);\n if (extension.source?.apiManifest) {\n const apiManifestContents = await readFile(\n path.join(resolvedSourceDirectory, extension.source.apiManifest.path),\n );\n if (validateManagedExtensions) {\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n extensionApiManifestContents.set(extension.id, apiManifestContents);\n }\n }),\n );\n\n return {\n assetContents,\n assetReferenceCount: references.length,\n extensions,\n extensionApiManifestContents,\n extensionBundles,\n extensionContents,\n project,\n resolvedSourceDirectory,\n sourceManifest,\n };\n}\n\nexport async function inspectSb3SourceForExtensionSync(\n sourceDirectory: string,\n): Promise<InspectedSb3Source> {\n return inspectSb3Source(sourceDirectory, false);\n}\n\nexport async function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source> {\n const source = await inspectSb3Source(sourceDirectory, true);\n buildExtensionBundles({\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n return source;\n}\n\nexport async function createDeterministicSb3(\n sourceDirectory: string,\n options: DeterministicSb3Options = {},\n): Promise<DeterministicSb3> {\n const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;\n assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');\n assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');\n assert(\n projectAssetsPath === undefined || typeof projectAssetsPath === 'string',\n 'projectAssetsPath must be a string when provided.',\n );\n const source = await validateSb3Source(sourceDirectory);\n const projectAssets: {\n archiveEntries: string[];\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n project: ProjectJson;\n summary: Readonly<ProjectAssetAdditionsSummary> | null;\n } = projectAssetsPath\n ? await applyProjectAssetAdditions({\n allowedAssetRoots,\n assetContents: source.assetContents,\n archiveEntries: source.sourceManifest.archiveEntries,\n manifestPath: projectAssetsPath,\n project: source.project,\n })\n : {\n archiveEntries: source.sourceManifest.archiveEntries,\n assetContents: source.assetContents,\n assetReferenceCount: 0,\n project: source.project,\n summary: null,\n };\n const bundled = buildExtensionBundles({\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: projectAssets.project,\n });\n let project = structuredClone(bundled.project);\n let blockCleanUp: BlockCleanUpSummary | null = null;\n if (cleanUpBlocks) {\n const cleaned = cleanUpTurboWarpBlocks(project);\n project = cleaned.project;\n blockCleanUp = {\n movedCommentCount: cleaned.movedCommentCount,\n movedScriptCount: cleaned.movedScriptCount,\n scriptCount: cleaned.scriptCount,\n targetCount: cleaned.targetCount,\n };\n }\n const extensionUrls: Record<string, unknown> = project.extensionURLs ?? {};\n for (const extension of bundled.extensions) {\n const contents = bundled.extensionContents.get(extension.id);\n assert(contents, `Embedded extension has no contents: ${extension.id}`);\n extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);\n }\n project.extensionURLs = extensionUrls;\n\n const archiveEntries: Record<string, Uint8Array> = {};\n for (const entryName of projectAssets.archiveEntries) {\n if (entryName === 'project.json') {\n archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\\n`);\n continue;\n }\n const contents = projectAssets.assetContents.get(entryName);\n assert(contents, `Archive entry has no contents: ${entryName}`);\n archiveEntries[entryName] = contents;\n }\n const archive = zipSync(archiveEntries, {\n level: 6,\n mtime: fixedZipTimestamp,\n });\n\n return {\n archive,\n assetCount: projectAssets.assetContents.size,\n assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,\n blockCleanUp,\n bundlePlans: bundled.bundlePlans,\n embeddedExtensionCount: bundled.ext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M,UAAU,sBAAsB;EACpC,kBAAkB,OAAO;EACzB,mBAAmB,OAAO;EAC1B,YAAY,OAAO;EACnB,SAAS,cAAc;CACzB,CAAC;CACD,IAAI,UAAU,gBAAgB,QAAQ,OAAO;CAC7C,IAAI,eAA2C;CAC/C,IAAI,eAAe;EACjB,MAAM,UAAU,uBAAuB,OAAO;EAC9C,UAAU,QAAQ;EAClB,eAAe;GACb,mBAAmB,QAAQ;GAC3B,kBAAkB,QAAQ;GAC1B,aAAa,QAAQ;GACrB,aAAa,QAAQ;EACvB;CACF;CACA,MAAM,gBAAyC,QAAQ,iBAAiB,CAAC;CACzE,KAAK,MAAM,aAAa,QAAQ,YAAY;EAC1C,MAAM,WAAW,QAAQ,kBAAkB,IAAI,UAAU,EAAE;EAC3D,OAAO,UAAU,uCAAuC,UAAU,IAAI;EACtE,cAAc,UAAU,MAAM,uBAAuB,WAAW,QAAQ;CAC1E;CACA,QAAQ,gBAAgB;CAExB,MAAM,iBAA6C,CAAC;CACpD,KAAK,MAAM,aAAa,cAAc,gBAAgB;EACpD,IAAI,cAAc,gBAAgB;GAChC,eAAe,aAAa,QAAQ,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG;GAClE;EACF;EACA,MAAM,WAAW,cAAc,cAAc,IAAI,SAAS;EAC1D,OAAO,UAAU,kCAAkC,WAAW;EAC9D,eAAe,aAAa;CAC9B;CAMA,OAAO;EACL,SANc,QAAQ,gBAAgB;GACtC,OAAO;GACP,OAAO;EACT,CAGE;EACA,YAAY,cAAc,cAAc;EACxC,qBAAqB,OAAO,sBAAsB,cAAc;EAChE;EACA,aAAa,QAAQ;EACrB,wBAAwB,QAAQ,WAAW;EAC3C,YAAY,cAAc,eAAe;EACzC,uBAAuB,cAAc;EACrC;CACF;AACF"}
1
+ {"version":3,"file":"source.js","names":[],"sources":["../src/source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readdir, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strToU8, zipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateExtensionBundleConfigurations} from './extension-bundle';\nimport {buildExtensionBundlesWithModules} from './extension-module-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {applyProjectAssetAdditions} from './project-asset-additions';\nimport type {ProjectAssetAdditionsSummary} from './project-asset-additions';\nimport {cleanUpTurboWarpBlocks} from './turbowarp-clean-up';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectAssetReference,\n ProjectJson,\n Sb3SourceManifest,\n UnknownRecord,\n} from './types';\n\nexport const sourceFormatVersion = 1;\nexport const fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);\n\nexport interface InspectedSb3Source {\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n extensions: EmbeddedExtension[];\n extensionApiManifestContents: Map<string, Uint8Array>;\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n project: ProjectJson;\n resolvedSourceDirectory: string;\n sourceManifest: Sb3SourceManifest;\n}\n\nexport interface BlockCleanUpSummary {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n targetCount: number;\n}\n\nexport interface DeterministicSb3Options {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n projectAssetsPath?: string;\n}\n\nexport interface DeterministicSb3 {\n archive: Uint8Array;\n assetCount: number;\n assetReferenceCount: number;\n blockCleanUp: BlockCleanUpSummary | null;\n bundlePlans: ExtensionBundlePlan[];\n embeddedExtensionCount: number;\n entryCount: number;\n projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;\n source: InspectedSb3Source;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readJson(filePath: string, description: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, {\n cause: error,\n });\n }\n}\n\nasync function assertDirectory(directoryPath: string, description: string): Promise<void> {\n const stats = await lstat(directoryPath);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `${description} must be a directory, not a file or symbolic link: ${directoryPath}`,\n );\n}\n\nasync function listRegularFiles(rootDirectory: string, description: string): Promise<string[]> {\n await assertDirectory(rootDirectory, description);\n const files: string[] = [];\n\n async function visit(directory: string, relativeDirectory: string): Promise<void> {\n const entries = await readdir(directory, {withFileTypes: true});\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? path.posix.join(relativeDirectory, entry.name)\n : entry.name;\n const absolutePath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n await visit(absolutePath, relativePath);\n } else {\n assert(\n entry.isFile(),\n `${description} contains a symbolic link or unsupported entry: ${relativePath}`,\n );\n files.push(relativePath);\n }\n }\n }\n\n await visit(rootDirectory, '');\n return files;\n}\n\nfunction assertSameFileSet(\n actualFiles: string[],\n expectedFiles: string[],\n description: string,\n): void {\n const actual = new Set(actualFiles);\n const expected = new Set(expectedFiles);\n const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();\n const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();\n assert(\n missing.length === 0 && extra.length === 0,\n `${description} does not match its manifest. Missing: ${missing.join(', ') || '(none)'}. ` +\n `Extra: ${extra.join(', ') || '(none)'}.`,\n );\n}\n\nfunction md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\n}\n\nfunction validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest {\n assert(isObject(manifest), 'sb3-source.json must contain an object.');\n assert(\n manifest.formatVersion === sourceFormatVersion,\n `Unsupported SB3 source format version: ${manifest.formatVersion}`,\n );\n assert(\n manifest.project === 'project.source.json',\n 'SB3 source format 1 requires project.source.json.',\n );\n assert(\n manifest.embeddedExtensions === 'embedded-extensions.json',\n 'SB3 source format 1 requires embedded-extensions.json.',\n );\n assert(\n manifest.assetsDirectory === 'assets',\n 'SB3 source format 1 requires the assets directory.',\n );\n assert(\n Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0,\n 'sb3-source.json archiveEntries must be a non-empty array.',\n );\n\n const seenEntries = new Set<string>();\n let projectEntryCount = 0;\n for (const rawEntryName of manifest.archiveEntries as unknown[]) {\n const entryName = validateArchiveEntryName(rawEntryName);\n assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);\n assert(\n !entryName.endsWith('/'),\n `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`,\n );\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`,\n );\n seenEntries.add(entryName);\n if (entryName === 'project.json') {\n projectEntryCount += 1;\n }\n }\n assert(projectEntryCount === 1, 'archiveEntries must contain project.json exactly once.');\n}\n\nfunction validateExtensionManifest(\n extensionManifest: unknown,\n project: ProjectJson,\n extensionFiles: string[],\n): {extensionBundles: ExtensionBundleConfiguration[]; extensions: EmbeddedExtension[]} {\n assert(isObject(extensionManifest), 'embedded-extensions.json must contain an object.');\n assert(\n extensionManifest.formatVersion === sourceFormatVersion,\n `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`,\n );\n assert(\n Array.isArray(extensionManifest.extensions),\n 'embedded-extensions.json extensions must be an array.',\n );\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n assert(\n isObject(extensionUrls),\n 'project.source.json extensionURLs must be an object when present.',\n );\n const extensionsById = new Map<string, EmbeddedExtension>();\n const expectedFiles: string[] = [];\n const extensions: EmbeddedExtension[] = [];\n\n for (const entry of extensionManifest.extensions as unknown[]) {\n assert(isObject(entry), 'Each embedded extension manifest entry must be an object.');\n const extension = entry as unknown as EmbeddedExtension;\n assert(\n typeof extension.id === 'string' && /^[A-Za-z0-9._-]+$/u.test(extension.id),\n `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`,\n );\n assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);\n const expectedPath = `extensions/${extension.id}.js`;\n assert(\n extension.path === expectedPath,\n `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`,\n );\n assert(\n typeof extension.mediaType === 'string' &&\n extension.mediaType.length > 0 &&\n !/[;,\\r\\n]/u.test(extension.mediaType),\n `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`,\n );\n assert(\n Array.isArray(extension.parameters) &&\n extension.parameters.every(\n (parameter) =>\n typeof parameter === 'string' && parameter.length > 0 && !/[;,\\r\\n]/u.test(parameter),\n ),\n `Invalid data URL parameters for embedded extension ${extension.id}.`,\n );\n assert(\n extension.encoding === 'base64' || extension.encoding === 'percent',\n `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`,\n );\n assert(\n extensionUrls[extension.id] === `embedded-extension:${extension.path}`,\n `project.source.json mapping does not match embedded extension ${extension.id}.`,\n );\n validateExtensionSourceMetadata(extension);\n extensionsById.set(extension.id, extension);\n extensions.push(extension);\n expectedFiles.push(`${extension.id}.js`);\n if (extension.source?.apiManifest) {\n expectedFiles.push(path.posix.relative('extensions', extension.source.apiManifest.path));\n }\n }\n\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n assert(\n typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:'),\n `project.source.json still contains an embedded data URL: ${extensionId}`,\n );\n if (typeof extensionUrl === 'string' && extensionUrl.startsWith('embedded-extension:')) {\n assert(\n extensionsById.has(extensionId),\n `project.source.json has no metadata for embedded extension ${extensionId}.`,\n );\n }\n }\n\n assertSameFileSet(extensionFiles, expectedFiles, 'Embedded extension files');\n return {\n extensionBundles: validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensions,\n ),\n extensions,\n };\n}\n\nfunction collectAssetReferences(\n project: ProjectJson,\n): {asset: ProjectAssetReference; description: string}[] {\n assert(Array.isArray(project.targets), 'project.source.json targets must be an array.');\n const references: {asset: ProjectAssetReference; description: string}[] = [];\n for (const [targetIndex, target] of (project.targets as unknown[]).entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n for (const [collectionName, kind] of [\n ['costumes', 'costume'],\n ['sounds', 'sound'],\n ] as const) {\n const assets: unknown = target[collectionName] ?? [];\n assert(\n Array.isArray(assets),\n `Project target ${targetIndex} ${collectionName} must be an array.`,\n );\n for (const [assetIndex, asset] of (assets as unknown[]).entries()) {\n assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);\n references.push({asset, description: `${kind} ${targetIndex}:${assetIndex}`});\n }\n }\n }\n return references;\n}\n\nfunction percentEncode(contents: Uint8Array): string {\n return [...contents]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction encodeExtensionDataUrl(extension: EmbeddedExtension, contents: Uint8Array): string {\n const metadata = [extension.mediaType, ...extension.parameters].join(';');\n if (extension.encoding === 'base64') {\n return `data:${metadata};base64,${Buffer.from(contents).toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(contents)}`;\n}\n\nasync function inspectSb3Source(\n sourceDirectory: string,\n validateManagedExtensions: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n await assertDirectory(resolvedSourceDirectory, 'SB3 source');\n const sourceManifest = await readJson(\n path.join(resolvedSourceDirectory, 'sb3-source.json'),\n 'SB3 source manifest',\n );\n validateSourceManifest(sourceManifest);\n const assetEntries = sourceManifest.archiveEntries.filter(\n (entryName) => entryName !== 'project.json',\n );\n const project: unknown = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.project),\n 'SB3 project source',\n );\n assert(isObject(project), 'project.source.json must contain an object.');\n const extensionManifest = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions),\n 'Embedded extension manifest',\n );\n\n const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);\n const extensionsDirectory = path.join(resolvedSourceDirectory, 'extensions');\n const [assetFiles, extensionFiles] = await Promise.all([\n listRegularFiles(assetsDirectory, 'Assets directory'),\n listRegularFiles(extensionsDirectory, 'Extensions directory'),\n ]);\n assertSameFileSet(assetFiles, assetEntries, 'Asset files');\n const {extensionBundles, extensions} = validateExtensionManifest(\n extensionManifest,\n project,\n extensionFiles,\n );\n\n const assetContents = new Map<string, Uint8Array>();\n await Promise.all(\n assetFiles.map(async (assetPath) => {\n assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));\n }),\n );\n const referencedAssets = new Set<string>();\n const references = collectAssetReferences(project);\n for (const {asset, description} of references) {\n assert(\n typeof asset.assetId === 'string' && /^[a-f0-9]{32}$/u.test(asset.assetId),\n `Invalid assetId for ${description}: ${asset.assetId}`,\n );\n assert(\n typeof asset.dataFormat === 'string' && /^[A-Za-z0-9]+$/u.test(asset.dataFormat),\n `Invalid dataFormat for ${description}: ${asset.dataFormat}`,\n );\n const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;\n assert(\n asset.md5ext === expectedFilename,\n `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`,\n );\n const contents = assetContents.get(expectedFilename);\n assert(contents, `Referenced asset is missing for ${description}: ${expectedFilename}`);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === asset.assetId,\n `Asset content hash mismatch for ${description}: expected ${asset.assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(expectedFilename);\n }\n const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));\n assert(\n unreferencedAssets.length === 0,\n `Asset manifest contains unreferenced files: ${unreferencedAssets.join(', ')}`,\n );\n\n const extensionContents = new Map<string, Uint8Array>();\n const extensionApiManifestContents = new Map<string, Uint8Array>();\n await Promise.all(\n extensions.map(async (extension) => {\n const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));\n if (validateManagedExtensions) {\n validateManagedExtensionContents(extension, contents);\n }\n extensionContents.set(extension.id, contents);\n if (extension.source?.apiManifest) {\n const apiManifestContents = await readFile(\n path.join(resolvedSourceDirectory, extension.source.apiManifest.path),\n );\n if (validateManagedExtensions) {\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n extensionApiManifestContents.set(extension.id, apiManifestContents);\n }\n }),\n );\n\n return {\n assetContents,\n assetReferenceCount: references.length,\n extensions,\n extensionApiManifestContents,\n extensionBundles,\n extensionContents,\n project,\n resolvedSourceDirectory,\n sourceManifest,\n };\n}\n\nexport async function inspectSb3SourceForExtensionSync(\n sourceDirectory: string,\n): Promise<InspectedSb3Source> {\n return inspectSb3Source(sourceDirectory, false);\n}\n\nexport async function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source> {\n const source = await inspectSb3Source(sourceDirectory, true);\n await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n return source;\n}\n\nexport async function createDeterministicSb3(\n sourceDirectory: string,\n options: DeterministicSb3Options = {},\n): Promise<DeterministicSb3> {\n const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;\n assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');\n assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');\n assert(\n projectAssetsPath === undefined || typeof projectAssetsPath === 'string',\n 'projectAssetsPath must be a string when provided.',\n );\n const source = await inspectSb3Source(sourceDirectory, true);\n const projectAssets: {\n archiveEntries: string[];\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n project: ProjectJson;\n summary: Readonly<ProjectAssetAdditionsSummary> | null;\n } = projectAssetsPath\n ? await applyProjectAssetAdditions({\n allowedAssetRoots,\n assetContents: source.assetContents,\n archiveEntries: source.sourceManifest.archiveEntries,\n manifestPath: projectAssetsPath,\n project: source.project,\n })\n : {\n archiveEntries: source.sourceManifest.archiveEntries,\n assetContents: source.assetContents,\n assetReferenceCount: 0,\n project: source.project,\n summary: null,\n };\n const bundled = await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: projectAssets.project,\n });\n let project = structuredClone(bundled.project);\n let blockCleanUp: BlockCleanUpSummary | null = null;\n if (cleanUpBlocks) {\n const cleaned = cleanUpTurboWarpBlocks(project);\n project = cleaned.project;\n blockCleanUp = {\n movedCommentCount: cleaned.movedCommentCount,\n movedScriptCount: cleaned.movedScriptCount,\n scriptCount: cleaned.scriptCount,\n targetCount: cleaned.targetCount,\n };\n }\n const extensionUrls: Record<string, unknown> = project.extensionURLs ?? {};\n for (const extension of bundled.extensions) {\n const contents = bundled.extensionContents.get(extension.id);\n assert(contents, `Embedded extension has no contents: ${extension.id}`);\n extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);\n }\n project.extensionURLs = extensionUrls;\n\n const archiveEntries: Record<string, Uint8Array> = {};\n for (const entryName of projectAssets.archiveEntries) {\n if (entryName === 'project.json') {\n archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\\n`);\n continue;\n }\n const contents = projectAssets.assetContents.get(entryName);\n assert(contents, `Archive entry has no contents: ${entryName}`);\n archiveEntries[entryName] = contents;\n }\n const archive = zipSync(archiveEntries, {\n level: 6,\n mtime: fixedZipTimestamp,\n });\n\n return {\n archive,\n assetCount: projectAssets.assetContents.size,\n assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,\n blockCleanUp,\n bundlePlans: bundled.bundlePlans,\n embeddedExtensionCount: bundled.extensions.length,\n entryCount: projectAssets.archiveEntries.length,\n projectAssetAdditions: projectAssets.summary,\n source,\n };\n}\n"],"mapp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