@kubohiroya/sb3-toolchain 0.23.0 → 0.25.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.
- package/CHANGELOG.md +10 -0
- package/README.ja.md +8 -1
- package/README.md +8 -1
- package/dist/archive.js +1 -2
- package/dist/archive.js.map +1 -1
- package/dist/block-palette.d.ts +60 -0
- package/dist/block-palette.js +295 -0
- package/dist/block-palette.js.map +1 -0
- package/dist/browser.d.ts +24 -0
- package/dist/browser.js +134 -0
- package/dist/browser.js.map +1 -0
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/constants.js.map +1 -1
- package/dist/expand-archive.d.ts +32 -0
- package/dist/expand-archive.js +146 -0
- package/dist/expand-archive.js.map +1 -0
- package/dist/import.d.ts +3 -0
- package/dist/import.js +31 -115
- package/dist/import.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +4 -2
- package/dist/output-safety.d.ts +1 -1
- package/dist/output-safety.js +2 -2
- package/dist/output-safety.js.map +1 -1
- package/dist/source-format.d.ts +20 -0
- package/dist/source-format.js +134 -0
- package/dist/source-format.js.map +1 -0
- package/dist/source.d.ts +4 -1
- package/dist/source.js +23 -116
- package/dist/source.js.map +1 -1
- package/dist/types.d.ts +2 -0
- package/docs/index.html +4 -2
- package/docs/ja/source-format-v1.md +2 -0
- package/docs/ja/source-format-v2.md +139 -0
- package/docs/source-format-v1.md +3 -0
- package/docs/source-format-v2.md +171 -0
- package/package.json +6 -1
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { assert, errorMessage } from "./assert.js";
|
|
2
|
+
import { blockPaletteFile, extractBlockPalette, serializeBlockPaletteDocument } from "./block-palette.js";
|
|
3
|
+
import { validateArchiveEntryName } from "./archive.js";
|
|
4
|
+
import { isObject } from "./source-format.js";
|
|
5
|
+
import { strFromU8, strToU8, unzipSync } from "fflate";
|
|
6
|
+
//#region src/expand-archive.ts
|
|
7
|
+
var Sb3SourceError = class extends Error {
|
|
8
|
+
code;
|
|
9
|
+
constructor(code, message, options) {
|
|
10
|
+
super(message, options);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.name = "Sb3SourceError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
function decodeExtensionBytes(dataUrl) {
|
|
16
|
+
assert(typeof dataUrl === "string" && dataUrl.startsWith("data:"), "Embedded extension URL must be a data URL.");
|
|
17
|
+
const commaIndex = dataUrl.indexOf(",");
|
|
18
|
+
assert(commaIndex >= 0, "Embedded extension data URL has no payload separator.");
|
|
19
|
+
const metadata = dataUrl.slice(5, commaIndex).split(";");
|
|
20
|
+
const mediaType = metadata.shift() || "text/plain";
|
|
21
|
+
const base64Index = metadata.indexOf("base64");
|
|
22
|
+
const encoding = base64Index >= 0 ? "base64" : "percent";
|
|
23
|
+
if (base64Index >= 0) metadata.splice(base64Index, 1);
|
|
24
|
+
const payload = dataUrl.slice(commaIndex + 1);
|
|
25
|
+
let source;
|
|
26
|
+
if (encoding === "base64") {
|
|
27
|
+
assert(/^[A-Za-z0-9+/]*={0,2}$/u.test(payload), "Embedded extension data URL contains invalid base64.");
|
|
28
|
+
const unpaddedPayload = payload.replace(/=+$/u, "");
|
|
29
|
+
assert(unpaddedPayload.length % 4 !== 1, "Embedded extension data URL contains invalid base64.");
|
|
30
|
+
const padded = unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, "=");
|
|
31
|
+
source = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
|
|
32
|
+
} else try {
|
|
33
|
+
source = strToU8(decodeURIComponent(payload));
|
|
34
|
+
} catch {
|
|
35
|
+
throw new Error("Embedded extension data URL contains invalid percent encoding.");
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
encoding,
|
|
39
|
+
mediaType,
|
|
40
|
+
parameters: metadata,
|
|
41
|
+
source
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Parse and extract the archive once. Callers choose the rules for extra ZIP entries. */
|
|
45
|
+
function expandArchive(bytes, limits) {
|
|
46
|
+
if (limits && bytes.byteLength > limits.maxArchiveBytes) throw new Sb3SourceError("archive-limit", "SB3 exceeds the maximum archive size.");
|
|
47
|
+
const seen = /* @__PURE__ */ new Set();
|
|
48
|
+
let expandedBytes = 0;
|
|
49
|
+
let archive;
|
|
50
|
+
try {
|
|
51
|
+
archive = unzipSync(bytes, { filter({ name, originalSize }) {
|
|
52
|
+
try {
|
|
53
|
+
validateArchiveEntryName(name);
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
throw new Sb3SourceError("unsafe-path", errorMessage(cause), { cause });
|
|
56
|
+
}
|
|
57
|
+
if (seen.has(name)) throw new Sb3SourceError("invalid-archive", `Duplicate SB3 archive entry: ${name}`);
|
|
58
|
+
seen.add(name);
|
|
59
|
+
expandedBytes += originalSize;
|
|
60
|
+
if (limits && (seen.size > limits.maxEntries || originalSize > limits.maxEntryBytes || expandedBytes > limits.maxExpandedBytes)) throw new Sb3SourceError("archive-limit", "Expanded SB3 exceeds the archive limits.");
|
|
61
|
+
return true;
|
|
62
|
+
} });
|
|
63
|
+
} catch (cause) {
|
|
64
|
+
if (cause instanceof Sb3SourceError) throw cause;
|
|
65
|
+
throw new Sb3SourceError("invalid-archive", `SB3 archive is not a valid ZIP: ${errorMessage(cause)}`, { cause });
|
|
66
|
+
}
|
|
67
|
+
const archiveEntries = Object.keys(archive);
|
|
68
|
+
if (archiveEntries.length === 0) throw new Sb3SourceError("invalid-archive", "SB3 archive is empty.");
|
|
69
|
+
if (archiveEntries.length !== seen.size) throw new Sb3SourceError("invalid-archive", "SB3 archive contains an unsupported entry name.");
|
|
70
|
+
const projectEntry = archive["project.json"];
|
|
71
|
+
if (!projectEntry) throw new Sb3SourceError("invalid-project", "SB3 archive does not contain project.json.");
|
|
72
|
+
let project;
|
|
73
|
+
try {
|
|
74
|
+
project = JSON.parse(strFromU8(projectEntry));
|
|
75
|
+
} catch (cause) {
|
|
76
|
+
throw new Sb3SourceError("invalid-project", `SB3 project.json is invalid JSON: ${errorMessage(cause)}`, { cause });
|
|
77
|
+
}
|
|
78
|
+
if (!isObject(project)) throw new Sb3SourceError("invalid-project", "SB3 project.json must contain a JSON object.");
|
|
79
|
+
const extensionUrls = project.extensionURLs ?? {};
|
|
80
|
+
if (!isObject(extensionUrls)) throw new Sb3SourceError("invalid-project", "SB3 project.json extensionURLs must be an object when present.");
|
|
81
|
+
const embeddedExtensions = [];
|
|
82
|
+
const extensionFiles = /* @__PURE__ */ new Map();
|
|
83
|
+
for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {
|
|
84
|
+
if (typeof extensionUrl !== "string" || !extensionUrl.startsWith("data:")) continue;
|
|
85
|
+
if (!/^[A-Za-z0-9._-]+$/u.test(extensionId)) throw new Sb3SourceError("unsafe-path", `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`);
|
|
86
|
+
try {
|
|
87
|
+
const { source, ...metadata } = decodeExtensionBytes(extensionUrl);
|
|
88
|
+
const path = `extensions/${extensionId}.js`;
|
|
89
|
+
extensionUrls[extensionId] = `embedded-extension:${path}`;
|
|
90
|
+
embeddedExtensions.push({
|
|
91
|
+
id: extensionId,
|
|
92
|
+
path,
|
|
93
|
+
mediaType: metadata.mediaType,
|
|
94
|
+
parameters: metadata.parameters,
|
|
95
|
+
encoding: metadata.encoding
|
|
96
|
+
});
|
|
97
|
+
extensionFiles.set(path, source);
|
|
98
|
+
} catch (cause) {
|
|
99
|
+
throw new Sb3SourceError("invalid-extension", errorMessage(cause), { cause });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
let blockPalette;
|
|
103
|
+
try {
|
|
104
|
+
blockPalette = extractBlockPalette(project);
|
|
105
|
+
} catch (cause) {
|
|
106
|
+
throw new Sb3SourceError("invalid-project", errorMessage(cause), { cause });
|
|
107
|
+
}
|
|
108
|
+
const assets = /* @__PURE__ */ new Map();
|
|
109
|
+
for (const name of archiveEntries) if (name !== "project.json" && !name.endsWith("/")) assets.set(name, archive[name]);
|
|
110
|
+
return {
|
|
111
|
+
archiveEntries,
|
|
112
|
+
assets,
|
|
113
|
+
blockPalette: blockPalette.document,
|
|
114
|
+
blockPaletteWarnings: blockPalette.warnings,
|
|
115
|
+
embeddedExtensions,
|
|
116
|
+
extensionFiles,
|
|
117
|
+
project
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function formatSourceFiles({ archiveEntries, assets, blockPalette, embeddedExtensions, extensionFiles, project }) {
|
|
121
|
+
const files = /* @__PURE__ */ new Map();
|
|
122
|
+
for (const [name, bytes] of assets) files.set(`assets/${name}`, bytes);
|
|
123
|
+
for (const [name, bytes] of extensionFiles) files.set(name, bytes);
|
|
124
|
+
const documents = {
|
|
125
|
+
"project.source.json": project,
|
|
126
|
+
"embedded-extensions.json": {
|
|
127
|
+
formatVersion: 1,
|
|
128
|
+
extensions: embeddedExtensions
|
|
129
|
+
},
|
|
130
|
+
"sb3-source.json": {
|
|
131
|
+
formatVersion: blockPalette ? 2 : 1,
|
|
132
|
+
project: "project.source.json",
|
|
133
|
+
embeddedExtensions: "embedded-extensions.json",
|
|
134
|
+
assetsDirectory: "assets",
|
|
135
|
+
archiveEntries,
|
|
136
|
+
...blockPalette ? { blockPalette: blockPaletteFile } : {}
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
for (const [name, value] of Object.entries(documents)) files.set(name, strToU8(`${JSON.stringify(value, null, 2)}\n`));
|
|
140
|
+
if (blockPalette) files.set(blockPaletteFile, strToU8(serializeBlockPaletteDocument(blockPalette)));
|
|
141
|
+
return files;
|
|
142
|
+
}
|
|
143
|
+
//#endregion
|
|
144
|
+
export { Sb3SourceError, decodeExtensionBytes, expandArchive, formatSourceFiles };
|
|
145
|
+
|
|
146
|
+
//# sourceMappingURL=expand-archive.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"expand-archive.js","names":[],"sources":["../src/expand-archive.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {strFromU8, strToU8, unzipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {\n blockPaletteFile,\n extractBlockPalette,\n serializeBlockPaletteDocument,\n} from './block-palette';\nimport type {BlockPaletteDocument, BlockPaletteWarning} from './block-palette';\nimport {\n blockPaletteSourceFormatVersion,\n embeddedExtensionManifestFormatVersion,\n isObject,\n sourceFormatVersion,\n} from './source-format';\nimport type {EmbeddedExtension, ExtensionEncoding, ProjectJson} from './types';\n\nexport type Sb3SourceErrorCode =\n | 'invalid-archive'\n | 'archive-limit'\n | 'unsafe-path'\n | 'invalid-project'\n | 'invalid-extension'\n | 'missing-asset'\n | 'invalid-asset'\n | 'invalid-source'\n | 'invalid-block-palette'\n | 'unsupported-project';\n\nexport class Sb3SourceError extends Error {\n constructor(\n readonly code: Sb3SourceErrorCode,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'Sb3SourceError';\n }\n}\n\ninterface ArchiveLimits {\n maxArchiveBytes: number;\n maxEntryBytes: number;\n maxEntries: number;\n maxExpandedBytes: number;\n}\n\ninterface ExpandedArchive {\n archiveEntries: string[];\n assets: Map<string, Uint8Array>;\n blockPalette: BlockPaletteDocument | null;\n blockPaletteWarnings: BlockPaletteWarning[];\n embeddedExtensions: EmbeddedExtension[];\n extensionFiles: Map<string, Uint8Array>;\n project: ProjectJson;\n}\n\nexport function decodeExtensionBytes(dataUrl: unknown): {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Uint8Array;\n} {\n assert(\n typeof dataUrl === 'string' && dataUrl.startsWith('data:'),\n 'Embedded extension URL must be a data URL.',\n );\n const commaIndex = dataUrl.indexOf(',');\n assert(commaIndex >= 0, 'Embedded extension data URL has no payload separator.');\n\n const metadata = dataUrl.slice('data:'.length, commaIndex).split(';');\n const mediaType = metadata.shift() || 'text/plain';\n const base64Index = metadata.indexOf('base64');\n const encoding: ExtensionEncoding = base64Index >= 0 ? 'base64' : 'percent';\n if (base64Index >= 0) metadata.splice(base64Index, 1);\n\n const payload = dataUrl.slice(commaIndex + 1);\n let source: Uint8Array;\n if (encoding === 'base64') {\n assert(\n /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),\n 'Embedded extension data URL contains invalid base64.',\n );\n const unpaddedPayload = payload.replace(/=+$/u, '');\n assert(\n unpaddedPayload.length % 4 !== 1,\n 'Embedded extension data URL contains invalid base64.',\n );\n const padded = unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, '=');\n source = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));\n } else {\n try {\n source = strToU8(decodeURIComponent(payload));\n } catch {\n throw new Error('Embedded extension data URL contains invalid percent encoding.');\n }\n }\n\n return {encoding, mediaType, parameters: metadata, source};\n}\n\n/** Parse and extract the archive once. Callers choose the rules for extra ZIP entries. */\nexport function expandArchive(bytes: Uint8Array, limits?: ArchiveLimits): ExpandedArchive {\n if (limits && bytes.byteLength > limits.maxArchiveBytes) {\n throw new Sb3SourceError('archive-limit', 'SB3 exceeds the maximum archive size.');\n }\n\n const seen = new Set<string>();\n let expandedBytes = 0;\n let archive: Record<string, Uint8Array>;\n try {\n archive = unzipSync(bytes, {\n filter({name, originalSize}) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (seen.has(name)) {\n throw new Sb3SourceError('invalid-archive', `Duplicate SB3 archive entry: ${name}`);\n }\n seen.add(name);\n expandedBytes += originalSize;\n if (\n limits &&\n (seen.size > limits.maxEntries ||\n originalSize > limits.maxEntryBytes ||\n expandedBytes > limits.maxExpandedBytes)\n ) {\n throw new Sb3SourceError('archive-limit', 'Expanded SB3 exceeds the archive limits.');\n }\n return true;\n },\n });\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError(\n 'invalid-archive',\n `SB3 archive is not a valid ZIP: ${errorMessage(cause)}`,\n {cause},\n );\n }\n const archiveEntries = Object.keys(archive);\n if (archiveEntries.length === 0) {\n throw new Sb3SourceError('invalid-archive', 'SB3 archive is empty.');\n }\n if (archiveEntries.length !== seen.size) {\n throw new Sb3SourceError('invalid-archive', 'SB3 archive contains an unsupported entry name.');\n }\n\n const projectEntry = archive['project.json'];\n if (!projectEntry) {\n throw new Sb3SourceError('invalid-project', 'SB3 archive does not contain project.json.');\n }\n let project: unknown;\n try {\n project = JSON.parse(strFromU8(projectEntry));\n } catch (cause) {\n throw new Sb3SourceError(\n 'invalid-project',\n `SB3 project.json is invalid JSON: ${errorMessage(cause)}`,\n {cause},\n );\n }\n if (!isObject(project)) {\n throw new Sb3SourceError('invalid-project', 'SB3 project.json must contain a JSON object.');\n }\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n if (!isObject(extensionUrls)) {\n throw new Sb3SourceError(\n 'invalid-project',\n 'SB3 project.json extensionURLs must be an object when present.',\n );\n }\n const embeddedExtensions: EmbeddedExtension[] = [];\n const extensionFiles = new Map<string, Uint8Array>();\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n if (typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:')) continue;\n if (!/^[A-Za-z0-9._-]+$/u.test(extensionId)) {\n throw new Sb3SourceError(\n 'unsafe-path',\n `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`,\n );\n }\n try {\n const {source, ...metadata} = decodeExtensionBytes(extensionUrl);\n const path = `extensions/${extensionId}.js`;\n extensionUrls[extensionId] = `embedded-extension:${path}`;\n embeddedExtensions.push({\n id: extensionId,\n path,\n mediaType: metadata.mediaType,\n parameters: metadata.parameters,\n encoding: metadata.encoding,\n });\n extensionFiles.set(path, source);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n }\n\n let blockPalette: ReturnType<typeof extractBlockPalette>;\n try {\n blockPalette = extractBlockPalette(project);\n } catch (cause) {\n throw new Sb3SourceError('invalid-project', errorMessage(cause), {cause});\n }\n\n const assets = new Map<string, Uint8Array>();\n for (const name of archiveEntries) {\n if (name !== 'project.json' && !name.endsWith('/')) assets.set(name, archive[name]);\n }\n return {\n archiveEntries,\n assets,\n blockPalette: blockPalette.document,\n blockPaletteWarnings: blockPalette.warnings,\n embeddedExtensions,\n extensionFiles,\n project,\n };\n}\n\nexport function formatSourceFiles({\n archiveEntries,\n assets,\n blockPalette,\n embeddedExtensions,\n extensionFiles,\n project,\n}: ExpandedArchive): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n for (const [name, bytes] of assets) files.set(`assets/${name}`, bytes);\n for (const [name, bytes] of extensionFiles) files.set(name, bytes);\n\n const documents = {\n 'project.source.json': project,\n 'embedded-extensions.json': {\n formatVersion: embeddedExtensionManifestFormatVersion,\n extensions: embeddedExtensions,\n },\n 'sb3-source.json': {\n formatVersion: blockPalette ? blockPaletteSourceFormatVersion : sourceFormatVersion,\n project: 'project.source.json',\n embeddedExtensions: 'embedded-extensions.json',\n assetsDirectory: 'assets',\n archiveEntries,\n ...(blockPalette ? {blockPalette: blockPaletteFile} : {}),\n },\n };\n for (const [name, value] of Object.entries(documents)) {\n files.set(name, strToU8(`${JSON.stringify(value, null, 2)}\\n`));\n }\n if (blockPalette) {\n files.set(blockPaletteFile, strToU8(serializeBlockPaletteDocument(blockPalette)));\n }\n return files;\n}\n"],"mappings":";;;;;;AAgCA,IAAa,iBAAb,cAAoC,MAAM;CAE7B;CADX,YACE,MACA,SACA,SACA;EACA,MAAM,SAAS,OAAO;EAJb,KAAA,OAAA;EAKT,KAAK,OAAO;CACd;AACF;AAmBA,SAAgB,qBAAqB,SAKnC;CACA,OACE,OAAO,YAAY,YAAY,QAAQ,WAAW,OAAO,GACzD,4CACF;CACA,MAAM,aAAa,QAAQ,QAAQ,GAAG;CACtC,OAAO,cAAc,GAAG,uDAAuD;CAE/E,MAAM,WAAW,QAAQ,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,GAAG,CAAC;CAEhE,IAAI,cACF,MAAM,IAAI,kBAAkB,QAAQ,8BAA8B,YAAY,CAAC,CAAC;CAElF,OAAO;AACT"}
|
package/dist/import.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { DirectoryComparison, GitOutputState } from './output-safety';
|
|
2
2
|
import { ExtensionEncoding } from './types';
|
|
3
|
+
import { BlockPaletteWarning } from './block-palette';
|
|
3
4
|
export { validateOutputDirectoryPath } from './output-safety';
|
|
4
5
|
export interface DecodedExtensionDataUrl {
|
|
5
6
|
encoding: ExtensionEncoding;
|
|
@@ -34,6 +35,8 @@ export interface ImportSb3Result {
|
|
|
34
35
|
inputPath: string;
|
|
35
36
|
outputDirectory: string;
|
|
36
37
|
rollbackCleanupWarning: string | null;
|
|
38
|
+
/** Block palette comments that were normalized or kept as plain comments. */
|
|
39
|
+
warnings: BlockPaletteWarning[];
|
|
37
40
|
}
|
|
38
41
|
export declare function decodeExtensionDataUrl(dataUrl: unknown): DecodedExtensionDataUrl;
|
|
39
42
|
export declare function importSb3({ inputPath, outputDirectory, protectedRoot, discardLocalChanges, yes, confirmReplace, }: ImportSb3Options): Promise<ImportSb3Result>;
|
package/dist/import.js
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
|
-
import { assert
|
|
1
|
+
import { assert } from "./assert.js";
|
|
2
2
|
import { assertNoInterruptedRollback, assertRecognizedOutputDirectory, compareDirectories, inspectGitOutputState, pathExists, replaceDirectoryTransactionally, validateOutputDirectoryPath } from "./output-safety.js";
|
|
3
|
-
import { validateArchiveEntryName } from "./archive.js";
|
|
4
3
|
import { validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
|
|
5
4
|
import { validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
6
|
-
import "./source.js";
|
|
5
|
+
import { isObject, supportedSourceFormatVersions } from "./source-format.js";
|
|
6
|
+
import { decodeExtensionBytes, expandArchive, formatSourceFiles } from "./expand-archive.js";
|
|
7
7
|
import process from "node:process";
|
|
8
8
|
import path from "node:path";
|
|
9
9
|
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
10
|
-
import { strFromU8, unzipSync } from "fflate";
|
|
11
10
|
//#region src/import.ts
|
|
12
|
-
function isObject(value) {
|
|
13
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
14
|
-
}
|
|
15
11
|
function summarizeGitChanges(gitState) {
|
|
16
12
|
const entries = [...gitState.statusEntries, ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`)];
|
|
17
13
|
return `${entries.slice(0, 8).join(", ")}${entries.length > 8 ? `, and ${entries.length - 8} more` : ""}`;
|
|
@@ -23,7 +19,7 @@ async function authorizeOutputReplacement({ candidateDirectory, confirmReplace,
|
|
|
23
19
|
comparison: null,
|
|
24
20
|
gitState: null
|
|
25
21
|
};
|
|
26
|
-
await assertRecognizedOutputDirectory(outputDirectory,
|
|
22
|
+
await assertRecognizedOutputDirectory(outputDirectory, supportedSourceFormatVersions);
|
|
27
23
|
const comparison = await compareDirectories(outputDirectory, candidateDirectory);
|
|
28
24
|
if (comparison.identical) return {
|
|
29
25
|
action: "unchanged",
|
|
@@ -58,10 +54,6 @@ async function revalidateOutputReplacement({ candidateDirectory, decision, disca
|
|
|
58
54
|
assert(latestGitState.fingerprint === decision.gitState.fingerprint, "Git state changed during SB3 import; refusing to replace the output.");
|
|
59
55
|
assert(latestGitState.clean || discardLocalChanges, "Output gained uncommitted Git changes during SB3 import; refusing to replace it.");
|
|
60
56
|
}
|
|
61
|
-
function extensionSourcePath(extensionId) {
|
|
62
|
-
assert(/^[A-Za-z0-9._-]+$/u.test(extensionId), `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`);
|
|
63
|
-
return `extensions/${extensionId}.js`;
|
|
64
|
-
}
|
|
65
57
|
async function readExistingExtensionSources(outputDirectory) {
|
|
66
58
|
if (!await pathExists(outputDirectory)) return /* @__PURE__ */ new Map();
|
|
67
59
|
const manifestPath = path.join(outputDirectory, "embedded-extensions.json");
|
|
@@ -81,31 +73,10 @@ async function readExistingExtensionSources(outputDirectory) {
|
|
|
81
73
|
return sources;
|
|
82
74
|
}
|
|
83
75
|
function decodeExtensionDataUrl(dataUrl) {
|
|
84
|
-
|
|
85
|
-
const commaIndex = dataUrl.indexOf(",");
|
|
86
|
-
assert(commaIndex >= 0, "Embedded extension data URL has no payload separator.");
|
|
87
|
-
const metadata = dataUrl.slice(5, commaIndex).split(";");
|
|
88
|
-
const mediaType = metadata.shift() || "text/plain";
|
|
89
|
-
const base64Index = metadata.indexOf("base64");
|
|
90
|
-
const encoding = base64Index >= 0 ? "base64" : "percent";
|
|
91
|
-
if (base64Index >= 0) metadata.splice(base64Index, 1);
|
|
92
|
-
const payload = dataUrl.slice(commaIndex + 1);
|
|
93
|
-
let source;
|
|
94
|
-
if (encoding === "base64") {
|
|
95
|
-
assert(/^[A-Za-z0-9+/]*={0,2}$/u.test(payload), "Embedded extension data URL contains invalid base64.");
|
|
96
|
-
const unpaddedPayload = payload.replace(/=+$/u, "");
|
|
97
|
-
assert(unpaddedPayload.length % 4 !== 1, "Embedded extension data URL contains invalid base64.");
|
|
98
|
-
source = Buffer.from(unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, "="), "base64");
|
|
99
|
-
} else try {
|
|
100
|
-
source = Buffer.from(decodeURIComponent(payload), "utf8");
|
|
101
|
-
} catch {
|
|
102
|
-
throw new Error("Embedded extension data URL contains invalid percent encoding.");
|
|
103
|
-
}
|
|
76
|
+
const decoded = decodeExtensionBytes(dataUrl);
|
|
104
77
|
return {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
parameters: metadata,
|
|
108
|
-
source
|
|
78
|
+
...decoded,
|
|
79
|
+
source: Buffer.from(decoded.source)
|
|
109
80
|
};
|
|
110
81
|
}
|
|
111
82
|
async function importSb3({ inputPath, outputDirectory, protectedRoot = process.cwd(), discardLocalChanges = false, yes = false, confirmReplace }) {
|
|
@@ -113,89 +84,33 @@ async function importSb3({ inputPath, outputDirectory, protectedRoot = process.c
|
|
|
113
84
|
assert(typeof outputDirectory === "string", "SB3 source output directory is required.");
|
|
114
85
|
const resolvedInputPath = path.resolve(inputPath);
|
|
115
86
|
const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);
|
|
116
|
-
const
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
} catch (error) {
|
|
128
|
-
throw new Error(`SB3 project.json is invalid JSON: ${errorMessage(error)}`, { cause: error });
|
|
129
|
-
}
|
|
130
|
-
assert(isObject(project), "SB3 project.json must contain a JSON object.");
|
|
131
|
-
const projectJson = project;
|
|
132
|
-
const extensionUrls = projectJson.extensionURLs ?? {};
|
|
133
|
-
assert(isObject(extensionUrls), "SB3 project.json extensionURLs must be an object when present.");
|
|
134
|
-
const existingExtensionSources = await readExistingExtensionSources(resolvedOutputDirectory);
|
|
135
|
-
const embeddedExtensions = [];
|
|
136
|
-
const decodedExtensionSources = [];
|
|
137
|
-
for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {
|
|
138
|
-
if (typeof extensionUrl !== "string" || !extensionUrl.startsWith("data:")) continue;
|
|
139
|
-
const sourcePath = extensionSourcePath(extensionId);
|
|
140
|
-
const decoded = decodeExtensionDataUrl(extensionUrl);
|
|
141
|
-
extensionUrls[extensionId] = `embedded-extension:${sourcePath}`;
|
|
142
|
-
const extension = {
|
|
143
|
-
id: extensionId,
|
|
144
|
-
path: sourcePath,
|
|
145
|
-
mediaType: decoded.mediaType,
|
|
146
|
-
parameters: decoded.parameters,
|
|
147
|
-
encoding: decoded.encoding
|
|
148
|
-
};
|
|
149
|
-
const existingSource = existingExtensionSources.get(`${extensionId}\u0000${sourcePath}`);
|
|
150
|
-
let existingApiManifestContents = null;
|
|
151
|
-
if (existingSource !== void 0) {
|
|
152
|
-
extension.source = structuredClone(existingSource);
|
|
153
|
-
validateManagedExtensionContents(extension, decoded.source);
|
|
154
|
-
if (extension.source.apiManifest) {
|
|
155
|
-
existingApiManifestContents = await readFile(path.join(resolvedOutputDirectory, extension.source.apiManifest.path));
|
|
156
|
-
validateManagedExtensionApiManifest(extension, existingApiManifestContents);
|
|
157
|
-
}
|
|
87
|
+
const expanded = expandArchive(await readFile(resolvedInputPath));
|
|
88
|
+
const existingSources = await readExistingExtensionSources(resolvedOutputDirectory);
|
|
89
|
+
for (const extension of expanded.embeddedExtensions) {
|
|
90
|
+
const source = existingSources.get(`${extension.id}\u0000${extension.path}`);
|
|
91
|
+
if (source === void 0) continue;
|
|
92
|
+
extension.source = structuredClone(source);
|
|
93
|
+
validateManagedExtensionContents(extension, expanded.extensionFiles.get(extension.path));
|
|
94
|
+
if (extension.source.apiManifest) {
|
|
95
|
+
const contents = await readFile(path.join(resolvedOutputDirectory, extension.source.apiManifest.path));
|
|
96
|
+
validateManagedExtensionApiManifest(extension, contents);
|
|
97
|
+
expanded.extensionFiles.set(extension.source.apiManifest.path, contents);
|
|
158
98
|
}
|
|
159
|
-
embeddedExtensions.push(extension);
|
|
160
|
-
decodedExtensionSources.push({
|
|
161
|
-
path: sourcePath,
|
|
162
|
-
source: decoded.source
|
|
163
|
-
});
|
|
164
|
-
if (existingApiManifestContents && extension.source?.apiManifest) decodedExtensionSources.push({
|
|
165
|
-
path: extension.source.apiManifest.path,
|
|
166
|
-
source: existingApiManifestContents
|
|
167
|
-
});
|
|
168
99
|
}
|
|
100
|
+
let decision;
|
|
101
|
+
let rollbackCleanupWarning = null;
|
|
169
102
|
const outputParent = path.dirname(resolvedOutputDirectory);
|
|
170
103
|
await mkdir(outputParent, { recursive: true });
|
|
171
104
|
const temporaryDirectory = await mkdtemp(path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`));
|
|
172
105
|
try {
|
|
173
|
-
|
|
174
|
-
await mkdir(assetsDirectory, { recursive: true });
|
|
106
|
+
await mkdir(path.join(temporaryDirectory, "assets"), { recursive: true });
|
|
175
107
|
await mkdir(path.join(temporaryDirectory, "extensions"), { recursive: true });
|
|
176
|
-
for (const [
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
await
|
|
181
|
-
await writeFile(assetPath, contents);
|
|
108
|
+
for (const [name, contents] of formatSourceFiles(expanded)) {
|
|
109
|
+
const outputPath = path.resolve(temporaryDirectory, name);
|
|
110
|
+
assert(outputPath.startsWith(`${temporaryDirectory}${path.sep}`), `SB3 archive entry escapes the source directory: ${JSON.stringify(name)}`);
|
|
111
|
+
await mkdir(path.dirname(outputPath), { recursive: true });
|
|
112
|
+
await writeFile(outputPath, contents);
|
|
182
113
|
}
|
|
183
|
-
for (const extension of decodedExtensionSources) await writeFile(path.join(temporaryDirectory, extension.path), extension.source);
|
|
184
|
-
const sourceManifest = {
|
|
185
|
-
formatVersion: 1,
|
|
186
|
-
project: "project.source.json",
|
|
187
|
-
embeddedExtensions: "embedded-extensions.json",
|
|
188
|
-
assetsDirectory: "assets",
|
|
189
|
-
archiveEntries: archiveEntries.map(([entryName]) => entryName)
|
|
190
|
-
};
|
|
191
|
-
await Promise.all([
|
|
192
|
-
writeFile(path.join(temporaryDirectory, "project.source.json"), `${JSON.stringify(projectJson, null, 2)}\n`),
|
|
193
|
-
writeFile(path.join(temporaryDirectory, "embedded-extensions.json"), `${JSON.stringify({
|
|
194
|
-
formatVersion: 1,
|
|
195
|
-
extensions: embeddedExtensions
|
|
196
|
-
}, null, 2)}\n`),
|
|
197
|
-
writeFile(path.join(temporaryDirectory, "sb3-source.json"), `${JSON.stringify(sourceManifest, null, 2)}\n`)
|
|
198
|
-
]);
|
|
199
114
|
decision = await authorizeOutputReplacement({
|
|
200
115
|
candidateDirectory: temporaryDirectory,
|
|
201
116
|
confirmReplace,
|
|
@@ -224,9 +139,9 @@ async function importSb3({ inputPath, outputDirectory, protectedRoot = process.c
|
|
|
224
139
|
throw error;
|
|
225
140
|
}
|
|
226
141
|
return {
|
|
227
|
-
archiveEntryCount: archiveEntries.length,
|
|
228
|
-
assetCount:
|
|
229
|
-
embeddedExtensionCount: embeddedExtensions.length,
|
|
142
|
+
archiveEntryCount: expanded.archiveEntries.length,
|
|
143
|
+
assetCount: expanded.assets.size,
|
|
144
|
+
embeddedExtensionCount: expanded.embeddedExtensions.length,
|
|
230
145
|
changed: decision.action !== "unchanged",
|
|
231
146
|
differenceCounts: decision.comparison ? {
|
|
232
147
|
added: decision.comparison.differences.added.length,
|
|
@@ -235,7 +150,8 @@ async function importSb3({ inputPath, outputDirectory, protectedRoot = process.c
|
|
|
235
150
|
} : null,
|
|
236
151
|
inputPath: resolvedInputPath,
|
|
237
152
|
outputDirectory: resolvedOutputDirectory,
|
|
238
|
-
rollbackCleanupWarning
|
|
153
|
+
rollbackCleanupWarning,
|
|
154
|
+
warnings: expanded.blockPaletteWarnings
|
|
239
155
|
};
|
|
240
156
|
}
|
|
241
157
|
//#endregion
|
package/dist/import.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"import.js","names":[],"sources":["../src/import.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\nimport {strFromU8, unzipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateManagedExtensionContents} from './extension-dependencies';\nimport {\n assertNoInterruptedRollback,\n assertRecognizedOutputDirectory,\n compareDirectories,\n inspectGitOutputState,\n pathExists,\n replaceDirectoryTransactionally,\n validateOutputDirectoryPath,\n} from './output-safety';\nimport type {DirectoryComparison, GitOutputState} from './output-safety';\nimport {sourceFormatVersion} from './source';\nimport type {\n EmbeddedExtension,\n ExtensionEncoding,\n ExtensionSource,\n ProjectJson,\n UnknownRecord,\n} from './types';\n\nexport {validateOutputDirectoryPath} from './output-safety';\n\nexport interface DecodedExtensionDataUrl {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Buffer;\n}\n\nexport interface OutputReplacementContext {\n comparison: DirectoryComparison;\n discardLocalChanges: boolean;\n gitState: GitOutputState;\n outputDirectory: string;\n}\n\ninterface OutputReplacementDecision {\n action: 'create' | 'unchanged' | 'replace';\n comparison: DirectoryComparison | null;\n discardLocalChanges?: boolean;\n gitState: GitOutputState | null;\n outputDirectory?: string;\n}\n\nexport interface ImportSb3Options {\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges?: boolean;\n inputPath: string;\n outputDirectory: string;\n protectedRoot?: string;\n yes?: boolean;\n}\n\nexport interface ImportSb3Result {\n archiveEntryCount: number;\n assetCount: number;\n changed: boolean;\n differenceCounts: {added: number; modified: number; removed: number} | null;\n embeddedExtensionCount: number;\n inputPath: string;\n outputDirectory: string;\n rollbackCleanupWarning: string | null;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction summarizeGitChanges(gitState: GitOutputState): string {\n const entries = [\n ...gitState.statusEntries,\n ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`),\n ];\n const visibleEntries = entries.slice(0, 8).join(', ');\n const remainder = entries.length > 8 ? `, and ${entries.length - 8} more` : '';\n return `${visibleEntries}${remainder}`;\n}\n\nasync function authorizeOutputReplacement({\n candidateDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory,\n yes,\n}: {\n candidateDirectory: string;\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges: boolean;\n outputDirectory: string;\n yes: boolean;\n}): Promise<OutputReplacementDecision> {\n await assertNoInterruptedRollback(outputDirectory);\n if (!(await pathExists(outputDirectory))) {\n return {action: 'create', comparison: null, gitState: null};\n }\n\n await assertRecognizedOutputDirectory(outputDirectory, sourceFormatVersion);\n const comparison = await compareDirectories(outputDirectory, candidateDirectory);\n if (comparison.identical) {\n return {action: 'unchanged', comparison, gitState: null};\n }\n\n const gitState = await inspectGitOutputState(outputDirectory, comparison.existingFilePaths);\n assert(\n gitState.managed,\n `Existing output differs from the SB3 candidate but is not tracked by Git: ${outputDirectory}. ` +\n 'Import to a new output directory instead of replacing unrecoverable content.',\n );\n assert(\n gitState.clean || discardLocalChanges,\n `Existing output differs from the SB3 candidate and has uncommitted Git changes: ` +\n `${summarizeGitChanges(gitState)}. Commit or stash them first, or explicitly use ` +\n '--discard-local-changes.',\n );\n\n const context = {\n comparison,\n discardLocalChanges,\n gitState,\n outputDirectory,\n };\n if (yes) {\n return {action: 'replace', ...context};\n }\n assert(\n typeof confirmReplace === 'function',\n `Output directory already exists: ${outputDirectory}. ` +\n 'Refusing to replace differing content without interactive confirmation or --yes.',\n );\n assert(\n await confirmReplace(context),\n 'SB3 import cancelled; the existing output was not changed.',\n );\n return {action: 'replace', ...context};\n}\n\nasync function revalidateOutputReplacement({\n candidateDirectory,\n decision,\n discardLocalChanges,\n outputDirectory,\n}: {\n candidateDirectory: string;\n decision: OutputReplacementContext;\n discardLocalChanges: boolean;\n outputDirectory: string;\n}): Promise<void> {\n const latestComparison = await compareDirectories(outputDirectory, candidateDirectory);\n assert(\n latestComparison.existingFingerprint === decision.comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === decision.comparison.candidateFingerprint,\n 'Output or candidate content changed during SB3 import; refusing to replace it.',\n );\n const latestGitState = await inspectGitOutputState(\n outputDirectory,\n latestComparison.existingFilePaths,\n );\n assert(\n latestGitState.managed,\n 'Output stopped being Git-managed during SB3 import; refusing to replace it.',\n );\n assert(\n latestGitState.fingerprint === decision.gitState.fingerprint,\n 'Git state changed during SB3 import; refusing to replace the output.',\n );\n assert(\n latestGitState.clean || discardLocalChanges,\n 'Output gained uncommitted Git changes during SB3 import; refusing to replace it.',\n );\n}\n\nfunction extensionSourcePath(extensionId: string): string {\n assert(\n /^[A-Za-z0-9._-]+$/u.test(extensionId),\n `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`,\n );\n return `extensions/${extensionId}.js`;\n}\n\nasync function readExistingExtensionSources(\n outputDirectory: string,\n): Promise<Map<string, ExtensionSource>> {\n if (!(await pathExists(outputDirectory))) {\n return new Map();\n }\n\n const manifestPath = path.join(outputDirectory, 'embedded-extensions.json');\n if (!(await pathExists(manifestPath))) {\n return new Map();\n }\n\n let manifest: unknown;\n try {\n manifest = JSON.parse(await readFile(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(`Existing embedded extension manifest is not valid JSON: ${manifestPath}`, {\n cause: error,\n });\n }\n assert(\n isObject(manifest) && Array.isArray(manifest.extensions),\n `Existing embedded extension manifest is invalid: ${manifestPath}`,\n );\n\n const sources = new Map<string, ExtensionSource>();\n for (const extension of manifest.extensions as unknown[]) {\n if (\n !isObject(extension) ||\n typeof extension.id !== 'string' ||\n typeof extension.path !== 'string' ||\n extension.source === undefined\n ) {\n continue;\n }\n sources.set(`${extension.id}\\u0000${extension.path}`, extension.source as ExtensionSource);\n }\n return sources;\n}\n\nexport function decodeExtensionDataUrl(dataUrl: unknown): DecodedExtensionDataUrl {\n assert(\n typeof dataUrl === 'string' && dataUrl.startsWith('data:'),\n 'Embedded extension URL must be a data URL.',\n );\n const commaIndex = dataUrl.indexOf(',');\n assert(commaIndex >= 0, 'Embedded extension data URL has no payload separator.');\n\n const metadata = dataUrl.slice('data:'.length, commaIndex).split(';');\n const mediaType = metadata.shift() || 'text/plain';\n const base64Index = metadata.indexOf('base64');\n const encoding: ExtensionEncoding = base64Index >= 0 ? 'base64' : 'percent';\n if (base64Index >= 0) {\n metadata.splice(base64Index, 1);\n }\n\n const payload = dataUrl.slice(commaIndex + 1);\n let source: Buffer;\n if (encoding === 'base64') {\n assert(\n /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),\n 'Embedded extension data URL contains invalid base64.',\n );\n const unpaddedPayload = payload.replace(/=+$/u, '');\n assert(\n unpaddedPayload.length % 4 !== 1,\n 'Embedded extension data URL contains invalid base64.',\n );\n source = Buffer.from(\n unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, '='),\n 'base64',\n );\n } else {\n try {\n source = Buffer.from(decodeURIComponent(payload), 'utf8');\n } catch {\n throw new Error('Embedded extension data URL contains invalid percent encoding.');\n }\n }\n\n return {\n encoding,\n mediaType,\n parameters: metadata,\n source,\n };\n}\n\nexport async function importSb3({\n inputPath,\n outputDirectory,\n protectedRoot = process.cwd(),\n discardLocalChanges = false,\n yes = false,\n confirmReplace,\n}: ImportSb3Options): Promise<ImportSb3Result> {\n assert(typeof inputPath === 'string', 'Input SB3 path is required.');\n assert(typeof outputDirectory === 'string', 'SB3 source output directory is required.');\n const resolvedInputPath = path.resolve(inputPath);\n const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);\n\n const archive = unzipSync(new Uint8Array(await readFile(resolvedInputPath)));\n const archiveEntries = Object.entries(archive);\n assert(archiveEntries.length > 0, 'SB3 archive is empty.');\n for (const [entryName] of archiveEntries) {\n validateArchiveEntryName(entryName);\n }\n\n const projectEntry = archive['project.json'];\n assert(projectEntry, 'SB3 archive does not contain project.json.');\n\n let project: unknown;\n let decision: OutputReplacementDecision | undefined;\n let rollbackCleanupWarning: string | null = null;\n try {\n project = JSON.parse(strFromU8(projectEntry));\n } catch (error) {\n throw new Error(`SB3 project.json is invalid JSON: ${errorMessage(error)}`, {cause: error});\n }\n assert(isObject(project), 'SB3 project.json must contain a JSON object.');\n const projectJson: ProjectJson = project;\n\n const extensionUrls: unknown = projectJson.extensionURLs ?? {};\n assert(isObject(extensionUrls), 'SB3 project.json extensionURLs must be an object when present.');\n\n const existingExtensionSources = await readExistingExtensionSources(resolvedOutputDirectory);\n const embeddedExtensions: EmbeddedExtension[] = [];\n const decodedExtensionSources: {path: string; source: Buffer}[] = [];\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n if (typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:')) {\n continue;\n }\n const sourcePath = extensionSourcePath(extensionId);\n const decoded = decodeExtensionDataUrl(extensionUrl);\n extensionUrls[extensionId] = `embedded-extension:${sourcePath}`;\n const extension: EmbeddedExtension = {\n id: extensionId,\n path: sourcePath,\n mediaType: decoded.mediaType,\n parameters: decoded.parameters,\n encoding: decoded.encoding,\n };\n const existingSource = existingExtensionSources.get(`${extensionId}\\u0000${sourcePath}`);\n let existingApiManifestContents: Buffer | null = null;\n if (existingSource !== undefined) {\n extension.source = structuredClone(existingSource);\n validateManagedExtensionContents(extension, decoded.source);\n if (extension.source.apiManifest) {\n existingApiManifestContents = await readFile(\n path.join(resolvedOutputDirectory, extension.source.apiManifest.path),\n );\n validateManagedExtensionApiManifest(extension, existingApiManifestContents);\n }\n }\n embeddedExtensions.push(extension);\n decodedExtensionSources.push({path: sourcePath, source: decoded.source});\n if (existingApiManifestContents && extension.source?.apiManifest) {\n decodedExtensionSources.push({\n path: extension.source.apiManifest.path,\n source: existingApiManifestContents,\n });\n }\n }\n\n const outputParent = path.dirname(resolvedOutputDirectory);\n await mkdir(outputParent, {recursive: true});\n const temporaryDirectory = await mkdtemp(\n path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`),\n );\n\n try {\n const assetsDirectory = path.join(temporaryDirectory, 'assets');\n await mkdir(assetsDirectory, {recursive: true});\n await mkdir(path.join(temporaryDirectory, 'extensions'), {recursive: true});\n\n for (const [entryName, contents] of archiveEntries) {\n if (entryName === 'project.json' || entryName.endsWith('/')) {\n continue;\n }\n const assetPath = path.resolve(assetsDirectory, entryName);\n assert(\n assetPath.startsWith(`${assetsDirectory}${path.sep}`),\n `SB3 archive entry escapes the assets directory: ${JSON.stringify(entryName)}`,\n );\n await mkdir(path.dirname(assetPath), {recursive: true});\n await writeFile(assetPath, contents);\n }\n\n for (const extension of decodedExtensionSources) {\n await writeFile(path.join(temporaryDirectory, extension.path), extension.source);\n }\n\n const sourceManifest = {\n formatVersion: sourceFormatVersion,\n project: 'project.source.json',\n embeddedExtensions: 'embedded-extensions.json',\n assetsDirectory: 'assets',\n archiveEntries: archiveEntries.map(([entryName]) => entryName),\n };\n await Promise.all([\n writeFile(\n path.join(temporaryDirectory, 'project.source.json'),\n `${JSON.stringify(projectJson, null, 2)}\\n`,\n ),\n writeFile(\n path.join(temporaryDirectory, 'embedded-extensions.json'),\n `${JSON.stringify({formatVersion: sourceFormatVersion, extensions: embeddedExtensions}, null, 2)}\\n`,\n ),\n writeFile(\n path.join(temporaryDirectory, 'sb3-source.json'),\n `${JSON.stringify(sourceManifest, null, 2)}\\n`,\n ),\n ]);\n decision = await authorizeOutputReplacement({\n candidateDirectory: temporaryDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n yes,\n });\n if (decision.action === 'unchanged') {\n await rm(temporaryDirectory, {recursive: true, force: true});\n } else {\n if (decision.action === 'replace') {\n await revalidateOutputReplacement({\n candidateDirectory: temporaryDirectory,\n decision: decision as OutputReplacementContext,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n });\n }\n ({rollbackCleanupWarning} = await replaceDirectoryTransactionally(\n temporaryDirectory,\n resolvedOutputDirectory,\n ));\n }\n } catch (error) {\n await rm(temporaryDirectory, {recursive: true, force: true});\n throw error;\n }\n\n return {\n archiveEntryCount: archiveEntries.length,\n assetCount: archiveEntries.filter(\n ([entryName]) => entryName !== 'project.json' && !entryName.endsWith('/'),\n ).length,\n embeddedExtensionCount: embeddedExtensions.length,\n changed: decision.action !== 'unchanged',\n differenceCounts: decision.comparison\n ? {\n added: decision.comparison.differences.added.length,\n modified: decision.comparison.differences.modified.length,\n removed: decision.comparison.differences.removed.length,\n }\n : null,\n inputPath: resolvedInputPath,\n outputDirectory: resolvedOutputDirectory,\n rollbackCleanupWarning,\n };\n}\n"],"mappings":";;;;;;;;;;;AA2EA,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UA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AAU,gBAAgB,MAAM,CAAC,EAAE,GAC7C;EACF,CAAC;EACD,WAAW,MAAM,2BAA2B;GAC1C,oBAAoB;GACpB;GACA;GACA,iBAAiB;GACjB;EACF,CAAC;EACD,IAAI,SAAS,WAAW,aACtB,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;OACtD;GACL,IAAI,SAAS,WAAW,WACtB,MAAM,4BAA4B;IAChC,oBAAoB;IACV;IACV;IACA,iBAAiB;GACnB,CAAC;GAEH,CAAC,CAAC,0BAA0B,MAAM,gCAChC,oBACA,uBACF;EACF;CACF,SAAS,OAAO;EACd,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;EAC3D,MAAM;CACR;CAEA,OAAO;EACL,mBAAmB,eAAe;EAClC,YAAY,eAAe,QACxB,CAAC,eAAe,cAAc,kBAAkB,CAAC,UAAU,SAAS,GAAG,CAC1E,CAAC,CAAC;EACF,wBAAwB,mBAAmB;EAC3C,SAAS,SAAS,WAAW;EAC7B,kBAAkB,SAAS,aACvB;GACE,OAAO,SAAS,WAAW,YAAY,MAAM;GAC7C,UAAU,SAAS,WAAW,YAAY,SAAS;GACnD,SAAS,SAAS,WAAW,YAAY,QAAQ;EACnD,IACA;EACJ,WAAW;EACX,iBAAiB;EACjB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"import.js","names":[],"sources":["../src/import.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\nimport {assert} from './assert';\nimport {decodeExtensionBytes, expandArchive, formatSourceFiles} from './expand-archive';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateManagedExtensionContents} from './extension-dependencies';\nimport {\n assertNoInterruptedRollback,\n assertRecognizedOutputDirectory,\n compareDirectories,\n inspectGitOutputState,\n pathExists,\n replaceDirectoryTransactionally,\n validateOutputDirectoryPath,\n} from './output-safety';\nimport type {DirectoryComparison, GitOutputState} from './output-safety';\nimport {isObject, supportedSourceFormatVersions} from './source-format';\nimport type {ExtensionEncoding, ExtensionSource} from './types';\nimport type {BlockPaletteWarning} from './block-palette';\n\nexport {validateOutputDirectoryPath} from './output-safety';\n\nexport interface DecodedExtensionDataUrl {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Buffer;\n}\n\nexport interface OutputReplacementContext {\n comparison: DirectoryComparison;\n discardLocalChanges: boolean;\n gitState: GitOutputState;\n outputDirectory: string;\n}\n\ninterface OutputReplacementDecision {\n action: 'create' | 'unchanged' | 'replace';\n comparison: DirectoryComparison | null;\n discardLocalChanges?: boolean;\n gitState: GitOutputState | null;\n outputDirectory?: string;\n}\n\nexport interface ImportSb3Options {\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges?: boolean;\n inputPath: string;\n outputDirectory: string;\n protectedRoot?: string;\n yes?: boolean;\n}\n\nexport interface ImportSb3Result {\n archiveEntryCount: number;\n assetCount: number;\n changed: boolean;\n differenceCounts: {added: number; modified: number; removed: number} | null;\n embeddedExtensionCount: number;\n inputPath: string;\n outputDirectory: string;\n rollbackCleanupWarning: string | null;\n /** Block palette comments that were normalized or kept as plain comments. */\n warnings: BlockPaletteWarning[];\n}\n\nfunction summarizeGitChanges(gitState: GitOutputState): string {\n const entries = [\n ...gitState.statusEntries,\n ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`),\n ];\n const visibleEntries = entries.slice(0, 8).join(', ');\n const remainder = entries.length > 8 ? `, and ${entries.length - 8} more` : '';\n return `${visibleEntries}${remainder}`;\n}\n\nasync function authorizeOutputReplacement({\n candidateDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory,\n yes,\n}: {\n candidateDirectory: string;\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges: boolean;\n outputDirectory: string;\n yes: boolean;\n}): Promise<OutputReplacementDecision> {\n await assertNoInterruptedRollback(outputDirectory);\n if (!(await pathExists(outputDirectory))) {\n return {action: 'create', comparison: null, gitState: null};\n }\n\n await assertRecognizedOutputDirectory(outputDirectory, supportedSourceFormatVersions);\n const comparison = await compareDirectories(outputDirectory, candidateDirectory);\n if (comparison.identical) {\n return {action: 'unchanged', comparison, gitState: null};\n }\n\n const gitState = await inspectGitOutputState(outputDirectory, comparison.existingFilePaths);\n assert(\n gitState.managed,\n `Existing output differs from the SB3 candidate but is not tracked by Git: ${outputDirectory}. ` +\n 'Import to a new output directory instead of replacing unrecoverable content.',\n );\n assert(\n gitState.clean || discardLocalChanges,\n `Existing output differs from the SB3 candidate and has uncommitted Git changes: ` +\n `${summarizeGitChanges(gitState)}. Commit or stash them first, or explicitly use ` +\n '--discard-local-changes.',\n );\n\n const context = {\n comparison,\n discardLocalChanges,\n gitState,\n outputDirectory,\n };\n if (yes) {\n return {action: 'replace', ...context};\n }\n assert(\n typeof confirmReplace === 'function',\n `Output directory already exists: ${outputDirectory}. ` +\n 'Refusing to replace differing content without interactive confirmation or --yes.',\n );\n assert(\n await confirmReplace(context),\n 'SB3 import cancelled; the existing output was not changed.',\n );\n return {action: 'replace', ...context};\n}\n\nasync function revalidateOutputReplacement({\n candidateDirectory,\n decision,\n discardLocalChanges,\n outputDirectory,\n}: {\n candidateDirectory: string;\n decision: OutputReplacementContext;\n discardLocalChanges: boolean;\n outputDirectory: string;\n}): Promise<void> {\n const latestComparison = await compareDirectories(outputDirectory, candidateDirectory);\n assert(\n latestComparison.existingFingerprint === decision.comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === decision.comparison.candidateFingerprint,\n 'Output or candidate content changed during SB3 import; refusing to replace it.',\n );\n const latestGitState = await inspectGitOutputState(\n outputDirectory,\n latestComparison.existingFilePaths,\n );\n assert(\n latestGitState.managed,\n 'Output stopped being Git-managed during SB3 import; refusing to replace it.',\n );\n assert(\n latestGitState.fingerprint === decision.gitState.fingerprint,\n 'Git state changed during SB3 import; refusing to replace the output.',\n );\n assert(\n latestGitState.clean || discardLocalChanges,\n 'Output gained uncommitted Git changes during SB3 import; refusing to replace it.',\n );\n}\n\nasync function readExistingExtensionSources(\n outputDirectory: string,\n): Promise<Map<string, ExtensionSource>> {\n if (!(await pathExists(outputDirectory))) {\n return new Map();\n }\n\n const manifestPath = path.join(outputDirectory, 'embedded-extensions.json');\n if (!(await pathExists(manifestPath))) {\n return new Map();\n }\n\n let manifest: unknown;\n try {\n manifest = JSON.parse(await readFile(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(`Existing embedded extension manifest is not valid JSON: ${manifestPath}`, {\n cause: error,\n });\n }\n assert(\n isObject(manifest) && Array.isArray(manifest.extensions),\n `Existing embedded extension manifest is invalid: ${manifestPath}`,\n );\n\n const sources = new Map<string, ExtensionSource>();\n for (const extension of manifest.extensions as unknown[]) {\n if (\n !isObject(extension) ||\n typeof extension.id !== 'string' ||\n typeof extension.path !== 'string' ||\n extension.source === undefined\n ) {\n continue;\n }\n sources.set(`${extension.id}\\u0000${extension.path}`, extension.source as ExtensionSource);\n }\n return sources;\n}\n\nexport function decodeExtensionDataUrl(dataUrl: unknown): DecodedExtensionDataUrl {\n const decoded = decodeExtensionBytes(dataUrl);\n return {...decoded, source: Buffer.from(decoded.source)};\n}\n\nexport async function importSb3({\n inputPath,\n outputDirectory,\n protectedRoot = process.cwd(),\n discardLocalChanges = false,\n yes = false,\n confirmReplace,\n}: ImportSb3Options): Promise<ImportSb3Result> {\n assert(typeof inputPath === 'string', 'Input SB3 path is required.');\n assert(typeof outputDirectory === 'string', 'SB3 source output directory is required.');\n const resolvedInputPath = path.resolve(inputPath);\n const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);\n\n const expanded = expandArchive(await readFile(resolvedInputPath));\n const existingSources = await readExistingExtensionSources(resolvedOutputDirectory);\n for (const extension of expanded.embeddedExtensions) {\n const source = existingSources.get(`${extension.id}\\u0000${extension.path}`);\n if (source === undefined) continue;\n extension.source = structuredClone(source);\n validateManagedExtensionContents(extension, expanded.extensionFiles.get(extension.path)!);\n if (extension.source.apiManifest) {\n const contents = await readFile(\n path.join(resolvedOutputDirectory, extension.source.apiManifest.path),\n );\n validateManagedExtensionApiManifest(extension, contents);\n expanded.extensionFiles.set(extension.source.apiManifest.path, contents);\n }\n }\n let decision: OutputReplacementDecision | undefined;\n let rollbackCleanupWarning: string | null = null;\n\n const outputParent = path.dirname(resolvedOutputDirectory);\n await mkdir(outputParent, {recursive: true});\n const temporaryDirectory = await mkdtemp(\n path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`),\n );\n\n try {\n await mkdir(path.join(temporaryDirectory, 'assets'), {recursive: true});\n await mkdir(path.join(temporaryDirectory, 'extensions'), {recursive: true});\n for (const [name, contents] of formatSourceFiles(expanded)) {\n const outputPath = path.resolve(temporaryDirectory, name);\n assert(\n outputPath.startsWith(`${temporaryDirectory}${path.sep}`),\n `SB3 archive entry escapes the source directory: ${JSON.stringify(name)}`,\n );\n await mkdir(path.dirname(outputPath), {recursive: true});\n await writeFile(outputPath, contents);\n }\n decision = await authorizeOutputReplacement({\n candidateDirectory: temporaryDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n yes,\n });\n if (decision.action === 'unchanged') {\n await rm(temporaryDirectory, {recursive: true, force: true});\n } else {\n if (decision.action === 'replace') {\n await revalidateOutputReplacement({\n candidateDirectory: temporaryDirectory,\n decision: decision as OutputReplacementContext,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n });\n }\n ({rollbackCleanupWarning} = await replaceDirectoryTransactionally(\n temporaryDirectory,\n resolvedOutputDirectory,\n ));\n }\n } catch (error) {\n await rm(temporaryDirectory, {recursive: true, force: true});\n throw error;\n }\n\n return {\n archiveEntryCount: expanded.archiveEntries.length,\n assetCount: expanded.assets.size,\n embeddedExtensionCount: expanded.embeddedExtensions.length,\n changed: decision.action !== 'unchanged',\n differenceCounts: decision.comparison\n ? {\n added: decision.comparison.differences.added.length,\n modified: decision.comparison.differences.modified.length,\n removed: decision.comparison.differences.removed.length,\n }\n : null,\n inputPath: resolvedInputPath,\n outputDirectory: resolvedOutputDirectory,\n rollbackCleanupWarning,\n warnings: expanded.blockPaletteWarnings,\n };\n}\n"],"mappings":";;;;;;;;;;AAsEA,SAAS,oBAAoB,UAAkC;CAC7D,MAAM,UAAU,CACd,GAAG,SAAS,eACZ,GAAG,SAAS,iBAAiB,KAAK,UAAU,gBAAgB,OAAO,CACrE;CAGA,OAAO,GAFgB,QAAQ,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,IAEtC,IADQ,QAAQ,SAAS,IAAI,SAAS,QAAQ,SAAS,EAAE,SAAS;AAE9E;AAEA,eAAe,2BAA2B,EACxC,oBACA,gBACA,qBACA,iBACA,OAOqC;CACrC,MAAM,4BAA4B,eAAe;CACjD,IAAI,CAAE,MAAM,WAAW,eAAe,GACpC,OAAO;EAAC,QAAQ;EAAU,YAAY;EAAM,UAAU;CAAI;CAG5D,MAAM,gCAAgC,iBAAiB,6BAA6B;CACpF,MAAM,aAAa,MAAM,mBAAmB,iBAAiB,kBAAkB;CAC/E,IAAI,WAAW,WACb,OAAO;EAAC,QAAQ;EAAa;EAAY,UAAU;CAAI;CAGzD,MAAM,WAAW,MAAM,sBAAsB,iBAAiB,WAAW,iBAAiB;CAC1F,OACE,SAAS,SACT,6EAA6E,gBAAgB,+EAE/F;CACA,OACE,SAAS,SAAS,qBAClB,mFACK,oBAAoB,QAAQ,EAAE,yEAErC;CAEA,MAAM,UAAU;EACd;EACA;EACA;EACA;CACF;CACA,IAAI,KACF,OAAO;EAAC,QAAQ;EAAW,GAAG;CAAO;CAEvC,OACE,OAAO,mBAAmB,YAC1B,oCAAoC,gBAAgB,mFAEtD;CACA,OACE,MAAM,eAAe,OAAO,GAC5B,4DACF;CACA,OAAO;EAAC,QAAQ;EAAW,GAAG;CAAO;AACvC;AAEA,eAAe,4BAA4B,EACzC,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D,OACE,WAAW,WAAW,GAAG,qBAAqB,KAAK,KAAK,GACxD,mDAAmD,KAAK,UAAU,IAAI,GACxE;GACA,MAAM,MAAM,KAAK,QAAQ,UAAU,GAAG,EAAC,WAAW,KAAI,CAAC;GACvD,MAAM,UAAU,YAAY,QAAQ;EACtC;EACA,WAAW,MAAM,2BAA2B;GAC1C,oBAAoB;GACpB;GACA;GACA,iBAAiB;GACjB;EACF,CAAC;EACD,IAAI,SAAS,WAAW,aACtB,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;OACtD;GACL,IAAI,SAAS,WAAW,WACtB,MAAM,4BAA4B;IAChC,oBAAoB;IACV;IACV;IACA,iBAAiB;GACnB,CAAC;GAEH,CAAC,CAAC,0BAA0B,MAAM,gCAChC,oBACA,uBACF;EACF;CACF,SAAS,OAAO;EACd,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;EAC3D,MAAM;CACR;CAEA,OAAO;EACL,mBAAmB,SAAS,eAAe;EAC3C,YAAY,SAAS,OAAO;EAC5B,wBAAwB,SAAS,mBAAmB;EACpD,SAAS,SAAS,WAAW;EAC7B,kBAAkB,SAAS,aACvB;GACE,OAAO,SAAS,WAAW,YAAY,MAAM;GAC7C,UAAU,SAAS,WAAW,YAAY,SAAS;GACnD,SAAS,SAAS,WAAW,YAAY,QAAQ;EACnD,IACA;EACJ,WAAW;EACX,iBAAiB;EACjB;EACA,UAAU,SAAS;CACrB;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionBundleMetadata, ExtensionEncoding, ExtensionModuleSource, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types';
|
|
2
2
|
export { assert } from './assert';
|
|
3
3
|
export { validateArchiveEntryName } from './archive';
|
|
4
|
+
export { blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, formatBlockPaletteComment, serializeBlockPaletteDocument, validateBlockPaletteDocument, } from './block-palette';
|
|
5
|
+
export type { BlockPaletteDocument, BlockPaletteSet, BlockPaletteTargetSetting, BlockPaletteWarning, BlockPaletteWarningCode, } from './block-palette';
|
|
4
6
|
export { buildSb3 } from './build';
|
|
5
7
|
export { cleanUpSb3, cleanUpSb3Archive } from './clean-up-sb3';
|
|
6
8
|
export type { CleanUpSb3ArchiveResult, CleanUpSb3Options, CleanUpSb3Result } from './clean-up-sb3';
|
|
@@ -18,7 +20,7 @@ export { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId, }
|
|
|
18
20
|
export { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions, } from './extension-sync';
|
|
19
21
|
export { decodeExtensionDataUrl, importSb3 } from './import';
|
|
20
22
|
export { compareDirectories, inspectGitOutputState, validateOutputDirectoryPath, } from './output-safety';
|
|
21
|
-
export { createDeterministicSb3, fixedZipTimestamp, sourceFormatVersion, validateSb3Source, } from './source';
|
|
23
|
+
export { createDeterministicSb3, blockPaletteSourceFormatVersion, fixedZipTimestamp, sourceFormatVersion, supportedSourceFormatVersions, validateSb3Source, } from './source';
|
|
22
24
|
export { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion, } from './project-asset-additions';
|
|
23
25
|
export { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate, } from './release-snapshot';
|
|
24
26
|
export { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from './turbowarp-clean-up';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assert } from "./assert.js";
|
|
2
2
|
import { compareDirectories, inspectGitOutputState, validateOutputDirectoryPath } from "./output-safety.js";
|
|
3
|
+
import { blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, formatBlockPaletteComment, serializeBlockPaletteDocument, validateBlockPaletteDocument } from "./block-palette.js";
|
|
3
4
|
import { validateArchiveEntryName } from "./archive.js";
|
|
4
5
|
import { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, tryParseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
|
|
5
6
|
import { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandboxedRequirement, unsandboxedRequirements, validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
@@ -7,7 +8,8 @@ import { buildExtensionBundles, bundleUnsandboxedRequirement, createStaticExtens
|
|
|
7
8
|
import { buildExtensionBundlesWithModules } from "./extension-module-bundle.js";
|
|
8
9
|
import { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion } from "./project-asset-additions.js";
|
|
9
10
|
import { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from "./turbowarp-clean-up.js";
|
|
10
|
-
import {
|
|
11
|
+
import { blockPaletteSourceFormatVersion, sourceFormatVersion, supportedSourceFormatVersions } from "./source-format.js";
|
|
12
|
+
import { createDeterministicSb3, fixedZipTimestamp, validateSb3Source } from "./source.js";
|
|
11
13
|
import { buildSb3 } from "./build.js";
|
|
12
14
|
import { cleanUpSb3, cleanUpSb3Archive } from "./clean-up-sb3.js";
|
|
13
15
|
import { packageName, packageVersion } from "./constants.js";
|
|
@@ -19,4 +21,4 @@ import { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId }
|
|
|
19
21
|
import { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions } from "./extension-sb3-replacement.js";
|
|
20
22
|
import { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
|
|
21
23
|
import { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate } from "./release-snapshot.js";
|
|
22
|
-
export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpSb3, cleanUpSb3Archive, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultKamishibaiManifestUrl, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionSourceTypes, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, formatExtensionDigestInventory, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, inspectSb3ExtensionDigests, inventoryExtensionDigests, kamishibaiReplacementIds, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, projectManifestKey, readProjectManifest, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, replaceSb3Extensions, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
|
|
24
|
+
export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSourceFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpSb3, cleanUpSb3Archive, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultKamishibaiManifestUrl, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionSourceTypes, extensionStatus, fixedZipTimestamp, formatBlockPaletteComment, formatExtensionApiCompatibilityChanges, formatExtensionDigestInventory, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, inspectSb3ExtensionDigests, inventoryExtensionDigests, kamishibaiReplacementIds, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, projectManifestKey, readProjectManifest, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, replaceSb3Extensions, serializeBlockPaletteDocument, sourceFormatVersion, supportedSourceFormatVersions, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateBlockPaletteDocument, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
|
package/dist/output-safety.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ export interface GitOutputState {
|
|
|
20
20
|
}
|
|
21
21
|
export declare function pathExists(targetPath: string): Promise<boolean>;
|
|
22
22
|
export declare function validateOutputDirectoryPath(outputDirectory: string, protectedRoot: string): string;
|
|
23
|
-
export declare function assertRecognizedOutputDirectory(outputDirectory: string,
|
|
23
|
+
export declare function assertRecognizedOutputDirectory(outputDirectory: string, sourceFormatVersions: readonly number[]): Promise<void>;
|
|
24
24
|
export declare function compareDirectories(existingDirectory: string, candidateDirectory: string): Promise<DirectoryComparison>;
|
|
25
25
|
export declare function inspectGitOutputState(outputDirectory: string, existingFilePaths: string[]): Promise<GitOutputState>;
|
|
26
26
|
export declare function assertNoInterruptedRollback(outputDirectory: string): Promise<void>;
|
package/dist/output-safety.js
CHANGED
|
@@ -28,7 +28,7 @@ function validateOutputDirectoryPath(outputDirectory, protectedRoot) {
|
|
|
28
28
|
assert(!resolvedOutputDirectory.split(path.sep).includes(".git"), "Refusing to write imported SB3 sources into a .git directory.");
|
|
29
29
|
return resolvedOutputDirectory;
|
|
30
30
|
}
|
|
31
|
-
async function assertRecognizedOutputDirectory(outputDirectory,
|
|
31
|
+
async function assertRecognizedOutputDirectory(outputDirectory, sourceFormatVersions) {
|
|
32
32
|
const stats = await lstat(outputDirectory);
|
|
33
33
|
assert(stats.isDirectory() && !stats.isSymbolicLink(), `Refusing to replace a non-directory or symbolic link: ${outputDirectory}`);
|
|
34
34
|
let manifest;
|
|
@@ -38,7 +38,7 @@ async function assertRecognizedOutputDirectory(outputDirectory, sourceFormatVers
|
|
|
38
38
|
if (errorCode(error) !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
|
|
39
39
|
throw new Error(`Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`, { cause: error });
|
|
40
40
|
}
|
|
41
|
-
assert(manifest
|
|
41
|
+
assert(manifest !== null && sourceFormatVersions.includes(manifest.formatVersion) && 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
42
|
}
|
|
43
43
|
function digest(value) {
|
|
44
44
|
return createHash("sha256").update(value).digest("hex");
|