@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,213 @@
1
+ import { assert, errorMessage } from "./assert.js";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { access, lstat, readFile, readdir, readlink, realpath, rename, rm } from "node:fs/promises";
5
+ import { execFile } from "node:child_process";
6
+ //#region src/output-safety.ts
7
+ function errorCode(error) {
8
+ return error?.code;
9
+ }
10
+ async function pathExists(targetPath) {
11
+ try {
12
+ await access(targetPath);
13
+ return true;
14
+ } catch (error) {
15
+ if (errorCode(error) === "ENOENT") return false;
16
+ throw error;
17
+ }
18
+ }
19
+ function isSamePathOrAncestor(candidatePath, targetPath) {
20
+ const relativePath = path.relative(candidatePath, targetPath);
21
+ return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
22
+ }
23
+ function validateOutputDirectoryPath(outputDirectory, protectedRoot) {
24
+ const resolvedOutputDirectory = path.resolve(outputDirectory);
25
+ const resolvedProtectedRoot = path.resolve(protectedRoot);
26
+ assert(resolvedOutputDirectory !== path.parse(resolvedOutputDirectory).root, "Refusing to replace a filesystem root with imported SB3 sources.");
27
+ assert(!isSamePathOrAncestor(resolvedOutputDirectory, resolvedProtectedRoot), "Refusing to replace the repository root or one of its ancestors.");
28
+ assert(!resolvedOutputDirectory.split(path.sep).includes(".git"), "Refusing to write imported SB3 sources into a .git directory.");
29
+ return resolvedOutputDirectory;
30
+ }
31
+ async function assertRecognizedOutputDirectory(outputDirectory, sourceFormatVersion) {
32
+ const stats = await lstat(outputDirectory);
33
+ assert(stats.isDirectory() && !stats.isSymbolicLink(), `Refusing to replace a non-directory or symbolic link: ${outputDirectory}`);
34
+ let manifest;
35
+ try {
36
+ manifest = JSON.parse(await readFile(path.join(outputDirectory, "sb3-source.json"), "utf8"));
37
+ } catch (error) {
38
+ if (errorCode(error) !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
39
+ throw new Error(`Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`, { cause: error });
40
+ }
41
+ assert(manifest?.formatVersion === sourceFormatVersion && manifest.project === "project.source.json" && manifest.embeddedExtensions === "embedded-extensions.json" && manifest.assetsDirectory === "assets" && Array.isArray(manifest.archiveEntries), `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`);
42
+ }
43
+ function digest(value) {
44
+ return createHash("sha256").update(value).digest("hex");
45
+ }
46
+ async function snapshotDirectory(rootDirectory) {
47
+ const snapshot = /* @__PURE__ */ new Map();
48
+ async function visit(directory, relativeDirectory) {
49
+ const entries = await readdir(directory, { withFileTypes: true });
50
+ entries.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
51
+ for (const entry of entries) {
52
+ const relativePath = relativeDirectory ? path.posix.join(relativeDirectory, entry.name) : entry.name;
53
+ const absolutePath = path.join(directory, entry.name);
54
+ if (entry.isDirectory()) {
55
+ snapshot.set(relativePath, { type: "directory" });
56
+ await visit(absolutePath, relativePath);
57
+ } else if (entry.isFile()) {
58
+ const contents = await readFile(absolutePath);
59
+ snapshot.set(relativePath, {
60
+ type: "file",
61
+ size: contents.length,
62
+ digest: digest(contents)
63
+ });
64
+ } else if (entry.isSymbolicLink()) snapshot.set(relativePath, {
65
+ type: "symbolic-link",
66
+ target: await readlink(absolutePath)
67
+ });
68
+ else snapshot.set(relativePath, { type: "other" });
69
+ }
70
+ }
71
+ await visit(rootDirectory, "");
72
+ return snapshot;
73
+ }
74
+ function snapshotFingerprint(snapshot) {
75
+ return digest(JSON.stringify([...snapshot.entries()]));
76
+ }
77
+ function entriesMatch(left, right) {
78
+ return JSON.stringify(left) === JSON.stringify(right);
79
+ }
80
+ async function compareDirectories(existingDirectory, candidateDirectory) {
81
+ const [existingSnapshot, candidateSnapshot] = await Promise.all([snapshotDirectory(existingDirectory), snapshotDirectory(candidateDirectory)]);
82
+ const paths = [.../* @__PURE__ */ new Set([...existingSnapshot.keys(), ...candidateSnapshot.keys()])].sort();
83
+ const differences = {
84
+ added: [],
85
+ modified: [],
86
+ removed: []
87
+ };
88
+ for (const relativePath of paths) {
89
+ const existingEntry = existingSnapshot.get(relativePath);
90
+ const candidateEntry = candidateSnapshot.get(relativePath);
91
+ if (!existingEntry) differences.added.push(relativePath);
92
+ else if (!candidateEntry) differences.removed.push(relativePath);
93
+ else if (!entriesMatch(existingEntry, candidateEntry)) differences.modified.push(relativePath);
94
+ }
95
+ return {
96
+ candidateFingerprint: snapshotFingerprint(candidateSnapshot),
97
+ differences,
98
+ existingFilePaths: [...existingSnapshot.entries()].filter(([, entry]) => entry.type !== "directory").map(([relativePath]) => relativePath),
99
+ existingFingerprint: snapshotFingerprint(existingSnapshot),
100
+ identical: Object.values(differences).every((entries) => entries.length === 0)
101
+ };
102
+ }
103
+ function executeGit(arguments_, cwd) {
104
+ return new Promise((resolve, reject) => {
105
+ execFile("git", arguments_, {
106
+ cwd,
107
+ encoding: "utf8",
108
+ maxBuffer: 10485760
109
+ }, (error, stdout, stderr) => {
110
+ if (error) {
111
+ Object.assign(error, {
112
+ stdout,
113
+ stderr
114
+ });
115
+ reject(error);
116
+ return;
117
+ }
118
+ resolve(stdout);
119
+ });
120
+ });
121
+ }
122
+ function toPosixPath(value) {
123
+ return value.split(path.sep).join("/");
124
+ }
125
+ async function inspectGitOutputState(outputDirectory, existingFilePaths) {
126
+ let repositoryRoot;
127
+ try {
128
+ repositoryRoot = (await executeGit(["rev-parse", "--show-toplevel"], outputDirectory)).trim();
129
+ } catch (error) {
130
+ if (errorCode(error) === 128) return {
131
+ clean: false,
132
+ fingerprint: "not-git-managed",
133
+ managed: false,
134
+ repositoryRoot: null,
135
+ statusEntries: [],
136
+ untrackedContent: [...existingFilePaths]
137
+ };
138
+ throw error;
139
+ }
140
+ const [canonicalOutputDirectory, canonicalRepositoryRoot] = await Promise.all([realpath(outputDirectory), realpath(repositoryRoot)]);
141
+ repositoryRoot = canonicalRepositoryRoot;
142
+ const relativeOutputDirectory = path.relative(repositoryRoot, canonicalOutputDirectory);
143
+ assert(relativeOutputDirectory !== ".." && !relativeOutputDirectory.startsWith(`..${path.sep}`) && !path.isAbsolute(relativeOutputDirectory), `Output directory is outside its detected Git worktree: ${outputDirectory}`);
144
+ const pathspec = relativeOutputDirectory || ".";
145
+ const [statusOutput, trackedOutput] = await Promise.all([executeGit([
146
+ "status",
147
+ "--porcelain=v1",
148
+ "--untracked-files=all",
149
+ "--",
150
+ pathspec
151
+ ], repositoryRoot), executeGit([
152
+ "ls-files",
153
+ "-z",
154
+ "--",
155
+ pathspec
156
+ ], repositoryRoot)]);
157
+ const statusEntries = statusOutput.split("\n").filter(Boolean);
158
+ const trackedPaths = new Set(trackedOutput.split("\0").filter(Boolean).map((trackedPath) => toPosixPath(path.relative(canonicalOutputDirectory, path.join(repositoryRoot, trackedPath)))));
159
+ const untrackedContent = existingFilePaths.filter((filePath) => !trackedPaths.has(filePath));
160
+ const managed = trackedPaths.size > 0;
161
+ const clean = managed && statusEntries.length === 0 && untrackedContent.length === 0;
162
+ return {
163
+ clean,
164
+ fingerprint: digest(JSON.stringify({
165
+ clean,
166
+ managed,
167
+ repositoryRoot,
168
+ statusEntries,
169
+ trackedPaths: [...trackedPaths].sort(),
170
+ untrackedContent: [...untrackedContent].sort()
171
+ })),
172
+ managed,
173
+ repositoryRoot,
174
+ statusEntries,
175
+ untrackedContent
176
+ };
177
+ }
178
+ async function assertNoInterruptedRollback(outputDirectory) {
179
+ const parentDirectory = path.dirname(outputDirectory);
180
+ const outputName = path.basename(outputDirectory);
181
+ const rollbackPrefixes = [`.${outputName}.rollback-`, `.${outputName}.backup-`];
182
+ const leftovers = (await readdir(parentDirectory)).filter((entryName) => rollbackPrefixes.some((prefix) => entryName.startsWith(prefix))).map((entryName) => path.join(parentDirectory, entryName));
183
+ assert(leftovers.length === 0, `Found an interrupted SB3 import rollback directory. Inspect or restore it before retrying: ${leftovers.join(", ")}`);
184
+ }
185
+ async function replaceDirectoryTransactionally(temporaryDirectory, outputDirectory) {
186
+ const parentDirectory = path.dirname(outputDirectory);
187
+ await assertNoInterruptedRollback(outputDirectory);
188
+ const rollbackDirectory = path.join(parentDirectory, `.${path.basename(outputDirectory)}.rollback-${randomUUID()}`);
189
+ assert(!await pathExists(rollbackDirectory), `Refusing to overwrite an existing rollback directory: ${rollbackDirectory}`);
190
+ const outputExists = await pathExists(outputDirectory);
191
+ if (outputExists) await rename(outputDirectory, rollbackDirectory);
192
+ try {
193
+ await rename(temporaryDirectory, outputDirectory);
194
+ } catch (installError) {
195
+ if (outputExists) try {
196
+ await rename(rollbackDirectory, outputDirectory);
197
+ } catch (restoreError) {
198
+ throw new AggregateError([installError, restoreError], `SB3 import failed and automatic restoration also failed. Original output remains at: ${rollbackDirectory}`);
199
+ }
200
+ throw installError;
201
+ }
202
+ if (!outputExists) return { rollbackCleanupWarning: null };
203
+ try {
204
+ await rm(rollbackDirectory, { recursive: true });
205
+ return { rollbackCleanupWarning: null };
206
+ } catch (error) {
207
+ return { rollbackCleanupWarning: `Imported output was installed, but its temporary rollback directory could not be removed: ${rollbackDirectory} (${errorMessage(error)})` };
208
+ }
209
+ }
210
+ //#endregion
211
+ export { assertNoInterruptedRollback, assertRecognizedOutputDirectory, compareDirectories, inspectGitOutputState, pathExists, replaceDirectoryTransactionally, validateOutputDirectoryPath };
212
+
213
+ //# sourceMappingURL=output-safety.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-safety.js","names":[],"sources":["../src/output-safety.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {execFile} from 'node:child_process';\nimport {createHash, randomUUID} from 'node:crypto';\nimport {access, lstat, realpath, readdir, readFile, readlink, rename, rm} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert, errorMessage} from './assert';\n\ntype SnapshotEntry =\n | {type: 'directory'}\n | {type: 'file'; size: number; digest: string}\n | {type: 'symbolic-link'; target: string}\n | {type: 'other'};\n\nexport interface DirectoryDifferences {\n added: string[];\n modified: string[];\n removed: string[];\n}\n\nexport interface DirectoryComparison {\n candidateFingerprint: string;\n differences: DirectoryDifferences;\n existingFilePaths: string[];\n existingFingerprint: string;\n identical: boolean;\n}\n\nexport interface GitOutputState {\n clean: boolean;\n fingerprint: string;\n managed: boolean;\n repositoryRoot: string | null;\n statusEntries: string[];\n untrackedContent: string[];\n}\n\nfunction errorCode(error: unknown): string | number | undefined {\n return (error as NodeJS.ErrnoException | null)?.code;\n}\n\nexport async function pathExists(targetPath: string): Promise<boolean> {\n try {\n await access(targetPath);\n return true;\n } catch (error) {\n if (errorCode(error) === 'ENOENT') {\n return false;\n }\n throw error;\n }\n}\n\nfunction isSamePathOrAncestor(candidatePath: string, targetPath: string): boolean {\n const relativePath = path.relative(candidatePath, targetPath);\n return (\n relativePath === '' ||\n (relativePath !== '..' &&\n !relativePath.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativePath))\n );\n}\n\nexport function validateOutputDirectoryPath(\n outputDirectory: string,\n protectedRoot: string,\n): string {\n const resolvedOutputDirectory = path.resolve(outputDirectory);\n const resolvedProtectedRoot = path.resolve(protectedRoot);\n assert(\n resolvedOutputDirectory !== path.parse(resolvedOutputDirectory).root,\n 'Refusing to replace a filesystem root with imported SB3 sources.',\n );\n assert(\n !isSamePathOrAncestor(resolvedOutputDirectory, resolvedProtectedRoot),\n 'Refusing to replace the repository root or one of its ancestors.',\n );\n assert(\n !resolvedOutputDirectory.split(path.sep).includes('.git'),\n 'Refusing to write imported SB3 sources into a .git directory.',\n );\n return resolvedOutputDirectory;\n}\n\nexport async function assertRecognizedOutputDirectory(\n outputDirectory: string,\n sourceFormatVersion: number,\n): Promise<void> {\n const stats = await lstat(outputDirectory);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `Refusing to replace a non-directory or symbolic link: ${outputDirectory}`,\n );\n\n let manifest: Record<string, unknown> | null;\n try {\n manifest = JSON.parse(await readFile(path.join(outputDirectory, 'sb3-source.json'), 'utf8'));\n } catch (error) {\n if (errorCode(error) !== 'ENOENT' && !(error instanceof SyntaxError)) {\n throw error;\n }\n throw new Error(\n `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`,\n {cause: error},\n );\n }\n\n assert(\n manifest?.formatVersion === sourceFormatVersion &&\n manifest.project === 'project.source.json' &&\n manifest.embeddedExtensions === 'embedded-extensions.json' &&\n manifest.assetsDirectory === 'assets' &&\n Array.isArray(manifest.archiveEntries),\n `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`,\n );\n}\n\nfunction digest(value: Uint8Array | string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nasync function snapshotDirectory(rootDirectory: string): Promise<Map<string, SnapshotEntry>> {\n const snapshot = new Map<string, SnapshotEntry>();\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\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 snapshot.set(relativePath, {type: 'directory'});\n await visit(absolutePath, relativePath);\n } else if (entry.isFile()) {\n const contents = await readFile(absolutePath);\n snapshot.set(relativePath, {\n type: 'file',\n size: contents.length,\n digest: digest(contents),\n });\n } else if (entry.isSymbolicLink()) {\n snapshot.set(relativePath, {\n type: 'symbolic-link',\n target: await readlink(absolutePath),\n });\n } else {\n snapshot.set(relativePath, {type: 'other'});\n }\n }\n }\n\n await visit(rootDirectory, '');\n return snapshot;\n}\n\nfunction snapshotFingerprint(snapshot: Map<string, SnapshotEntry>): string {\n return digest(JSON.stringify([...snapshot.entries()]));\n}\n\nfunction entriesMatch(left: SnapshotEntry, right: SnapshotEntry): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport async function compareDirectories(\n existingDirectory: string,\n candidateDirectory: string,\n): Promise<DirectoryComparison> {\n const [existingSnapshot, candidateSnapshot] = await Promise.all([\n snapshotDirectory(existingDirectory),\n snapshotDirectory(candidateDirectory),\n ]);\n const paths = [...new Set([...existingSnapshot.keys(), ...candidateSnapshot.keys()])].sort();\n const differences: DirectoryDifferences = {added: [], modified: [], removed: []};\n\n for (const relativePath of paths) {\n const existingEntry = existingSnapshot.get(relativePath);\n const candidateEntry = candidateSnapshot.get(relativePath);\n if (!existingEntry) {\n differences.added.push(relativePath);\n } else if (!candidateEntry) {\n differences.removed.push(relativePath);\n } else if (!entriesMatch(existingEntry, candidateEntry)) {\n differences.modified.push(relativePath);\n }\n }\n\n return {\n candidateFingerprint: snapshotFingerprint(candidateSnapshot),\n differences,\n existingFilePaths: [...existingSnapshot.entries()]\n .filter(([, entry]) => entry.type !== 'directory')\n .map(([relativePath]) => relativePath),\n existingFingerprint: snapshotFingerprint(existingSnapshot),\n identical: Object.values(differences).every((entries) => entries.length === 0),\n };\n}\n\nfunction executeGit(arguments_: string[], cwd: string): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n execFile(\n 'git',\n arguments_,\n {cwd, encoding: 'utf8', maxBuffer: 10 * 1024 * 1024},\n (error, stdout, stderr) => {\n if (error) {\n Object.assign(error, {stdout, stderr});\n reject(error);\n return;\n }\n resolve(stdout);\n },\n );\n });\n}\n\nfunction toPosixPath(value: string): string {\n return value.split(path.sep).join('/');\n}\n\nexport async function inspectGitOutputState(\n outputDirectory: string,\n existingFilePaths: string[],\n): Promise<GitOutputState> {\n let repositoryRoot: string;\n try {\n repositoryRoot = (await executeGit(['rev-parse', '--show-toplevel'], outputDirectory)).trim();\n } catch (error) {\n if (errorCode(error) === 128) {\n return {\n clean: false,\n fingerprint: 'not-git-managed',\n managed: false,\n repositoryRoot: null,\n statusEntries: [],\n untrackedContent: [...existingFilePaths],\n };\n }\n throw error;\n }\n\n const [canonicalOutputDirectory, canonicalRepositoryRoot] = await Promise.all([\n realpath(outputDirectory),\n realpath(repositoryRoot),\n ]);\n repositoryRoot = canonicalRepositoryRoot;\n const relativeOutputDirectory = path.relative(repositoryRoot, canonicalOutputDirectory);\n assert(\n relativeOutputDirectory !== '..' &&\n !relativeOutputDirectory.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativeOutputDirectory),\n `Output directory is outside its detected Git worktree: ${outputDirectory}`,\n );\n const pathspec = relativeOutputDirectory || '.';\n const [statusOutput, trackedOutput] = await Promise.all([\n executeGit(\n ['status', '--porcelain=v1', '--untracked-files=all', '--', pathspec],\n repositoryRoot,\n ),\n executeGit(['ls-files', '-z', '--', pathspec], repositoryRoot),\n ]);\n const statusEntries = statusOutput.split('\\n').filter(Boolean);\n const trackedPaths = new Set(\n trackedOutput\n .split('\\0')\n .filter(Boolean)\n .map((trackedPath) =>\n toPosixPath(\n path.relative(canonicalOutputDirectory, path.join(repositoryRoot, trackedPath)),\n ),\n ),\n );\n const untrackedContent = existingFilePaths.filter((filePath) => !trackedPaths.has(filePath));\n const managed = trackedPaths.size > 0;\n const clean = managed && statusEntries.length === 0 && untrackedContent.length === 0;\n const fingerprint = digest(\n JSON.stringify({\n clean,\n managed,\n repositoryRoot,\n statusEntries,\n trackedPaths: [...trackedPaths].sort(),\n untrackedContent: [...untrackedContent].sort(),\n }),\n );\n\n return {\n clean,\n fingerprint,\n managed,\n repositoryRoot,\n statusEntries,\n untrackedContent,\n };\n}\n\nexport async function assertNoInterruptedRollback(outputDirectory: string): Promise<void> {\n const parentDirectory = path.dirname(outputDirectory);\n const outputName = path.basename(outputDirectory);\n const rollbackPrefixes = [`.${outputName}.rollback-`, `.${outputName}.backup-`];\n const leftovers = (await readdir(parentDirectory))\n .filter((entryName) => rollbackPrefixes.some((prefix) => entryName.startsWith(prefix)))\n .map((entryName) => path.join(parentDirectory, entryName));\n assert(\n leftovers.length === 0,\n `Found an interrupted SB3 import rollback directory. ` +\n `Inspect or restore it before retrying: ${leftovers.join(', ')}`,\n );\n}\n\nexport async function replaceDirectoryTransactionally(\n temporaryDirectory: string,\n outputDirectory: string,\n): Promise<{rollbackCleanupWarning: string | null}> {\n const parentDirectory = path.dirname(outputDirectory);\n await assertNoInterruptedRollback(outputDirectory);\n const rollbackDirectory = path.join(\n parentDirectory,\n `.${path.basename(outputDirectory)}.rollback-${randomUUID()}`,\n );\n assert(\n !(await pathExists(rollbackDirectory)),\n `Refusing to overwrite an existing rollback directory: ${rollbackDirectory}`,\n );\n const outputExists = await pathExists(outputDirectory);\n\n if (outputExists) {\n await rename(outputDirectory, rollbackDirectory);\n }\n\n try {\n await rename(temporaryDirectory, outputDirectory);\n } catch (installError) {\n if (outputExists) {\n try {\n await rename(rollbackDirectory, outputDirectory);\n } catch (restoreError) {\n throw new AggregateError(\n [installError, restoreError],\n `SB3 import failed and automatic restoration also failed. ` +\n `Original output remains at: ${rollbackDirectory}`,\n );\n }\n }\n throw installError;\n }\n\n if (!outputExists) {\n return {rollbackCleanupWarning: null};\n }\n\n try {\n await rm(rollbackDirectory, {recursive: true});\n return {rollbackCleanupWarning: null};\n } catch (error) {\n return {\n rollbackCleanupWarning:\n `Imported output was installed, but its temporary rollback ` +\n `directory could not be removed: ${rollbackDirectory} (${errorMessage(error)})`,\n };\n }\n}\n"],"mappings":";;;;;;AAsCA,SAAS,UAAU,OAA6C;CAC9D,OAAQ,OAAwC;AAClD;AAEA,eAAsB,WAAW,YAAsC;CACrE,IAAI;EACF,MAAM,OAAO,UAAU;EACvB,OAAO;CACT,SAAS,OAAO;EACd,IAAI,UAAU,KAAK,MAAM,UACvB,OAAO;EAET,MAAM;CACR;AACF;AAEA,SAAS,qBAAqB,eAAuB,YAA6B;CAChF,MAAM,eAAe,KAAK,SAAS,eAAe,UAAU;CAC5D,OACE,iBAAiB,MAChB,iBAAiB,QAChB,CAAC,aAAa,WAAW,KAAK,KAAK,KAAK,KACxC,CAAC,KAAK,WAAW,YAAY;AAEnC;AAEA,SAAgB,4BACd,iBACA,eACQ;CACR,MAAM,0BAA0B,KAAK,QAAQ,eAAe;CAC5D,MAAM,wBAAwB,KAAK,QAAQ,aAAa;CACxD,OACE,4BAA4B,KAAK,MAAM,uBAAuB,CAAC,CAAC,MAChE,kEACF;CACA,OACE,CAAC,qBAA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cAAc,KAAK,KAAK,iBAAiB,SAAS,CAAC;CAC3D,OACE,UAAU,WAAW,GACrB,8FAC4C,UAAU,KAAK,IAAI,GACjE;AACF;AAEA,eAAsB,gCACpB,oBACA,iBACkD;CAClD,MAAM,kBAAkB,KAAK,QAAQ,eAAe;CACpD,MAAM,4BAA4B,eAAe;CACjD,MAAM,oBAAoB,KAAK,KAC7B,iBACA,IAAI,KAAK,SAAS,eAAe,EAAE,YAAY,WAAW,GAC5D;CACA,OACE,CAAE,MAAM,WAAW,iBAAiB,GACpC,yDAAyD,mBAC3D;CACA,MAAM,eAAe,MAAM,WAAW,eAAe;CAErD,IAAI,cACF,MAAM,OAAO,iBAAiB,iBAAiB;CAGjD,IAAI;EACF,MAAM,OAAO,oBAAoB,eAAe;CAClD,SAAS,cAAc;EACrB,IAAI,cACF,IAAI;GACF,MAAM,OAAO,mBAAmB,eAAe;EACjD,SAAS,cAAc;GACrB,MAAM,IAAI,eACR,CAAC,cAAc,YAAY,GAC3B,wFACiC,mBACnC;EACF;EAEF,MAAM;CACR;CAEA,IAAI,CAAC,cACH,OAAO,EAAC,wBAAwB,KAAI;CAGtC,IAAI;EACF,MAAM,GAAG,mBAAmB,EAAC,WAAW,KAAI,CAAC;EAC7C,OAAO,EAAC,wBAAwB,KAAI;CACtC,SAAS,OAAO;EACd,OAAO,EACL,wBACE,6FACmC,kBAAkB,IAAI,aAAa,KAAK,EAAE,GACjF;CACF;AACF"}
@@ -0,0 +1,29 @@
1
+ import { ProjectJson } from './types';
2
+ export declare const projectAssetAdditionsFormatVersion = 1;
3
+ export interface ProjectAssetAdditionsSummary {
4
+ assetFileCount: number;
5
+ backdropCount: number;
6
+ costumeCount: number;
7
+ soundCount: number;
8
+ spriteCount: number;
9
+ }
10
+ export interface ProjectAssetAdditionsInput {
11
+ allowedAssetRoots?: string[];
12
+ archiveEntries: string[];
13
+ assetContents: Map<string, Uint8Array>;
14
+ manifestPath: string;
15
+ project: ProjectJson;
16
+ }
17
+ export interface ProjectAssetAdditionsResult {
18
+ archiveEntries: string[];
19
+ assetContents: Map<string, Uint8Array>;
20
+ assetReferenceCount: number;
21
+ manifestPath: string;
22
+ project: ProjectJson;
23
+ summary: Readonly<ProjectAssetAdditionsSummary>;
24
+ }
25
+ /**
26
+ * Validate a JSON or YAML project-assets manifest and compose it into one in-memory build.
27
+ * The expanded source and all manifest inputs remain unchanged.
28
+ */
29
+ export declare function applyProjectAssetAdditions({ allowedAssetRoots, assetContents, archiveEntries, manifestPath, project, }: ProjectAssetAdditionsInput): Promise<ProjectAssetAdditionsResult>;