@kubohiroya/sb3-toolchain 0.14.0 → 0.15.1
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 +31 -0
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/constants.js.map +1 -1
- package/dist/extension-bundle.d.ts +12 -1
- package/dist/extension-bundle.js +124 -9
- package/dist/extension-bundle.js.map +1 -1
- package/dist/extension-dependencies.d.ts +10 -0
- package/dist/extension-dependencies.js +14 -2
- package/dist/extension-dependencies.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -3
- package/dist/types.d.ts +1 -0
- package/docs/extension-bundles.md +52 -0
- package/docs/ja/extension-bundles.md +51 -0
- package/docs/ja/source-format-v1.md +3 -0
- package/docs/source-format-v1.md +1 -0
- package/package.json +8 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.15.1 - 2026-10-19
|
|
4
|
+
|
|
5
|
+
- Align package metadata, the public API/CLI version, and install examples.
|
|
6
|
+
- Preserve existing build behavior and data formats from the current source.
|
|
7
|
+
|
|
8
|
+
Rollback: pin `@kubohiroya/sb3-toolchain@0.15.0`.
|
|
9
|
+
|
|
10
|
+
## 0.15.0 - 2026-10-12
|
|
11
|
+
|
|
12
|
+
- Read an `// Unsandboxed: required | optional | not-needed` header line, so an extension can
|
|
13
|
+
declare statically whether TurboWarp's "Run without sandbox" must be checked when it is allowed.
|
|
14
|
+
Any other value fails the build. `extensionHeaderMetadata` returns it as `unsandboxed`, and
|
|
15
|
+
`unsandboxedRequirement` validates it.
|
|
16
|
+
- Derive a bundle's requirement from its members (`required` wins over `optional`, which wins over
|
|
17
|
+
`not-needed`) with `bundleUnsandboxedRequirement`, and record it and each member's value in the
|
|
18
|
+
generated header.
|
|
19
|
+
- When a `required` bundle is loaded sandboxed, register a placeholder under the bundle ID instead
|
|
20
|
+
of running its members; its palette shows the bundle name and how to reload the project
|
|
21
|
+
unsandboxed, and the console gets the same text. Before, a member that threw because it was
|
|
22
|
+
sandboxed left TurboWarp's sandboxed iframe waiting forever, so the project never finished loading
|
|
23
|
+
and the user saw no reason. An `optional` bundle loaded sandboxed runs its members and starts the
|
|
24
|
+
palette with a notice that some features are unavailable.
|
|
25
|
+
- Add the bundle field `sandboxedNotice` to override or add per-locale notices, and export the
|
|
26
|
+
built-in English and Japanese text as `defaultSandboxedNotices`.
|
|
27
|
+
|
|
28
|
+
Bundles whose members declare nothing generate byte-identical JavaScript, so existing builds are
|
|
29
|
+
unaffected.
|
|
30
|
+
|
|
31
|
+
Rollback: pin `@kubohiroya/sb3-toolchain@0.14.0`. A bundle that relies on the sandbox guard then
|
|
32
|
+
loses it, and a `sandboxedNotice` field is ignored rather than rejected.
|
|
33
|
+
|
|
3
34
|
## 0.14.0 - 2026-09-24
|
|
4
35
|
|
|
5
36
|
- Accept extension API manifest format version 2, which carries the metadata a server-side compiler
|
package/README.ja.md
CHANGED
|
@@ -31,7 +31,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
|
|
|
31
31
|
再現可能なインストールのため、検証済みのnpmバージョンを固定します。
|
|
32
32
|
|
|
33
33
|
```bash
|
|
34
|
-
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.
|
|
34
|
+
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.15.1
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
## クイックスタート
|
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
|
|
|
32
32
|
Pin the verified npm version for reproducible installation.
|
|
33
33
|
|
|
34
34
|
```bash
|
|
35
|
-
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.
|
|
35
|
+
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.15.1
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
## Quick start
|
package/dist/constants.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const packageName = "@kubohiroya/sb3-toolchain";
|
|
2
|
-
export declare const packageVersion = "0.
|
|
2
|
+
export declare const packageVersion = "0.15.1";
|
package/dist/constants.js
CHANGED
package/dist/constants.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.15.1';\n"],"mappings":";AAEA,IAAa,cAAc;AAC3B,IAAa,iBAAiB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ExtensionHeaderMetadata } from './extension-dependencies';
|
|
1
|
+
import { ExtensionHeaderMetadata, UnsandboxedRequirement } from './extension-dependencies';
|
|
2
2
|
import { EmbeddedExtension, ExtensionBundleConfiguration, ProjectJson } from './types';
|
|
3
3
|
export declare const extensionBundleRecoveryMarker = "SB3-Toolchain-Reversible-Bundle-v1";
|
|
4
4
|
export interface ExtensionBundleComponent {
|
|
@@ -32,6 +32,17 @@ export interface BuildExtensionBundlesResult {
|
|
|
32
32
|
project: ProjectJson;
|
|
33
33
|
}
|
|
34
34
|
declare function validateBundleId(id: unknown, description?: string): string;
|
|
35
|
+
/**
|
|
36
|
+
* Shown in the palette when a bundle runs sandboxed although a member declared
|
|
37
|
+
* `// Unsandboxed: required` (the members then do not run) or `optional` (they run with less).
|
|
38
|
+
*/
|
|
39
|
+
export declare const defaultSandboxedNotices: Readonly<Record<'required' | 'optional', Readonly<Record<string, string>>>>;
|
|
40
|
+
/**
|
|
41
|
+
* Derives a bundle's requirement from its members' declarations: any `required` member makes the
|
|
42
|
+
* bundle required; otherwise any `optional` member makes it optional; it is `not-needed` only when
|
|
43
|
+
* every member says so. `null` means no member declares anything.
|
|
44
|
+
*/
|
|
45
|
+
export declare function bundleUnsandboxedRequirement(components: readonly Pick<ExtensionBundleComponent, 'metadata'>[]): UnsandboxedRequirement | null;
|
|
35
46
|
declare function validateBundleName(name: unknown): string;
|
|
36
47
|
export declare function validateExtensionBundleConfigurations(extensionBundles: unknown, extensions: EmbeddedExtension[]): ExtensionBundleConfiguration[];
|
|
37
48
|
export declare function createStaticExtensionBundle(bundle: ExtensionBundleConfiguration, components: ExtensionBundleComponent[], originalProject?: ProjectJson | undefined): Buffer;
|
package/dist/extension-bundle.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { assert } from "./assert.js";
|
|
2
|
-
import { extensionHeaderMetadata } from "./extension-dependencies.js";
|
|
2
|
+
import { extensionHeaderMetadata, unsandboxedRequirement } from "./extension-dependencies.js";
|
|
3
3
|
//#region src/extension-bundle.ts
|
|
4
4
|
var extensionBundleRecoveryMarker = "SB3-Toolchain-Reversible-Bundle-v1";
|
|
5
5
|
function isObject(value) {
|
|
@@ -9,6 +9,42 @@ function validateBundleId(id, description = "Extension bundle ID") {
|
|
|
9
9
|
assert(typeof id === "string" && /^[a-z0-9]+$/u.test(id), `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`);
|
|
10
10
|
return id;
|
|
11
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Shown in the palette when a bundle runs sandboxed although a member declared
|
|
14
|
+
* `// Unsandboxed: required` (the members then do not run) or `optional` (they run with less).
|
|
15
|
+
*/
|
|
16
|
+
var defaultSandboxedNotices = Object.freeze({
|
|
17
|
+
required: Object.freeze({
|
|
18
|
+
en: "This extension must run without the sandbox.\nLoad the project again and, in the extension\nsecurity dialog, check \"Run without sandbox\"\nbefore allowing it.",
|
|
19
|
+
ja: "この拡張機能はサンドボックスなしで実行する必要があります。\nプロジェクトを開き直し、拡張機能セキュリティの画面で\n「サンドボックスなしで実行する」にチェックを付けてから\n許可してください。"
|
|
20
|
+
}),
|
|
21
|
+
optional: Object.freeze({
|
|
22
|
+
en: "Running in the sandbox: some features are unavailable.\nTo use them, load the project again and check\n\"Run without sandbox\" in the extension security dialog.",
|
|
23
|
+
ja: "サンドボックス内で実行中のため、一部の機能が使えません。\n使うには、プロジェクトを開き直し、拡張機能セキュリティの画面で\n「サンドボックスなしで実行する」にチェックを付けてください。"
|
|
24
|
+
})
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* Derives a bundle's requirement from its members' declarations: any `required` member makes the
|
|
28
|
+
* bundle required; otherwise any `optional` member makes it optional; it is `not-needed` only when
|
|
29
|
+
* every member says so. `null` means no member declares anything.
|
|
30
|
+
*/
|
|
31
|
+
function bundleUnsandboxedRequirement(components) {
|
|
32
|
+
const declared = components.map((component) => unsandboxedRequirement(component.metadata));
|
|
33
|
+
if (declared.includes("required")) return "required";
|
|
34
|
+
if (declared.includes("optional")) return "optional";
|
|
35
|
+
if (declared.length > 0 && declared.every((requirement) => requirement === "not-needed")) return "not-needed";
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
function validateSandboxedNotice(notice, bundleId) {
|
|
39
|
+
assert(isObject(notice) && Object.keys(notice).length > 0, `Extension bundle ${bundleId} sandboxedNotice must be a non-empty object of locale messages.`);
|
|
40
|
+
const validated = {};
|
|
41
|
+
for (const [locale, message] of Object.entries(notice)) {
|
|
42
|
+
assert(/^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/u.test(locale), `Extension bundle ${bundleId} sandboxedNotice locale must be a lowercase language tag: ` + JSON.stringify(locale));
|
|
43
|
+
assert(typeof message === "string" && message.trim().length > 0, `Extension bundle ${bundleId} sandboxedNotice.${locale} must be a non-empty string.`);
|
|
44
|
+
validated[locale] = message;
|
|
45
|
+
}
|
|
46
|
+
return validated;
|
|
47
|
+
}
|
|
12
48
|
function validateBundleName(name) {
|
|
13
49
|
assert(typeof name === "string" && name.trim() === name && name.length > 0 && !/[\r\n]/u.test(name), `Extension bundle name must be a non-empty single line: ${JSON.stringify(name)}`);
|
|
14
50
|
return name;
|
|
@@ -29,6 +65,7 @@ function validateExtensionBundleConfigurations(extensionBundles, extensions) {
|
|
|
29
65
|
assert(Array.isArray(bundle.members) && bundle.members.length >= 2, `Extension bundle ${id} must contain at least two members.`);
|
|
30
66
|
assert(bundle.recoveryCapsule === void 0 || typeof bundle.recoveryCapsule === "boolean", `Extension bundle ${id} recoveryCapsule must be a boolean when present.`);
|
|
31
67
|
const capsuleFlag = bundle.recoveryCapsule;
|
|
68
|
+
const sandboxedNotice = bundle.sandboxedNotice === void 0 ? void 0 : validateSandboxedNotice(bundle.sandboxedNotice, id);
|
|
32
69
|
const localMemberIds = /* @__PURE__ */ new Set();
|
|
33
70
|
const members = [];
|
|
34
71
|
for (const rawMemberId of bundle.members) {
|
|
@@ -44,7 +81,8 @@ function validateExtensionBundleConfigurations(extensionBundles, extensions) {
|
|
|
44
81
|
id,
|
|
45
82
|
members,
|
|
46
83
|
name,
|
|
47
|
-
...capsuleFlag === void 0 ? {} : { recoveryCapsule: capsuleFlag }
|
|
84
|
+
...capsuleFlag === void 0 ? {} : { recoveryCapsule: capsuleFlag },
|
|
85
|
+
...sandboxedNotice === void 0 ? {} : { sandboxedNotice }
|
|
48
86
|
};
|
|
49
87
|
});
|
|
50
88
|
}
|
|
@@ -63,6 +101,7 @@ function readBundleComponents(bundle, extensionsById, extensionContents) {
|
|
|
63
101
|
["description", "Description"],
|
|
64
102
|
["license", "License"]
|
|
65
103
|
]) assert(metadata[property], `Extension bundle ${bundle.id} member ${memberId} requires a // ${label}: header.`);
|
|
104
|
+
unsandboxedRequirement(metadata);
|
|
66
105
|
const source = Buffer.from(contents).toString("utf8");
|
|
67
106
|
assert(!source.startsWith("#!"), `Extension bundle ${bundle.id} member ${memberId} cannot use a shebang.`);
|
|
68
107
|
assert(!source.includes(extensionBundleRecoveryMarker), `Extension bundle ${bundle.id} member ${memberId} contains the reserved recovery marker.`);
|
|
@@ -86,11 +125,15 @@ function bundleHeader(bundle, components) {
|
|
|
86
125
|
`// ID: ${bundle.id}`,
|
|
87
126
|
`// Description: Static bundle of ${components.length} TurboWarp extensions.`,
|
|
88
127
|
`// By: ${commentLine(authors.join(", "))}`,
|
|
89
|
-
"// License: See the bundled extension notices below."
|
|
90
|
-
"//",
|
|
91
|
-
"// Bundled extensions:"
|
|
128
|
+
"// License: See the bundled extension notices below."
|
|
92
129
|
];
|
|
93
|
-
|
|
130
|
+
const requirement = bundleUnsandboxedRequirement(components);
|
|
131
|
+
if (requirement !== null) lines.push(`// Unsandboxed: ${requirement}`);
|
|
132
|
+
lines.push("//", "// Bundled extensions:");
|
|
133
|
+
for (const component of components) {
|
|
134
|
+
lines.push(`// - Name: ${commentLine(component.metadata.name)}`, `// ID: ${component.metadata.id}`, `// By: ${commentLine(component.metadata.author)}`, `// Description: ${commentLine(component.metadata.description)}`, `// License: ${commentLine(component.metadata.license)}`);
|
|
135
|
+
if (component.metadata.unsandboxed !== null) lines.push(`// Unsandboxed: ${component.metadata.unsandboxed}`);
|
|
136
|
+
}
|
|
94
137
|
return `${lines.join("\n")}\n`;
|
|
95
138
|
}
|
|
96
139
|
function componentLoadSource(component) {
|
|
@@ -120,9 +163,80 @@ function recoveryCapsule(bundle, components, originalProject) {
|
|
|
120
163
|
originalExtensionUrlIds: Object.keys(originalProject?.extensionURLs ?? {})
|
|
121
164
|
};
|
|
122
165
|
}
|
|
166
|
+
function sandboxedNotice(bundle, requirement) {
|
|
167
|
+
if (requirement !== "required" && requirement !== "optional") {
|
|
168
|
+
assert(bundle.sandboxedNotice === void 0, `Extension bundle ${bundle.id} sandboxedNotice needs a member that declares // Unsandboxed: required or optional.`);
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
...defaultSandboxedNotices[requirement],
|
|
173
|
+
...bundle.sandboxedNotice
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Detects a sandboxed load for a bundle whose members declared they need (`required`) or benefit
|
|
178
|
+
* from (`optional`) TurboWarp's unsandboxed API. A required bundle registers a placeholder under
|
|
179
|
+
* the bundle ID instead of running its members, so none can fail on a missing `Scratch.vm` and the
|
|
180
|
+
* project still finishes loading: a sandboxed iframe that throws before registering leaves
|
|
181
|
+
* TurboWarp waiting forever, and a worker reports only a generic failure. An optional bundle runs
|
|
182
|
+
* its members and prefixes the palette with the notice. Bundles without a declaration get nothing.
|
|
183
|
+
*/
|
|
184
|
+
function sandboxedGuardSource(requirement, notice) {
|
|
185
|
+
if (notice === null) return "";
|
|
186
|
+
const required = requirement === "required";
|
|
187
|
+
return `
|
|
188
|
+
const SANDBOXED = !Scratch.extensions || Scratch.extensions.unsandboxed !== true;
|
|
189
|
+
const SANDBOXED_NOTICE = ${JSON.stringify(notice)};
|
|
190
|
+
const currentLocale = () => {
|
|
191
|
+
try {
|
|
192
|
+
if (Scratch.translate && typeof Scratch.translate.language === 'string') {
|
|
193
|
+
return Scratch.translate.language;
|
|
194
|
+
}
|
|
195
|
+
} catch (_error) {
|
|
196
|
+
// Fall through to the browser language.
|
|
197
|
+
}
|
|
198
|
+
return typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en';
|
|
199
|
+
};
|
|
200
|
+
const sandboxedNoticeText = () => {
|
|
201
|
+
const locale = String(currentLocale()).toLowerCase();
|
|
202
|
+
const language = locale.split('-')[0];
|
|
203
|
+
if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, locale)) return SANDBOXED_NOTICE[locale];
|
|
204
|
+
if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, language)) return SANDBOXED_NOTICE[language];
|
|
205
|
+
return SANDBOXED_NOTICE.en;
|
|
206
|
+
};
|
|
207
|
+
const sandboxedNoticeBlocks = () => ['⚠ ' + BUNDLE_NAME, ...sandboxedNoticeText().split('\\n')]
|
|
208
|
+
.filter((line) => line.length > 0)
|
|
209
|
+
.map((line) => ({
|
|
210
|
+
blockType: (Scratch.BlockType && Scratch.BlockType.LABEL) || 'label',
|
|
211
|
+
sb3Toolchain: {kind: 'bundle-sandboxed-notice'},
|
|
212
|
+
text: line,
|
|
213
|
+
}));
|
|
214
|
+
if (SANDBOXED && typeof console !== 'undefined') {
|
|
215
|
+
const report = console.${required ? "error" : "warn"} || console.log;
|
|
216
|
+
report.call(console, '[' + BUNDLE_ID + '] ' + BUNDLE_NAME + ' ${required ? "requires" : "works better with"} unsandboxed loading. ' + sandboxedNoticeText().replace(/\\n/gu, ' '));
|
|
217
|
+
}
|
|
218
|
+
${required ? ` if (SANDBOXED) {
|
|
219
|
+
class SandboxedExtensionBundleNotice {
|
|
220
|
+
getInfo() {
|
|
221
|
+
return {
|
|
222
|
+
id: BUNDLE_ID,
|
|
223
|
+
name: BUNDLE_NAME,
|
|
224
|
+
color1: '#D65C5C',
|
|
225
|
+
blocks: sandboxedNoticeBlocks(),
|
|
226
|
+
menus: {},
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
Scratch.extensions.register(new SandboxedExtensionBundleNotice());
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
` : ""}`;
|
|
234
|
+
}
|
|
123
235
|
function createStaticExtensionBundle(bundle, components, originalProject = void 0) {
|
|
124
236
|
const componentIds = JSON.stringify(components.map((component) => component.metadata.id));
|
|
125
237
|
const header = bundleHeader(bundle, components);
|
|
238
|
+
const requirement = bundleUnsandboxedRequirement(components);
|
|
239
|
+
const notice = sandboxedNotice(bundle, requirement);
|
|
126
240
|
const loaders = components.map(componentLoadSource).join("\n");
|
|
127
241
|
const runtime = `(function (Scratch) {
|
|
128
242
|
'use strict';
|
|
@@ -130,7 +244,7 @@ function createStaticExtensionBundle(bundle, components, originalProject = void
|
|
|
130
244
|
const BUNDLE_ID = ${JSON.stringify(bundle.id)};
|
|
131
245
|
const BUNDLE_NAME = ${JSON.stringify(bundle.name)};
|
|
132
246
|
const COMPONENT_IDS = ${componentIds};
|
|
133
|
-
const components = new Map();
|
|
247
|
+
${sandboxedGuardSource(requirement, notice)} const components = new Map();
|
|
134
248
|
|
|
135
249
|
const rewriteOpcode = (componentId, opcode) => {
|
|
136
250
|
const prefix = componentId + '_';
|
|
@@ -276,7 +390,8 @@ ${loaders}
|
|
|
276
390
|
blocks: [],
|
|
277
391
|
menus: {},
|
|
278
392
|
customFieldTypes: {},
|
|
279
|
-
}
|
|
393
|
+
};${requirement === "optional" ? `
|
|
394
|
+
if (SANDBOXED) result.blocks.push(...sandboxedNoticeBlocks(), '---', '---');` : ""}
|
|
280
395
|
this.delegates.clear();
|
|
281
396
|
const transformedOpcodes = new Set();
|
|
282
397
|
|
|
@@ -575,6 +690,6 @@ function buildExtensionBundles({ extensionBundles, extensionContents, extensions
|
|
|
575
690
|
};
|
|
576
691
|
}
|
|
577
692
|
//#endregion
|
|
578
|
-
export { buildExtensionBundles, createStaticExtensionBundle, extensionBundleRecoveryMarker, validateBundleId, validateBundleName, validateExtensionBundleConfigurations };
|
|
693
|
+
export { buildExtensionBundles, bundleUnsandboxedRequirement, createStaticExtensionBundle, defaultSandboxedNotices, extensionBundleRecoveryMarker, validateBundleId, validateBundleName, validateExtensionBundleConfigurations };
|
|
579
694
|
|
|
580
695
|
//# sourceMappingURL=extension-bundle.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-bundle.js","names":[],"sources":["../src/extension-bundle.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {assert} from './assert';\nimport {extensionHeaderMetadata} from './extension-dependencies';\nimport type {ExtensionHeaderMetadata} from './extension-dependencies';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n UnknownRecord,\n} from './types';\n\nexport const extensionBundleRecoveryMarker = 'SB3-Toolchain-Reversible-Bundle-v1';\n\nexport interface ExtensionBundleComponent {\n contents: string;\n extension: EmbeddedExtension;\n metadata: ExtensionHeaderMetadata;\n originalContents: Buffer;\n}\n\nexport interface ExtensionBundleCounts {\n extensionStorage: number;\n extensionUrls: number;\n opcodes: number;\n projectExtensions: number;\n}\n\nexport interface ExtensionBundlePlan {\n bundle: ExtensionBundleConfiguration;\n components: ExtensionBundleComponent[];\n contents: Buffer;\n counts: ExtensionBundleCounts;\n}\n\nexport interface BuildExtensionBundlesInput {\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n}\n\nexport interface BuildExtensionBundlesResult {\n bundlePlans: ExtensionBundlePlan[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction validateBundleId(id: unknown, description = 'Extension bundle ID'): string {\n assert(\n typeof id === 'string' && /^[a-z0-9]+$/u.test(id),\n `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`,\n );\n return id;\n}\n\nfunction validateBundleName(name: unknown): string {\n assert(\n typeof name === 'string' && name.trim() === name && name.length > 0 && !/[\\r\\n]/u.test(name),\n `Extension bundle name must be a non-empty single line: ${JSON.stringify(name)}`,\n );\n return name;\n}\n\nexport function validateExtensionBundleConfigurations(\n extensionBundles: unknown,\n extensions: EmbeddedExtension[],\n): ExtensionBundleConfiguration[] {\n if (extensionBundles === undefined) return [];\n assert(\n Array.isArray(extensionBundles),\n 'embedded-extensions.json extensionBundles must be an array.',\n );\n\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundleIds = new Set<string>();\n const bundledMemberIds = new Set<string>();\n\n return (extensionBundles as unknown[]).map((bundle, bundleIndex) => {\n assert(isObject(bundle), `Extension bundle ${bundleIndex} must be an object.`);\n const id = validateBundleId(bundle.id, `Extension bundle ${bundleIndex} ID`);\n const name = validateBundleName(bundle.name);\n assert(!extensionsById.has(id), `Extension bundle ID collides with an extension: ${id}`);\n assert(!bundleIds.has(id), `Duplicate extension bundle ID: ${id}`);\n bundleIds.add(id);\n assert(\n Array.isArray(bundle.members) && bundle.members.length >= 2,\n `Extension bundle ${id} must contain at least two members.`,\n );\n assert(\n bundle.recoveryCapsule === undefined || typeof bundle.recoveryCapsule === 'boolean',\n `Extension bundle ${id} recoveryCapsule must be a boolean when present.`,\n );\n const capsuleFlag = bundle.recoveryCapsule;\n\n const localMemberIds = new Set<string>();\n const members: string[] = [];\n for (const rawMemberId of bundle.members as unknown[]) {\n const memberId = validateBundleId(rawMemberId, `Extension bundle ${id} member ID`);\n assert(\n extensionsById.has(memberId),\n `Extension bundle ${id} has unknown member: ${memberId}`,\n );\n assert(!localMemberIds.has(memberId), `Extension bundle ${id} repeats member: ${memberId}`);\n assert(\n !bundledMemberIds.has(memberId),\n `Embedded extension belongs to more than one bundle: ${memberId}`,\n );\n localMemberIds.add(memberId);\n bundledMemberIds.add(memberId);\n members.push(memberId);\n }\n return {\n id,\n members,\n name,\n ...(capsuleFlag === undefined ? {} : {recoveryCapsule: capsuleFlag}),\n };\n });\n}\n\nfunction readBundleComponents(\n bundle: ExtensionBundleConfiguration,\n extensionsById: Map<string, EmbeddedExtension>,\n extensionContents: Map<string, Uint8Array>,\n): ExtensionBundleComponent[] {\n return bundle.members.map((memberId) => {\n const extension = extensionsById.get(memberId);\n const contents = extensionContents.get(memberId);\n assert(contents, `Extension bundle ${bundle.id} has no contents for member: ${memberId}`);\n assert(\n extension,\n `Extension bundle ${bundle.id} has no manifest entry for member: ${memberId}`,\n );\n assert(\n extension.mediaType === 'text/javascript' || extension.mediaType === 'application/javascript',\n `Extension bundle ${bundle.id} member ${memberId} must be JavaScript, got ${extension.mediaType}.`,\n );\n const metadata = extensionHeaderMetadata(contents);\n assert(\n metadata.id === memberId,\n `Extension bundle ${bundle.id} member header ID mismatch: expected ${memberId}, ` +\n `got ${metadata.id ?? '(missing)'}`,\n );\n for (const [property, label] of [\n ['name', 'Name'],\n ['author', 'By'],\n ['description', 'Description'],\n ['license', 'License'],\n ] as const) {\n assert(\n metadata[property],\n `Extension bundle ${bundle.id} member ${memberId} requires a // ${label}: header.`,\n );\n }\n const source = Buffer.from(contents).toString('utf8');\n assert(\n !source.startsWith('#!'),\n `Extension bundle ${bundle.id} member ${memberId} cannot use a shebang.`,\n );\n assert(\n !source.includes(extensionBundleRecoveryMarker),\n `Extension bundle ${bundle.id} member ${memberId} contains the reserved recovery marker.`,\n );\n const registrations = source.match(/\\bScratch\\s*\\.\\s*extensions\\s*\\.\\s*register\\s*\\(/gu) ?? [];\n assert(\n registrations.length === 1,\n `Extension bundle ${bundle.id} member ${memberId} must contain exactly one synchronous ` +\n `Scratch.extensions.register call; found ${registrations.length}.`,\n );\n return {contents: source, extension, metadata, originalContents: Buffer.from(contents)};\n });\n}\n\nfunction commentLine(value: unknown): string {\n return String(value).replaceAll('\\r', ' ').replaceAll('\\n', ' ');\n}\n\nfunction bundleHeader(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n): string {\n const authors = [...new Set(components.map((component) => component.metadata.author))];\n const lines = [\n `// Name: ${commentLine(bundle.name)}`,\n `// ID: ${bundle.id}`,\n `// Description: Static bundle of ${components.length} TurboWarp extensions.`,\n `// By: ${commentLine(authors.join(', '))}`,\n '// License: See the bundled extension notices below.',\n '//',\n '// Bundled extensions:',\n ];\n for (const component of components) {\n lines.push(\n `// - Name: ${commentLine(component.metadata.name)}`,\n `// ID: ${component.metadata.id}`,\n `// By: ${commentLine(component.metadata.author)}`,\n `// Description: ${commentLine(component.metadata.description)}`,\n `// License: ${commentLine(component.metadata.license)}`,\n );\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction componentLoadSource(component: ExtensionBundleComponent): string {\n const memberId = JSON.stringify(component.metadata.id);\n const source = component.contents.endsWith('\\n') ? component.contents : `${component.contents}\\n`;\n return `loadComponent(${memberId}, function (Scratch) {\\n${source}});\\n`;\n}\n\nfunction percentEncode(contents: Uint8Array | string): string {\n return [...Buffer.from(contents)]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction componentDataUrl(component: ExtensionBundleComponent): string {\n const metadata = [component.extension.mediaType, ...component.extension.parameters].join(';');\n const originalContents = component.originalContents ?? Buffer.from(component.contents);\n if (component.extension.encoding === 'base64') {\n return `data:${metadata};base64,${originalContents.toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(originalContents)}`;\n}\n\nfunction recoveryCapsule(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined,\n): UnknownRecord {\n return {\n formatVersion: 1,\n bundle: {id: bundle.id, name: bundle.name},\n components: components.map((component) => ({\n dataUrl: componentDataUrl(component),\n id: component.metadata.id,\n })),\n originalExtensionIds: Array.isArray(originalProject?.extensions)\n ? [...(originalProject.extensions as unknown[])]\n : null,\n originalExtensionUrlIds: Object.keys(originalProject?.extensionURLs ?? {}),\n };\n}\n\nexport function createStaticExtensionBundle(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined = undefined,\n): Buffer {\n const componentIds = JSON.stringify(components.map((component) => component.metadata.id));\n const header = bundleHeader(bundle, components);\n const loaders = components.map(componentLoadSource).join('\\n');\n const runtime = `(function (Scratch) {\n 'use strict';\n\n const BUNDLE_ID = ${JSON.stringify(bundle.id)};\n const BUNDLE_NAME = ${JSON.stringify(bundle.name)};\n const COMPONENT_IDS = ${componentIds};\n const components = new Map();\n\n const rewriteOpcode = (componentId, opcode) => {\n const prefix = componentId + '_';\n return typeof opcode === 'string' && opcode.startsWith(prefix)\n ? BUNDLE_ID + '_' + componentId + '__' + opcode.slice(prefix.length)\n : opcode;\n };\n\n const rewriteBundleOpcode = (opcode) => {\n for (const componentId of COMPONENT_IDS) {\n const rewritten = rewriteOpcode(componentId, opcode);\n if (rewritten !== opcode) return rewritten;\n }\n return opcode;\n };\n\n const xmlEscape = (value) => String(value).replace(/[<>&'\"]/gu, (character) => ({\n '<': '<',\n '>': '>',\n '&': '&',\n \"'\": ''',\n '\"': '"',\n })[character]);\n\n const installStorageAliases = (storage) => {\n if (!storage || typeof storage !== 'object') return;\n const hasBundleStorage = Object.prototype.hasOwnProperty.call(storage, BUNDLE_ID);\n const hasMemberStorage = COMPONENT_IDS.some((id) => Object.prototype.hasOwnProperty.call(storage, id));\n if (!hasBundleStorage && !hasMemberStorage) return;\n let bundleStorage = storage[BUNDLE_ID];\n if (!bundleStorage || typeof bundleStorage !== 'object' || Array.isArray(bundleStorage)) {\n bundleStorage = {formatVersion: 1, components: {}};\n storage[BUNDLE_ID] = bundleStorage;\n }\n if (!bundleStorage.components || typeof bundleStorage.components !== 'object' || Array.isArray(bundleStorage.components)) {\n throw new Error('Invalid extension storage for static bundle ' + BUNDLE_ID + '.');\n }\n for (const id of COMPONENT_IDS) {\n const descriptor = Object.getOwnPropertyDescriptor(storage, id);\n if (descriptor && !descriptor.get && !Object.prototype.hasOwnProperty.call(bundleStorage.components, id)) {\n bundleStorage.components[id] = storage[id];\n }\n if (!descriptor || !descriptor.get) {\n delete storage[id];\n Object.defineProperty(storage, id, {\n configurable: true,\n enumerable: false,\n get: () => bundleStorage.components[id],\n set: (value) => {\n bundleStorage.components[id] = value;\n },\n });\n }\n }\n };\n\n const installAllStorageAliases = () => {\n const runtime = Scratch.vm && Scratch.vm.runtime;\n if (!runtime) return;\n installStorageAliases(runtime.extensionStorage);\n for (const target of runtime.targets || []) installStorageAliases(target.extensionStorage);\n };\n\n installAllStorageAliases();\n\n const createComponentScratch = (componentId, register) => {\n const baseRuntime = Scratch.vm && Scratch.vm.runtime;\n const runtime = baseRuntime && new Proxy(baseRuntime, {\n get(target, property) {\n if (property === 'startHats') {\n return (opcode, ...args) => target.startHats(rewriteOpcode(componentId, opcode), ...args);\n }\n if (property === 'getOpcodeFunction') {\n return (opcode, ...args) => target.getOpcodeFunction(rewriteBundleOpcode(opcode), ...args);\n }\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const baseVm = Scratch.vm;\n const vm = baseVm && new Proxy(baseVm, {\n get(target, property) {\n if (property === 'runtime') return runtime;\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const extensions = Object.create(Scratch.extensions);\n Object.defineProperty(extensions, 'register', {value: register});\n return new Proxy(Scratch, {\n get(target, property) {\n if (property === 'extensions') return extensions;\n if (property === 'vm') return vm;\n return Reflect.get(target, property, target);\n },\n });\n };\n\n const loadComponent = (componentId, execute) => {\n let registration = null;\n let registrationCount = 0;\n let acceptingRegistration = true;\n const componentScratch = createComponentScratch(componentId, (extension) => {\n if (!acceptingRegistration) {\n throw new Error('Asynchronous registration is unsupported in static bundle member ' + componentId + '.');\n }\n registration = extension;\n registrationCount += 1;\n });\n execute(componentScratch);\n acceptingRegistration = false;\n if (registrationCount !== 1) {\n throw new Error(\n 'Static bundle member ' + componentId + ' must register exactly once synchronously; got ' + registrationCount + '.',\n );\n }\n components.set(componentId, registration);\n };\n\n${loaders}\n class StaticExtensionBundle {\n constructor() {\n this.delegates = new Map();\n }\n\n addDelegate(name, component, originalName) {\n if (this.delegates.has(name)) throw new Error('Duplicate static bundle delegate: ' + name);\n if (typeof originalName !== 'string' || typeof component[originalName] !== 'function') {\n throw new Error('Missing static bundle handler: ' + originalName);\n }\n this.delegates.set(name, {component, originalName});\n this[name] = (...args) => {\n installAllStorageAliases();\n return component[originalName](...args);\n };\n }\n\n getInfo() {\n const result = {\n id: BUNDLE_ID,\n name: BUNDLE_NAME,\n color1: '#5B67A5',\n blocks: [],\n menus: {},\n customFieldTypes: {},\n };\n this.delegates.clear();\n const transformedOpcodes = new Set();\n\n for (const [componentIndex, componentId] of COMPONENT_IDS.entries()) {\n const component = components.get(componentId);\n const info = component.getInfo();\n if (!info || info.id !== componentId) {\n throw new Error(\n 'Static bundle member runtime ID mismatch: expected ' + componentId + ', got ' +\n (info && info.id ? info.id : '(missing)') + '.',\n );\n }\n if (typeof info.name !== 'string' || info.name.length === 0) {\n throw new Error('Static bundle member ' + componentId + ' must have a non-empty name.');\n }\n const namespace = componentId + '__';\n const memberBlockIconURI =\n typeof info.blockIconURI === 'string' && info.blockIconURI.length > 0\n ? info.blockIconURI\n : null;\n const customFieldTypes = info.customFieldTypes || {};\n for (const [fieldName, fieldInfo] of Object.entries(customFieldTypes)) {\n result.customFieldTypes[namespace + fieldName] = fieldInfo;\n }\n if (componentIndex > 0) result.blocks.push('---', '---');\n result.blocks.push({\n blockType: Scratch.BlockType.LABEL,\n sb3Toolchain: {kind: 'bundle-member-heading', memberId: componentId},\n text: '◆ ' + info.name + ' [' + componentId + '] ◆',\n });\n if (info.docsURI) {\n const docsURI = String(info.docsURI);\n result.blocks.push({\n blockType: Scratch.BlockType.XML,\n sb3Toolchain: {\n docsURI,\n kind: 'bundle-member-docs',\n memberId: componentId,\n },\n xml: '<button text=\"Open Documentation\" callbackKey=\"OPEN_EXTENSION_DOCS\" callbackData=\"' + xmlEscape(docsURI) + '\"></button>',\n });\n }\n for (const block of info.blocks || []) {\n if (block === '---') {\n result.blocks.push(block);\n continue;\n }\n if (!block || typeof block !== 'object') throw new Error('Invalid block in static bundle member ' + componentId + '.');\n if (block.blockType === Scratch.BlockType.XML) {\n throw new Error('XML blocks are unsupported in static bundle member ' + componentId + '.');\n }\n const transformed = {...block};\n if (\n memberBlockIconURI !== null &&\n !Object.prototype.hasOwnProperty.call(block, 'blockIconURI') &&\n block.blockType !== Scratch.BlockType.LABEL &&\n block.blockType !== Scratch.BlockType.BUTTON\n ) {\n transformed.blockIconURI = memberBlockIconURI;\n }\n if (block.arguments) {\n transformed.arguments = Object.fromEntries(\n Object.entries(block.arguments).map(([argumentName, argument]) => {\n const transformedArgument = {...argument};\n if (typeof transformedArgument.menu === 'string') {\n transformedArgument.menu = namespace + transformedArgument.menu;\n }\n if (typeof transformedArgument.type === 'string' && Object.prototype.hasOwnProperty.call(customFieldTypes, transformedArgument.type)) {\n transformedArgument.type = namespace + transformedArgument.type;\n }\n return [argumentName, transformedArgument];\n }),\n );\n }\n if (block.blockType === Scratch.BlockType.LABEL) {\n result.blocks.push(transformed);\n continue;\n }\n if (block.blockType === Scratch.BlockType.BUTTON) {\n const delegateName = namespace + 'button__' + block.func;\n transformed.func = delegateName;\n this.addDelegate(delegateName, component, block.func);\n result.blocks.push(transformed);\n continue;\n }\n if (typeof block.opcode !== 'string' || block.opcode.length === 0) {\n throw new Error('Missing opcode in static bundle member ' + componentId + '.');\n }\n transformed.opcode = namespace + block.opcode;\n if (transformedOpcodes.has(transformed.opcode)) {\n throw new Error('Duplicate static bundle opcode: ' + transformed.opcode);\n }\n transformedOpcodes.add(transformed.opcode);\n if (block.blockType !== Scratch.BlockType.EVENT) {\n const originalName = block.func || block.opcode;\n transformed.func = transformed.opcode;\n this.addDelegate(transformed.opcode, component, originalName);\n } else {\n delete transformed.func;\n }\n result.blocks.push(transformed);\n }\n for (const [menuName, menu] of Object.entries(info.menus || {})) {\n const transformedMenuName = namespace + menuName;\n if (typeof menu === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu);\n result.menus[transformedMenuName] = {items: delegateName};\n } else if (Array.isArray(menu)) {\n result.menus[transformedMenuName] = [...menu];\n } else if (menu && typeof menu === 'object') {\n const transformedMenu = {...menu};\n if (typeof menu.items === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu.items);\n transformedMenu.items = delegateName;\n }\n result.menus[transformedMenuName] = transformedMenu;\n } else {\n throw new Error('Invalid menu in static bundle member ' + componentId + ': ' + menuName + '.');\n }\n }\n }\n return result;\n }\n }\n\n Scratch.extensions.register(new StaticExtensionBundle());\n})(Scratch);\n`;\n if (bundle.recoveryCapsule !== true) {\n return Buffer.from(`${header}\\n${runtime}`);\n }\n const capsule = Buffer.from(\n JSON.stringify(\n recoveryCapsule(\n bundle,\n components,\n originalProject ?? {\n extensions: bundle.members,\n extensionURLs: Object.fromEntries(bundle.members.map((memberId) => [memberId, true])),\n },\n ),\n ),\n ).toString('base64');\n return Buffer.from(`${header}\\n${runtime}\\n// ${extensionBundleRecoveryMarker}: ${capsule}\\n`);\n}\n\nfunction replaceMemberKeys(\n object: UnknownRecord,\n memberIds: Set<string>,\n bundleId: string,\n bundleValue: (value: unknown) => unknown,\n): {inserted: boolean; replacement: UnknownRecord} {\n const replacement: UnknownRecord = {};\n let inserted = false;\n for (const [key, value] of Object.entries(object)) {\n if (memberIds.has(key)) {\n if (!inserted) {\n replacement[bundleId] = bundleValue(value);\n inserted = true;\n }\n } else {\n replacement[key] = value;\n }\n }\n return {inserted, replacement};\n}\n\nfunction bundleStorage(storage: unknown, bundle: ExtensionBundleConfiguration): unknown {\n if (!isObject(storage)) return storage;\n const memberIds = new Set(bundle.members);\n const componentStorage: UnknownRecord = {};\n for (const memberId of bundle.members) {\n if (Object.hasOwn(storage, memberId)) componentStorage[memberId] = storage[memberId];\n }\n if (Object.keys(componentStorage).length === 0) return storage;\n assert(\n !Object.hasOwn(storage, bundle.id),\n `Extension storage already contains bundle ID: ${bundle.id}`,\n );\n return replaceMemberKeys(storage, memberIds, bundle.id, () => ({\n formatVersion: 1,\n components: componentStorage,\n })).replacement;\n}\n\nfunction rewriteOpcodeValues(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n counts: ExtensionBundleCounts,\n): void {\n if (!value || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const entry of value as unknown[]) rewriteOpcodeValues(entry, bundle, counts);\n return;\n }\n const record = value as UnknownRecord;\n for (const [key, entry] of Object.entries(record)) {\n if (key === 'opcode' && typeof entry === 'string') {\n for (const memberId of bundle.members) {\n const prefix = `${memberId}_`;\n if (entry.startsWith(prefix)) {\n record[key] = `${bundle.id}_${memberId}__${entry.slice(prefix.length)}`;\n counts.opcodes += 1;\n break;\n }\n }\n } else {\n rewriteOpcodeValues(entry, bundle, counts);\n }\n }\n}\n\nfunction collectRemainingOpcodeReferences(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n): string[] {\n const references: string[] = [];\n const prefixes = bundle.members.map((memberId) => `${memberId}_`);\n function visit(current: unknown, pointer: string): void {\n if (typeof current === 'string') {\n if (prefixes.some((prefix) => current.startsWith(prefix))) references.push(pointer || '/');\n return;\n }\n if (!current || typeof current !== 'object') return;\n if (Array.isArray(current)) {\n (current as unknown[]).forEach((entry, index) => visit(entry, `${pointer}/${index}`));\n return;\n }\n for (const [key, entry] of Object.entries(current as UnknownRecord)) {\n visit(entry, `${pointer}/${key}`);\n }\n }\n visit(value, '');\n return references;\n}\n\nfunction rewriteProjectForBundle(\n project: ProjectJson,\n bundle: ExtensionBundleConfiguration,\n): {counts: ExtensionBundleCounts; project: ProjectJson} {\n const rewritten = structuredClone(project);\n const memberIds = new Set(bundle.members);\n const counts: ExtensionBundleCounts = {\n extensionStorage: 0,\n extensionUrls: 0,\n opcodes: 0,\n projectExtensions: 0,\n };\n assert(isObject(rewritten.extensionURLs), 'project.source.json extensionURLs must be an object.');\n assert(\n !Object.hasOwn(rewritten.extensionURLs, bundle.id),\n `project.source.json already uses bundle ID: ${bundle.id}`,\n );\n for (const memberId of bundle.members) {\n assert(\n rewritten.extensionURLs[memberId] === `embedded-extension:extensions/${memberId}.js`,\n `Extension bundle ${bundle.id} member URL mismatch: ${memberId}`,\n );\n }\n const extensionUrls = replaceMemberKeys(\n rewritten.extensionURLs,\n memberIds,\n bundle.id,\n () => `embedded-extension:extensions/${bundle.id}.js`,\n );\n assert(\n extensionUrls.inserted,\n `Extension bundle ${bundle.id} did not replace any extension URL.`,\n );\n rewritten.extensionURLs = extensionUrls.replacement;\n counts.extensionUrls = bundle.members.length + 1;\n\n if (rewritten.extensions !== undefined) {\n assert(\n Array.isArray(rewritten.extensions),\n 'project.source.json extensions must be an array when present.',\n );\n const output: unknown[] = [];\n let inserted = false;\n for (const id of rewritten.extensions as unknown[]) {\n if (typeof id === 'string' && memberIds.has(id)) {\n counts.projectExtensions += 1;\n if (!inserted) {\n output.push(bundle.id);\n inserted = true;\n }\n } else {\n output.push(id);\n }\n }\n rewritten.extensions = output;\n }\n\n const originalGlobalStorage = rewritten.extensionStorage;\n rewritten.extensionStorage = bundleStorage(rewritten.extensionStorage, bundle);\n if (rewritten.extensionStorage !== originalGlobalStorage) counts.extensionStorage += 1;\n for (const target of (rewritten.targets as unknown[] | undefined) ?? []) {\n if (!isObject(target)) continue;\n const originalTargetStorage = target.extensionStorage;\n target.extensionStorage = bundleStorage(target.extensionStorage, bundle);\n if (target.extensionStorage !== originalTargetStorage) counts.extensionStorage += 1;\n }\n\n rewriteOpcodeValues(rewritten.targets, bundle, counts);\n rewriteOpcodeValues(rewritten.monitors, bundle, counts);\n const remainingReferences = collectRemainingOpcodeReferences(rewritten, bundle);\n assert(\n remainingReferences.length === 0,\n `Extension bundle ${bundle.id} has unsupported opcode references at: ` +\n remainingReferences.slice(0, 8).join(', '),\n );\n return {counts, project: rewritten};\n}\n\nexport function buildExtensionBundles({\n extensionBundles,\n extensionContents,\n extensions,\n project,\n}: BuildExtensionBundlesInput): BuildExtensionBundlesResult {\n if (extensionBundles.length === 0) {\n return {bundlePlans: [], extensionContents, extensions, project};\n }\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundlesByMemberId = new Map<string, ExtensionBundleConfiguration>();\n const bundlePlans: ExtensionBundlePlan[] = [];\n let bundledProject = project;\n const bundledContents = new Map(extensionContents);\n\n for (const bundle of extensionBundles) {\n const components = readBundleComponents(bundle, extensionsById, extensionContents);\n const rewrite = rewriteProjectForBundle(bundledProject, bundle);\n const contents = createStaticExtensionBundle(bundle, components, project);\n bundledProject = rewrite.project;\n bundledContents.set(bundle.id, contents);\n for (const memberId of bundle.members) {\n bundlesByMemberId.set(memberId, bundle);\n bundledContents.delete(memberId);\n }\n bundlePlans.push({bundle, components, contents, counts: rewrite.counts});\n }\n\n const bundledExtensions: EmbeddedExtension[] = [];\n const emittedBundleIds = new Set<string>();\n for (const extension of extensions) {\n const bundle = bundlesByMemberId.get(extension.id);\n if (!bundle) {\n bundledExtensions.push(extension);\n } else if (!emittedBundleIds.has(bundle.id)) {\n emittedBundleIds.add(bundle.id);\n bundledExtensions.push({\n encoding: 'base64',\n id: bundle.id,\n mediaType: 'text/javascript',\n parameters: [],\n path: `extensions/${bundle.id}.js`,\n });\n }\n }\n return {\n bundlePlans,\n extensionContents: bundledContents,\n extensions: bundledExtensions,\n project: bundledProject,\n };\n}\n\nexport {validateBundleId, validateBundleName};\n"],"mappings":";;;AAYA,IAAa,gCAAgC;AAqC7C,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,iBAAiB,IAAa,cAAc,uBAA+B;CAClF,OACE,OAAO,OAAO,YAAY,eAAe,KAAK,EAAE,GAChD,GAAG,YAAY,0CAA0C,KAAK,UAAU,EAAE,GAC5E;CACA,OAAO;AACT;AAEA,SAAS,mBAAmB,MAAuB;CACjD,OACE,OAAO,SAAS,YAAY,KAAK,KAAK,MAAM,QAAQ,KAAK,SAAS,KAAK,CAAC,UAAU,KAAK,IAAI,GAC3F,0DAA0D,KAAK,UAAU,IAAI,GAC/E;CACA,OAAO;AACT;AAEA,SAAgB,sCACd,kBACA,YACgC;CAChC,IAAI,qBAAqB,KAAA,GAAW,OAAO,CAAC;CAC5C,OACE,MAAM,QAAQ,gBAAgB,GAC9B,6DACF;CAEA,MAAM,iBAAiB,IAAI,IAAI,WAAW,KAAK,cAAc,CAAC,UAAU,IAAI,SAAS,CAAC,CAAC;CACvF,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,mCAAmB,IAAI,IAAY;CAEzC,OAAQ,iBAA+B,KAAK,QAAQ,gBAAgB;EAClE,OAAO,SAAS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AI,SAAS,CAAC,CAAC;CACvF,MAAM,oCAAoB,IAAI,IAA0C;CACxE,MAAM,cAAqC,CAAC;CAC5C,IAAI,iBAAiB;CACrB,MAAM,kBAAkB,IAAI,IAAI,iBAAiB;CAEjD,KAAK,MAAM,UAAU,kBAAkB;EACrC,MAAM,aAAa,qBAAqB,QAAQ,gBAAgB,iBAAiB;EACjF,MAAM,UAAU,wBAAwB,gBAAgB,MAAM;EAC9D,MAAM,WAAW,4BAA4B,QAAQ,YAAY,OAAO;EACxE,iBAAiB,QAAQ;EACzB,gBAAgB,IAAI,OAAO,IAAI,QAAQ;EACvC,KAAK,MAAM,YAAY,OAAO,SAAS;GACrC,kBAAkB,IAAI,UAAU,MAAM;GACtC,gBAAgB,OAAO,QAAQ;EACjC;EACA,YAAY,KAAK;GAAC;GAAQ;GAAY;GAAU,QAAQ,QAAQ;EAAM,CAAC;CACzE;CAEA,MAAM,oBAAyC,CAAC;CAChD,MAAM,mCAAmB,IAAI,IAAY;CACzC,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,SAAS,kBAAkB,IAAI,UAAU,EAAE;EACjD,IAAI,CAAC,QACH,kBAAkB,KAAK,SAAS;OAC3B,IAAI,CAAC,iBAAiB,IAAI,OAAO,EAAE,GAAG;GAC3C,iBAAiB,IAAI,OAAO,EAAE;GAC9B,kBAAkB,KAAK;IACrB,UAAU;IACV,IAAI,OAAO;IACX,WAAW;IACX,YAAY,CAAC;IACb,MAAM,cAAc,OAAO,GAAG;GAChC,CAAC;EACH;CACF;CACA,OAAO;EACL;EACA,mBAAmB;EACnB,YAAY;EACZ,SAAS;CACX;AACF"}
|
|
1
|
+
{"version":3,"file":"extension-bundle.js","names":[],"sources":["../src/extension-bundle.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {assert} from './assert';\nimport {extensionHeaderMetadata, unsandboxedRequirement} from './extension-dependencies';\nimport type {ExtensionHeaderMetadata, UnsandboxedRequirement} from './extension-dependencies';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n UnknownRecord,\n} from './types';\n\nexport const extensionBundleRecoveryMarker = 'SB3-Toolchain-Reversible-Bundle-v1';\n\nexport interface ExtensionBundleComponent {\n contents: string;\n extension: EmbeddedExtension;\n metadata: ExtensionHeaderMetadata;\n originalContents: Buffer;\n}\n\nexport interface ExtensionBundleCounts {\n extensionStorage: number;\n extensionUrls: number;\n opcodes: number;\n projectExtensions: number;\n}\n\nexport interface ExtensionBundlePlan {\n bundle: ExtensionBundleConfiguration;\n components: ExtensionBundleComponent[];\n contents: Buffer;\n counts: ExtensionBundleCounts;\n}\n\nexport interface BuildExtensionBundlesInput {\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n}\n\nexport interface BuildExtensionBundlesResult {\n bundlePlans: ExtensionBundlePlan[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction validateBundleId(id: unknown, description = 'Extension bundle ID'): string {\n assert(\n typeof id === 'string' && /^[a-z0-9]+$/u.test(id),\n `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`,\n );\n return id;\n}\n\n/**\n * Shown in the palette when a bundle runs sandboxed although a member declared\n * `// Unsandboxed: required` (the members then do not run) or `optional` (they run with less).\n */\nexport const defaultSandboxedNotices: Readonly<\n Record<'required' | 'optional', Readonly<Record<string, string>>>\n> = Object.freeze({\n required: Object.freeze({\n en:\n 'This extension must run without the sandbox.\\n' +\n 'Load the project again and, in the extension\\n' +\n 'security dialog, check \"Run without sandbox\"\\n' +\n 'before allowing it.',\n ja:\n 'この拡張機能はサンドボックスなしで実行する必要があります。\\n' +\n 'プロジェクトを開き直し、拡張機能セキュリティの画面で\\n' +\n '「サンドボックスなしで実行する」にチェックを付けてから\\n' +\n '許可してください。',\n }),\n optional: Object.freeze({\n en:\n 'Running in the sandbox: some features are unavailable.\\n' +\n 'To use them, load the project again and check\\n' +\n '\"Run without sandbox\" in the extension security dialog.',\n ja:\n 'サンドボックス内で実行中のため、一部の機能が使えません。\\n' +\n '使うには、プロジェクトを開き直し、拡張機能セキュリティの画面で\\n' +\n '「サンドボックスなしで実行する」にチェックを付けてください。',\n }),\n});\n\n/**\n * Derives a bundle's requirement from its members' declarations: any `required` member makes the\n * bundle required; otherwise any `optional` member makes it optional; it is `not-needed` only when\n * every member says so. `null` means no member declares anything.\n */\nexport function bundleUnsandboxedRequirement(\n components: readonly Pick<ExtensionBundleComponent, 'metadata'>[],\n): UnsandboxedRequirement | null {\n const declared = components.map((component) => unsandboxedRequirement(component.metadata));\n if (declared.includes('required')) return 'required';\n if (declared.includes('optional')) return 'optional';\n if (declared.length > 0 && declared.every((requirement) => requirement === 'not-needed')) {\n return 'not-needed';\n }\n return null;\n}\n\nfunction validateSandboxedNotice(notice: unknown, bundleId: string): Record<string, string> {\n assert(\n isObject(notice) && Object.keys(notice).length > 0,\n `Extension bundle ${bundleId} sandboxedNotice must be a non-empty object of locale messages.`,\n );\n const validated: Record<string, string> = {};\n for (const [locale, message] of Object.entries(notice)) {\n assert(\n /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/u.test(locale),\n `Extension bundle ${bundleId} sandboxedNotice locale must be a lowercase language tag: ` +\n JSON.stringify(locale),\n );\n assert(\n typeof message === 'string' && message.trim().length > 0,\n `Extension bundle ${bundleId} sandboxedNotice.${locale} must be a non-empty string.`,\n );\n validated[locale] = message;\n }\n return validated;\n}\n\nfunction validateBundleName(name: unknown): string {\n assert(\n typeof name === 'string' && name.trim() === name && name.length > 0 && !/[\\r\\n]/u.test(name),\n `Extension bundle name must be a non-empty single line: ${JSON.stringify(name)}`,\n );\n return name;\n}\n\nexport function validateExtensionBundleConfigurations(\n extensionBundles: unknown,\n extensions: EmbeddedExtension[],\n): ExtensionBundleConfiguration[] {\n if (extensionBundles === undefined) return [];\n assert(\n Array.isArray(extensionBundles),\n 'embedded-extensions.json extensionBundles must be an array.',\n );\n\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundleIds = new Set<string>();\n const bundledMemberIds = new Set<string>();\n\n return (extensionBundles as unknown[]).map((bundle, bundleIndex) => {\n assert(isObject(bundle), `Extension bundle ${bundleIndex} must be an object.`);\n const id = validateBundleId(bundle.id, `Extension bundle ${bundleIndex} ID`);\n const name = validateBundleName(bundle.name);\n assert(!extensionsById.has(id), `Extension bundle ID collides with an extension: ${id}`);\n assert(!bundleIds.has(id), `Duplicate extension bundle ID: ${id}`);\n bundleIds.add(id);\n assert(\n Array.isArray(bundle.members) && bundle.members.length >= 2,\n `Extension bundle ${id} must contain at least two members.`,\n );\n assert(\n bundle.recoveryCapsule === undefined || typeof bundle.recoveryCapsule === 'boolean',\n `Extension bundle ${id} recoveryCapsule must be a boolean when present.`,\n );\n const capsuleFlag = bundle.recoveryCapsule;\n const sandboxedNotice =\n bundle.sandboxedNotice === undefined\n ? undefined\n : validateSandboxedNotice(bundle.sandboxedNotice, id);\n\n const localMemberIds = new Set<string>();\n const members: string[] = [];\n for (const rawMemberId of bundle.members as unknown[]) {\n const memberId = validateBundleId(rawMemberId, `Extension bundle ${id} member ID`);\n assert(\n extensionsById.has(memberId),\n `Extension bundle ${id} has unknown member: ${memberId}`,\n );\n assert(!localMemberIds.has(memberId), `Extension bundle ${id} repeats member: ${memberId}`);\n assert(\n !bundledMemberIds.has(memberId),\n `Embedded extension belongs to more than one bundle: ${memberId}`,\n );\n localMemberIds.add(memberId);\n bundledMemberIds.add(memberId);\n members.push(memberId);\n }\n return {\n id,\n members,\n name,\n ...(capsuleFlag === undefined ? {} : {recoveryCapsule: capsuleFlag}),\n ...(sandboxedNotice === undefined ? {} : {sandboxedNotice}),\n };\n });\n}\n\nfunction readBundleComponents(\n bundle: ExtensionBundleConfiguration,\n extensionsById: Map<string, EmbeddedExtension>,\n extensionContents: Map<string, Uint8Array>,\n): ExtensionBundleComponent[] {\n return bundle.members.map((memberId) => {\n const extension = extensionsById.get(memberId);\n const contents = extensionContents.get(memberId);\n assert(contents, `Extension bundle ${bundle.id} has no contents for member: ${memberId}`);\n assert(\n extension,\n `Extension bundle ${bundle.id} has no manifest entry for member: ${memberId}`,\n );\n assert(\n extension.mediaType === 'text/javascript' || extension.mediaType === 'application/javascript',\n `Extension bundle ${bundle.id} member ${memberId} must be JavaScript, got ${extension.mediaType}.`,\n );\n const metadata = extensionHeaderMetadata(contents);\n assert(\n metadata.id === memberId,\n `Extension bundle ${bundle.id} member header ID mismatch: expected ${memberId}, ` +\n `got ${metadata.id ?? '(missing)'}`,\n );\n for (const [property, label] of [\n ['name', 'Name'],\n ['author', 'By'],\n ['description', 'Description'],\n ['license', 'License'],\n ] as const) {\n assert(\n metadata[property],\n `Extension bundle ${bundle.id} member ${memberId} requires a // ${label}: header.`,\n );\n }\n unsandboxedRequirement(metadata);\n const source = Buffer.from(contents).toString('utf8');\n assert(\n !source.startsWith('#!'),\n `Extension bundle ${bundle.id} member ${memberId} cannot use a shebang.`,\n );\n assert(\n !source.includes(extensionBundleRecoveryMarker),\n `Extension bundle ${bundle.id} member ${memberId} contains the reserved recovery marker.`,\n );\n const registrations = source.match(/\\bScratch\\s*\\.\\s*extensions\\s*\\.\\s*register\\s*\\(/gu) ?? [];\n assert(\n registrations.length === 1,\n `Extension bundle ${bundle.id} member ${memberId} must contain exactly one synchronous ` +\n `Scratch.extensions.register call; found ${registrations.length}.`,\n );\n return {contents: source, extension, metadata, originalContents: Buffer.from(contents)};\n });\n}\n\nfunction commentLine(value: unknown): string {\n return String(value).replaceAll('\\r', ' ').replaceAll('\\n', ' ');\n}\n\nfunction bundleHeader(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n): string {\n const authors = [...new Set(components.map((component) => component.metadata.author))];\n const lines = [\n `// Name: ${commentLine(bundle.name)}`,\n `// ID: ${bundle.id}`,\n `// Description: Static bundle of ${components.length} TurboWarp extensions.`,\n `// By: ${commentLine(authors.join(', '))}`,\n '// License: See the bundled extension notices below.',\n ];\n const requirement = bundleUnsandboxedRequirement(components);\n if (requirement !== null) lines.push(`// Unsandboxed: ${requirement}`);\n lines.push('//', '// Bundled extensions:');\n for (const component of components) {\n lines.push(\n `// - Name: ${commentLine(component.metadata.name)}`,\n `// ID: ${component.metadata.id}`,\n `// By: ${commentLine(component.metadata.author)}`,\n `// Description: ${commentLine(component.metadata.description)}`,\n `// License: ${commentLine(component.metadata.license)}`,\n );\n if (component.metadata.unsandboxed !== null) {\n lines.push(`// Unsandboxed: ${component.metadata.unsandboxed}`);\n }\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction componentLoadSource(component: ExtensionBundleComponent): string {\n const memberId = JSON.stringify(component.metadata.id);\n const source = component.contents.endsWith('\\n') ? component.contents : `${component.contents}\\n`;\n return `loadComponent(${memberId}, function (Scratch) {\\n${source}});\\n`;\n}\n\nfunction percentEncode(contents: Uint8Array | string): string {\n return [...Buffer.from(contents)]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction componentDataUrl(component: ExtensionBundleComponent): string {\n const metadata = [component.extension.mediaType, ...component.extension.parameters].join(';');\n const originalContents = component.originalContents ?? Buffer.from(component.contents);\n if (component.extension.encoding === 'base64') {\n return `data:${metadata};base64,${originalContents.toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(originalContents)}`;\n}\n\nfunction recoveryCapsule(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined,\n): UnknownRecord {\n return {\n formatVersion: 1,\n bundle: {id: bundle.id, name: bundle.name},\n components: components.map((component) => ({\n dataUrl: componentDataUrl(component),\n id: component.metadata.id,\n })),\n originalExtensionIds: Array.isArray(originalProject?.extensions)\n ? [...(originalProject.extensions as unknown[])]\n : null,\n originalExtensionUrlIds: Object.keys(originalProject?.extensionURLs ?? {}),\n };\n}\n\nfunction sandboxedNotice(\n bundle: ExtensionBundleConfiguration,\n requirement: UnsandboxedRequirement | null,\n): Record<string, string> | null {\n if (requirement !== 'required' && requirement !== 'optional') {\n assert(\n bundle.sandboxedNotice === undefined,\n `Extension bundle ${bundle.id} sandboxedNotice needs a member that declares ` +\n '// Unsandboxed: required or optional.',\n );\n return null;\n }\n return {...defaultSandboxedNotices[requirement], ...bundle.sandboxedNotice};\n}\n\n/**\n * Detects a sandboxed load for a bundle whose members declared they need (`required`) or benefit\n * from (`optional`) TurboWarp's unsandboxed API. A required bundle registers a placeholder under\n * the bundle ID instead of running its members, so none can fail on a missing `Scratch.vm` and the\n * project still finishes loading: a sandboxed iframe that throws before registering leaves\n * TurboWarp waiting forever, and a worker reports only a generic failure. An optional bundle runs\n * its members and prefixes the palette with the notice. Bundles without a declaration get nothing.\n */\nfunction sandboxedGuardSource(\n requirement: UnsandboxedRequirement | null,\n notice: Record<string, string> | null,\n): string {\n if (notice === null) return '';\n const required = requirement === 'required';\n return `\n const SANDBOXED = !Scratch.extensions || Scratch.extensions.unsandboxed !== true;\n const SANDBOXED_NOTICE = ${JSON.stringify(notice)};\n const currentLocale = () => {\n try {\n if (Scratch.translate && typeof Scratch.translate.language === 'string') {\n return Scratch.translate.language;\n }\n } catch (_error) {\n // Fall through to the browser language.\n }\n return typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en';\n };\n const sandboxedNoticeText = () => {\n const locale = String(currentLocale()).toLowerCase();\n const language = locale.split('-')[0];\n if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, locale)) return SANDBOXED_NOTICE[locale];\n if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, language)) return SANDBOXED_NOTICE[language];\n return SANDBOXED_NOTICE.en;\n };\n const sandboxedNoticeBlocks = () => ['⚠ ' + BUNDLE_NAME, ...sandboxedNoticeText().split('\\\\n')]\n .filter((line) => line.length > 0)\n .map((line) => ({\n blockType: (Scratch.BlockType && Scratch.BlockType.LABEL) || 'label',\n sb3Toolchain: {kind: 'bundle-sandboxed-notice'},\n text: line,\n }));\n if (SANDBOXED && typeof console !== 'undefined') {\n const report = console.${required ? 'error' : 'warn'} || console.log;\n report.call(console, '[' + BUNDLE_ID + '] ' + BUNDLE_NAME + ' ${required ? 'requires' : 'works better with'} unsandboxed loading. ' + sandboxedNoticeText().replace(/\\\\n/gu, ' '));\n }\n${\n required\n ? ` if (SANDBOXED) {\n class SandboxedExtensionBundleNotice {\n getInfo() {\n return {\n id: BUNDLE_ID,\n name: BUNDLE_NAME,\n color1: '#D65C5C',\n blocks: sandboxedNoticeBlocks(),\n menus: {},\n };\n }\n }\n Scratch.extensions.register(new SandboxedExtensionBundleNotice());\n return;\n }\n`\n : ''\n}`;\n}\n\nexport function createStaticExtensionBundle(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined = undefined,\n): Buffer {\n const componentIds = JSON.stringify(components.map((component) => component.metadata.id));\n const header = bundleHeader(bundle, components);\n const requirement = bundleUnsandboxedRequirement(components);\n const notice = sandboxedNotice(bundle, requirement);\n const loaders = components.map(componentLoadSource).join('\\n');\n const runtime = `(function (Scratch) {\n 'use strict';\n\n const BUNDLE_ID = ${JSON.stringify(bundle.id)};\n const BUNDLE_NAME = ${JSON.stringify(bundle.name)};\n const COMPONENT_IDS = ${componentIds};\n${sandboxedGuardSource(requirement, notice)} const components = new Map();\n\n const rewriteOpcode = (componentId, opcode) => {\n const prefix = componentId + '_';\n return typeof opcode === 'string' && opcode.startsWith(prefix)\n ? BUNDLE_ID + '_' + componentId + '__' + opcode.slice(prefix.length)\n : opcode;\n };\n\n const rewriteBundleOpcode = (opcode) => {\n for (const componentId of COMPONENT_IDS) {\n const rewritten = rewriteOpcode(componentId, opcode);\n if (rewritten !== opcode) return rewritten;\n }\n return opcode;\n };\n\n const xmlEscape = (value) => String(value).replace(/[<>&'\"]/gu, (character) => ({\n '<': '<',\n '>': '>',\n '&': '&',\n \"'\": ''',\n '\"': '"',\n })[character]);\n\n const installStorageAliases = (storage) => {\n if (!storage || typeof storage !== 'object') return;\n const hasBundleStorage = Object.prototype.hasOwnProperty.call(storage, BUNDLE_ID);\n const hasMemberStorage = COMPONENT_IDS.some((id) => Object.prototype.hasOwnProperty.call(storage, id));\n if (!hasBundleStorage && !hasMemberStorage) return;\n let bundleStorage = storage[BUNDLE_ID];\n if (!bundleStorage || typeof bundleStorage !== 'object' || Array.isArray(bundleStorage)) {\n bundleStorage = {formatVersion: 1, components: {}};\n storage[BUNDLE_ID] = bundleStorage;\n }\n if (!bundleStorage.components || typeof bundleStorage.components !== 'object' || Array.isArray(bundleStorage.components)) {\n throw new Error('Invalid extension storage for static bundle ' + BUNDLE_ID + '.');\n }\n for (const id of COMPONENT_IDS) {\n const descriptor = Object.getOwnPropertyDescriptor(storage, id);\n if (descriptor && !descriptor.get && !Object.prototype.hasOwnProperty.call(bundleStorage.components, id)) {\n bundleStorage.components[id] = storage[id];\n }\n if (!descriptor || !descriptor.get) {\n delete storage[id];\n Object.defineProperty(storage, id, {\n configurable: true,\n enumerable: false,\n get: () => bundleStorage.components[id],\n set: (value) => {\n bundleStorage.components[id] = value;\n },\n });\n }\n }\n };\n\n const installAllStorageAliases = () => {\n const runtime = Scratch.vm && Scratch.vm.runtime;\n if (!runtime) return;\n installStorageAliases(runtime.extensionStorage);\n for (const target of runtime.targets || []) installStorageAliases(target.extensionStorage);\n };\n\n installAllStorageAliases();\n\n const createComponentScratch = (componentId, register) => {\n const baseRuntime = Scratch.vm && Scratch.vm.runtime;\n const runtime = baseRuntime && new Proxy(baseRuntime, {\n get(target, property) {\n if (property === 'startHats') {\n return (opcode, ...args) => target.startHats(rewriteOpcode(componentId, opcode), ...args);\n }\n if (property === 'getOpcodeFunction') {\n return (opcode, ...args) => target.getOpcodeFunction(rewriteBundleOpcode(opcode), ...args);\n }\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const baseVm = Scratch.vm;\n const vm = baseVm && new Proxy(baseVm, {\n get(target, property) {\n if (property === 'runtime') return runtime;\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const extensions = Object.create(Scratch.extensions);\n Object.defineProperty(extensions, 'register', {value: register});\n return new Proxy(Scratch, {\n get(target, property) {\n if (property === 'extensions') return extensions;\n if (property === 'vm') return vm;\n return Reflect.get(target, property, target);\n },\n });\n };\n\n const loadComponent = (componentId, execute) => {\n let registration = null;\n let registrationCount = 0;\n let acceptingRegistration = true;\n const componentScratch = createComponentScratch(componentId, (extension) => {\n if (!acceptingRegistration) {\n throw new Error('Asynchronous registration is unsupported in static bundle member ' + componentId + '.');\n }\n registration = extension;\n registrationCount += 1;\n });\n execute(componentScratch);\n acceptingRegistration = false;\n if (registrationCount !== 1) {\n throw new Error(\n 'Static bundle member ' + componentId + ' must register exactly once synchronously; got ' + registrationCount + '.',\n );\n }\n components.set(componentId, registration);\n };\n\n${loaders}\n class StaticExtensionBundle {\n constructor() {\n this.delegates = new Map();\n }\n\n addDelegate(name, component, originalName) {\n if (this.delegates.has(name)) throw new Error('Duplicate static bundle delegate: ' + name);\n if (typeof originalName !== 'string' || typeof component[originalName] !== 'function') {\n throw new Error('Missing static bundle handler: ' + originalName);\n }\n this.delegates.set(name, {component, originalName});\n this[name] = (...args) => {\n installAllStorageAliases();\n return component[originalName](...args);\n };\n }\n\n getInfo() {\n const result = {\n id: BUNDLE_ID,\n name: BUNDLE_NAME,\n color1: '#5B67A5',\n blocks: [],\n menus: {},\n customFieldTypes: {},\n };${\n requirement === 'optional'\n ? `\n if (SANDBOXED) result.blocks.push(...sandboxedNoticeBlocks(), '---', '---');`\n : ''\n }\n this.delegates.clear();\n const transformedOpcodes = new Set();\n\n for (const [componentIndex, componentId] of COMPONENT_IDS.entries()) {\n const component = components.get(componentId);\n const info = component.getInfo();\n if (!info || info.id !== componentId) {\n throw new Error(\n 'Static bundle member runtime ID mismatch: expected ' + componentId + ', got ' +\n (info && info.id ? info.id : '(missing)') + '.',\n );\n }\n if (typeof info.name !== 'string' || info.name.length === 0) {\n throw new Error('Static bundle member ' + componentId + ' must have a non-empty name.');\n }\n const namespace = componentId + '__';\n const memberBlockIconURI =\n typeof info.blockIconURI === 'string' && info.blockIconURI.length > 0\n ? info.blockIconURI\n : null;\n const customFieldTypes = info.customFieldTypes || {};\n for (const [fieldName, fieldInfo] of Object.entries(customFieldTypes)) {\n result.customFieldTypes[namespace + fieldName] = fieldInfo;\n }\n if (componentIndex > 0) result.blocks.push('---', '---');\n result.blocks.push({\n blockType: Scratch.BlockType.LABEL,\n sb3Toolchain: {kind: 'bundle-member-heading', memberId: componentId},\n text: '◆ ' + info.name + ' [' + componentId + '] ◆',\n });\n if (info.docsURI) {\n const docsURI = String(info.docsURI);\n result.blocks.push({\n blockType: Scratch.BlockType.XML,\n sb3Toolchain: {\n docsURI,\n kind: 'bundle-member-docs',\n memberId: componentId,\n },\n xml: '<button text=\"Open Documentation\" callbackKey=\"OPEN_EXTENSION_DOCS\" callbackData=\"' + xmlEscape(docsURI) + '\"></button>',\n });\n }\n for (const block of info.blocks || []) {\n if (block === '---') {\n result.blocks.push(block);\n continue;\n }\n if (!block || typeof block !== 'object') throw new Error('Invalid block in static bundle member ' + componentId + '.');\n if (block.blockType === Scratch.BlockType.XML) {\n throw new Error('XML blocks are unsupported in static bundle member ' + componentId + '.');\n }\n const transformed = {...block};\n if (\n memberBlockIconURI !== null &&\n !Object.prototype.hasOwnProperty.call(block, 'blockIconURI') &&\n block.blockType !== Scratch.BlockType.LABEL &&\n block.blockType !== Scratch.BlockType.BUTTON\n ) {\n transformed.blockIconURI = memberBlockIconURI;\n }\n if (block.arguments) {\n transformed.arguments = Object.fromEntries(\n Object.entries(block.arguments).map(([argumentName, argument]) => {\n const transformedArgument = {...argument};\n if (typeof transformedArgument.menu === 'string') {\n transformedArgument.menu = namespace + transformedArgument.menu;\n }\n if (typeof transformedArgument.type === 'string' && Object.prototype.hasOwnProperty.call(customFieldTypes, transformedArgument.type)) {\n transformedArgument.type = namespace + transformedArgument.type;\n }\n return [argumentName, transformedArgument];\n }),\n );\n }\n if (block.blockType === Scratch.BlockType.LABEL) {\n result.blocks.push(transformed);\n continue;\n }\n if (block.blockType === Scratch.BlockType.BUTTON) {\n const delegateName = namespace + 'button__' + block.func;\n transformed.func = delegateName;\n this.addDelegate(delegateName, component, block.func);\n result.blocks.push(transformed);\n continue;\n }\n if (typeof block.opcode !== 'string' || block.opcode.length === 0) {\n throw new Error('Missing opcode in static bundle member ' + componentId + '.');\n }\n transformed.opcode = namespace + block.opcode;\n if (transformedOpcodes.has(transformed.opcode)) {\n throw new Error('Duplicate static bundle opcode: ' + transformed.opcode);\n }\n transformedOpcodes.add(transformed.opcode);\n if (block.blockType !== Scratch.BlockType.EVENT) {\n const originalName = block.func || block.opcode;\n transformed.func = transformed.opcode;\n this.addDelegate(transformed.opcode, component, originalName);\n } else {\n delete transformed.func;\n }\n result.blocks.push(transformed);\n }\n for (const [menuName, menu] of Object.entries(info.menus || {})) {\n const transformedMenuName = namespace + menuName;\n if (typeof menu === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu);\n result.menus[transformedMenuName] = {items: delegateName};\n } else if (Array.isArray(menu)) {\n result.menus[transformedMenuName] = [...menu];\n } else if (menu && typeof menu === 'object') {\n const transformedMenu = {...menu};\n if (typeof menu.items === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu.items);\n transformedMenu.items = delegateName;\n }\n result.menus[transformedMenuName] = transformedMenu;\n } else {\n throw new Error('Invalid menu in static bundle member ' + componentId + ': ' + menuName + '.');\n }\n }\n }\n return result;\n }\n }\n\n Scratch.extensions.register(new StaticExtensionBundle());\n})(Scratch);\n`;\n if (bundle.recoveryCapsule !== true) {\n return Buffer.from(`${header}\\n${runtime}`);\n }\n const capsule = Buffer.from(\n JSON.stringify(\n recoveryCapsule(\n bundle,\n components,\n originalProject ?? {\n extensions: bundle.members,\n extensionURLs: Object.fromEntries(bundle.members.map((memberId) => [memberId, true])),\n },\n ),\n ),\n ).toString('base64');\n return Buffer.from(`${header}\\n${runtime}\\n// ${extensionBundleRecoveryMarker}: ${capsule}\\n`);\n}\n\nfunction replaceMemberKeys(\n object: UnknownRecord,\n memberIds: Set<string>,\n bundleId: string,\n bundleValue: (value: unknown) => unknown,\n): {inserted: boolean; replacement: UnknownRecord} {\n const replacement: UnknownRecord = {};\n let inserted = false;\n for (const [key, value] of Object.entries(object)) {\n if (memberIds.has(key)) {\n if (!inserted) {\n replacement[bundleId] = bundleValue(value);\n inserted = true;\n }\n } else {\n replacement[key] = value;\n }\n }\n return {inserted, replacement};\n}\n\nfunction bundleStorage(storage: unknown, bundle: ExtensionBundleConfiguration): unknown {\n if (!isObject(storage)) return storage;\n const memberIds = new Set(bundle.members);\n const componentStorage: UnknownRecord = {};\n for (const memberId of bundle.members) {\n if (Object.hasOwn(storage, memberId)) componentStorage[memberId] = storage[memberId];\n }\n if (Object.keys(componentStorage).length === 0) return storage;\n assert(\n !Object.hasOwn(storage, bundle.id),\n `Extension storage already contains bundle ID: ${bundle.id}`,\n );\n return replaceMemberKeys(storage, memberIds, bundle.id, () => ({\n formatVersion: 1,\n components: componentStorage,\n })).replacement;\n}\n\nfunction rewriteOpcodeValues(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n counts: ExtensionBundleCounts,\n): void {\n if (!value || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const entry of value as unknown[]) rewriteOpcodeValues(entry, bundle, counts);\n return;\n }\n const record = value as UnknownRecord;\n for (const [key, entry] of Object.entries(record)) {\n if (key === 'opcode' && typeof entry === 'string') {\n for (const memberId of bundle.members) {\n const prefix = `${memberId}_`;\n if (entry.startsWith(prefix)) {\n record[key] = `${bundle.id}_${memberId}__${entry.slice(prefix.length)}`;\n counts.opcodes += 1;\n break;\n }\n }\n } else {\n rewriteOpcodeValues(entry, bundle, counts);\n }\n }\n}\n\nfunction collectRemainingOpcodeReferences(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n): string[] {\n const references: string[] = [];\n const prefixes = bundle.members.map((memberId) => `${memberId}_`);\n function visit(current: unknown, pointer: string): void {\n if (typeof current === 'string') {\n if (prefixes.some((prefix) => current.startsWith(prefix))) references.push(pointer || '/');\n return;\n }\n if (!current || typeof current !== 'object') return;\n if (Array.isArray(current)) {\n (current as unknown[]).forEach((entry, index) => visit(entry, `${pointer}/${index}`));\n return;\n }\n for (const [key, entry] of Object.entries(current as UnknownRecord)) {\n visit(entry, `${pointer}/${key}`);\n }\n }\n visit(value, '');\n return references;\n}\n\nfunction rewriteProjectForBundle(\n project: ProjectJson,\n bundle: ExtensionBundleConfiguration,\n): {counts: ExtensionBundleCounts; project: ProjectJson} {\n const rewritten = structuredClone(project);\n const memberIds = new Set(bundle.members);\n const counts: ExtensionBundleCounts = {\n extensionStorage: 0,\n extensionUrls: 0,\n opcodes: 0,\n projectExtensions: 0,\n };\n assert(isObject(rewritten.extensionURLs), 'project.source.json extensionURLs must be an object.');\n assert(\n !Object.hasOwn(rewritten.extensionURLs, bundle.id),\n `project.source.json already uses bundle ID: ${bundle.id}`,\n );\n for (const memberId of bundle.members) {\n assert(\n rewritten.extensionURLs[memberId] === `embedded-extension:extensions/${memberId}.js`,\n `Extension bundle ${bundle.id} member URL mismatch: ${memberId}`,\n );\n }\n const extensionUrls = replaceMemberKeys(\n rewritten.extensionURLs,\n memberIds,\n bundle.id,\n () => `embedded-extension:extensions/${bundle.id}.js`,\n );\n assert(\n extensionUrls.inserted,\n `Extension bundle ${bundle.id} did not replace any extension URL.`,\n );\n rewritten.extensionURLs = extensionUrls.replacement;\n counts.extensionUrls = bundle.members.length + 1;\n\n if (rewritten.extensions !== undefined) {\n assert(\n Array.isArray(rewritten.extensions),\n 'project.source.json extensions must be an array when present.',\n );\n const output: unknown[] = [];\n let inserted = false;\n for (const id of rewritten.extensions as unknown[]) {\n if (typeof id === 'string' && memberIds.has(id)) {\n counts.projectExtensions += 1;\n if (!inserted) {\n output.push(bundle.id);\n inserted = true;\n }\n } else {\n output.push(id);\n }\n }\n rewritten.extensions = output;\n }\n\n const originalGlobalStorage = rewritten.extensionStorage;\n rewritten.extensionStorage = bundleStorage(rewritten.extensionStorage, bundle);\n if (rewritten.extensionStorage !== originalGlobalStorage) counts.extensionStorage += 1;\n for (const target of (rewritten.targets as unknown[] | undefined) ?? []) {\n if (!isObject(target)) continue;\n const originalTargetStorage = target.extensionStorage;\n target.extensionStorage = bundleStorage(target.extensionStorage, bundle);\n if (target.extensionStorage !== originalTargetStorage) counts.extensionStorage += 1;\n }\n\n rewriteOpcodeValues(rewritten.targets, bundle, counts);\n rewriteOpcodeValues(rewritten.monitors, bundle, counts);\n const remainingReferences = collectRemainingOpcodeReferences(rewritten, bundle);\n assert(\n remainingReferences.length === 0,\n `Extension bundle ${bundle.id} has unsupported opcode references at: ` +\n remainingReferences.slice(0, 8).join(', '),\n );\n return {counts, project: rewritten};\n}\n\nexport function buildExtensionBundles({\n extensionBundles,\n extensionContents,\n extensions,\n project,\n}: BuildExtensionBundlesInput): BuildExtensionBundlesResult {\n if (extensionBundles.length === 0) {\n return {bundlePlans: [], extensionContents, extensions, project};\n }\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundlesByMemberId = new Map<string, ExtensionBundleConfiguration>();\n const bundlePlans: ExtensionBundlePlan[] = [];\n let bundledProject = project;\n const bundledContents = new Map(extensionContents);\n\n for (const bundle of extensionBundles) {\n const components = readBundleComponents(bundle, extensionsById, extensionContents);\n const rewrite = rewriteProjectForBundle(bundledProject, bundle);\n const contents = createStaticExtensionBundle(bundle, components, project);\n bundledProject = rewrite.project;\n bundledContents.set(bundle.id, contents);\n for (const memberId of bundle.members) {\n bundlesByMemberId.set(memberId, bundle);\n bundledContents.delete(memberId);\n }\n bundlePlans.push({bundle, components, contents, counts: rewrite.counts});\n }\n\n const bundledExtensions: EmbeddedExtension[] = [];\n const emittedBundleIds = new Set<string>();\n for (const extension of extensions) {\n const bundle = bundlesByMemberId.get(extension.id);\n if (!bundle) {\n bundledExtensions.push(extension);\n } else if (!emittedBundleIds.has(bundle.id)) {\n emittedBundleIds.add(bundle.id);\n bundledExtensions.push({\n encoding: 'base64',\n id: bundle.id,\n mediaType: 'text/javascript',\n parameters: [],\n path: `extensions/${bundle.id}.js`,\n });\n }\n }\n return {\n bundlePlans,\n extensionContents: bundledContents,\n extensions: bundledExtensions,\n project: bundledProject,\n };\n}\n\nexport {validateBundleId, validateBundleName};\n"],"mappings":";;;AAYA,IAAa,gCAAgC;AAqC7C,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,iBAAiB,IAAa,cAAc,uBAA+B;CAClF,OACE,OAAO,OAAO,YAAY,eAAe,KAAK,EAAE,GAChD,GAAG,YAAY,0CAA0C,KAAK,UAAU,EAAE,GAC5E;CACA,OAAO;AACT;;;;;AAMA,IAAa,0BAET,OAAO,OAAO;CAChB,UAAU,OAAO,OAAO;EACtB,IACE;EAIF,IACE;CAIJ,CAAC;CACD,UAAU,OAAO,OAAO;EACtB,IACE;EAGF,IACE;CAGJ,CAAC;AACH,CAAC;;;;;;AAOD,SAAgB,6BACd,YAC+B;CAC/B,MAAM,WAAW,WAAW,KAAK,cAAc,uBAAuB,UAAU,QAAQ,CAAC;CACzF,IAAI,SAAS,SAAS,UAAU,GAAG,OAAO;CAC1C,IAAI,SAAS,SAAS,UAAU,GAAG,OAAO;CAC1C,IAAI,SAAS,SAAS,KAAK,SAAS,OAAO,gBAAgB,gBAAgB,YAAY,GACrF,OAAO;CAET,OAAO;AACT;AAEA,SAAS,wBAAwB,QAAiB,UAA0C;CAC1F,OACE,SAAS,MAAM,KAAK,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,GACjD,oBAAoB,SAA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YAAY;EAClC,MAAM,SAAS,kBAAkB,IAAI,UAAU,EAAE;EACjD,IAAI,CAAC,QACH,kBAAkB,KAAK,SAAS;OAC3B,IAAI,CAAC,iBAAiB,IAAI,OAAO,EAAE,GAAG;GAC3C,iBAAiB,IAAI,OAAO,EAAE;GAC9B,kBAAkB,KAAK;IACrB,UAAU;IACV,IAAI,OAAO;IACX,WAAW;IACX,YAAY,CAAC;IACb,MAAM,cAAc,OAAO,GAAG;GAChC,CAAC;EACH;CACF;CACA,OAAO;EACL;EACA,mBAAmB;EACnB,YAAY;EACZ,SAAS;CACX;AACF"}
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import { EmbeddedExtension, ExtensionSource } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Whether an extension must be loaded with TurboWarp's "Run without sandbox" checked, declared by
|
|
4
|
+
* its `// Unsandboxed:` header line.
|
|
5
|
+
*/
|
|
6
|
+
export type UnsandboxedRequirement = 'required' | 'optional' | 'not-needed';
|
|
7
|
+
export declare const unsandboxedRequirements: readonly UnsandboxedRequirement[];
|
|
2
8
|
export interface ExtensionHeaderMetadata {
|
|
3
9
|
author: string | null;
|
|
4
10
|
description: string | null;
|
|
5
11
|
id: string | null;
|
|
6
12
|
license: string | null;
|
|
7
13
|
name: string | null;
|
|
14
|
+
/** The raw `// Unsandboxed:` value; see {@link unsandboxedRequirement} to validate it. */
|
|
15
|
+
unsandboxed: string | null;
|
|
8
16
|
}
|
|
9
17
|
export interface ManagedExtensionContents {
|
|
10
18
|
actualId: string | null;
|
|
@@ -14,5 +22,7 @@ export interface ManagedExtensionContents {
|
|
|
14
22
|
export declare function extensionIntegrity(contents: Uint8Array | string): string;
|
|
15
23
|
export declare function extensionHeaderId(contents: Uint8Array | string): string | null;
|
|
16
24
|
export declare function extensionHeaderMetadata(contents: Uint8Array | string): ExtensionHeaderMetadata;
|
|
25
|
+
/** Validates a header's `// Unsandboxed:` value; `null` means the extension declares nothing. */
|
|
26
|
+
export declare function unsandboxedRequirement(metadata: ExtensionHeaderMetadata): UnsandboxedRequirement | null;
|
|
17
27
|
export declare function validateExtensionSourceMetadata(extension: EmbeddedExtension): ExtensionSource | null;
|
|
18
28
|
export declare function validateManagedExtensionContents(extension: EmbeddedExtension, contents: Uint8Array | string): ManagedExtensionContents | null;
|
|
@@ -3,6 +3,11 @@ import { validateArchiveEntryName } from "./archive.js";
|
|
|
3
3
|
import { validateExtensionApiManifestSourceMetadata } from "./extension-api-manifest.js";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
//#region src/extension-dependencies.ts
|
|
6
|
+
var unsandboxedRequirements = Object.freeze([
|
|
7
|
+
"required",
|
|
8
|
+
"optional",
|
|
9
|
+
"not-needed"
|
|
10
|
+
]);
|
|
6
11
|
function extensionIntegrity(contents) {
|
|
7
12
|
return `sha256-${createHash("sha256").update(contents).digest("base64")}`;
|
|
8
13
|
}
|
|
@@ -18,9 +23,16 @@ function extensionHeaderMetadata(contents) {
|
|
|
18
23
|
description: readField("Description"),
|
|
19
24
|
id: id && /^[A-Za-z0-9._-]+$/u.test(id) ? id : null,
|
|
20
25
|
license: readField("License"),
|
|
21
|
-
name: readField("Name")
|
|
26
|
+
name: readField("Name"),
|
|
27
|
+
unsandboxed: readField("Unsandboxed")
|
|
22
28
|
};
|
|
23
29
|
}
|
|
30
|
+
/** Validates a header's `// Unsandboxed:` value; `null` means the extension declares nothing. */
|
|
31
|
+
function unsandboxedRequirement(metadata) {
|
|
32
|
+
if (metadata.unsandboxed === null) return null;
|
|
33
|
+
assert(unsandboxedRequirements.includes(metadata.unsandboxed), `Extension ${metadata.id ?? "(unknown)"} declares an invalid // Unsandboxed: header ${JSON.stringify(metadata.unsandboxed)}; use ${unsandboxedRequirements.join(", ")}.`);
|
|
34
|
+
return metadata.unsandboxed;
|
|
35
|
+
}
|
|
24
36
|
function validateExtensionSourceMetadata(extension) {
|
|
25
37
|
if (extension.source === void 0) return null;
|
|
26
38
|
const source = extension.source;
|
|
@@ -54,6 +66,6 @@ function validateManagedExtensionContents(extension, contents) {
|
|
|
54
66
|
};
|
|
55
67
|
}
|
|
56
68
|
//#endregion
|
|
57
|
-
export { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, validateExtensionSourceMetadata, validateManagedExtensionContents };
|
|
69
|
+
export { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandboxedRequirement, unsandboxedRequirements, validateExtensionSourceMetadata, validateManagedExtensionContents };
|
|
58
70
|
|
|
59
71
|
//# sourceMappingURL=extension-dependencies.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-dependencies.js","names":[],"sources":["../src/extension-dependencies.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert} from './assert';\nimport {validateExtensionApiManifestSourceMetadata} from './extension-api-manifest';\nimport type {EmbeddedExtension, ExtensionSource} from './types';\n\nexport interface ExtensionHeaderMetadata {\n author: string | null;\n description: string | null;\n id: string | null;\n license: string | null;\n name: string | null;\n}\n\nexport interface ManagedExtensionContents {\n actualId: string | null;\n integrity: string;\n source: ExtensionSource;\n}\n\nexport function extensionIntegrity(contents: Uint8Array | string): string {\n return `sha256-${createHash('sha256').update(contents).digest('base64')}`;\n}\n\nexport function extensionHeaderId(contents: Uint8Array | string): string | null {\n return extensionHeaderMetadata(contents).id;\n}\n\nexport function extensionHeaderMetadata(contents: Uint8Array | string): ExtensionHeaderMetadata {\n const source = Buffer.from(contents).toString('utf8');\n const readField = (field: string): string | null =>\n source.match(new RegExp(`^// ${field}: (.+)\\\\r?$`, 'mu'))?.[1]?.trim() ?? null;\n const id = readField('ID');\n return {\n author: readField('By'),\n description: readField('Description'),\n id: id && /^[A-Za-z0-9._-]+$/u.test(id) ? id : null,\n license: readField('License'),\n name: readField('Name'),\n };\n}\n\nexport function validateExtensionSourceMetadata(\n extension: EmbeddedExtension,\n): ExtensionSource | null {\n if (extension.source === undefined) {\n return null;\n }\n\n const source = extension.source as unknown as Record<string, unknown> | undefined;\n assert(\n source && typeof source === 'object' && !Array.isArray(source),\n `Managed extension source must be an object: ${extension.id}`,\n );\n if (source.provider === 'github') {\n assert(\n typeof source.repository === 'string' &&\n /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\\/[A-Za-z0-9._-]+$/u.test(source.repository),\n `Invalid GitHub repository for extension ${extension.id}: ${source.repository}`,\n );\n assert(\n typeof source.ref === 'string' &&\n source.ref.length > 0 &&\n !/[\\u0000-\\u0020\\u007f]/u.test(source.ref),\n `Invalid Git ref for extension ${extension.id}: ${source.ref}`,\n );\n assert(\n typeof source.resolvedCommit === 'string' && /^[a-f0-9]{40}$/u.test(source.resolvedCommit),\n `Managed extension ${extension.id} requires a 40-character resolvedCommit.`,\n );\n } else if (source.provider === 'npm') {\n assert(\n typeof source.package === 'string' &&\n /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u.test(source.package),\n `Invalid npm package for extension ${extension.id}: ${source.package}`,\n );\n assert(\n typeof source.version === 'string' &&\n /^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/u.test(source.version),\n `Managed npm extension ${extension.id} requires an exact semantic version.`,\n );\n } else {\n throw new Error(\n `Unsupported extension source provider for ${extension.id}: ${source.provider}`,\n );\n }\n assert(\n typeof source.artifact === 'string' && source.artifact.length > 0,\n `Managed extension ${extension.id} requires an artifact path.`,\n );\n validateArchiveEntryName(source.artifact);\n assert(\n !source.artifact.endsWith('/'),\n `Managed extension artifact must be a file: ${source.artifact}`,\n );\n assert(\n typeof source.integrity === 'string' && /^sha256-[A-Za-z0-9+/]{43}=$/u.test(source.integrity),\n `Managed extension ${extension.id} requires SHA-256 integrity.`,\n );\n validateExtensionApiManifestSourceMetadata(extension);\n return source as unknown as ExtensionSource;\n}\n\nexport function validateManagedExtensionContents(\n extension: EmbeddedExtension,\n contents: Uint8Array | string,\n): ManagedExtensionContents | null {\n const source = validateExtensionSourceMetadata(extension);\n if (!source) {\n return null;\n }\n\n const actualIntegrity = extensionIntegrity(contents);\n assert(\n actualIntegrity === source.integrity,\n `Managed extension integrity mismatch for ${extension.id}: ` +\n `expected ${source.integrity}, got ${actualIntegrity}`,\n );\n const actualId = extensionHeaderId(contents);\n assert(\n actualId === extension.id,\n `Managed extension header ID mismatch for ${extension.id}: ` +\n `expected ${extension.id}, got ${actualId ?? '(missing)'}`,\n );\n return {actualId, integrity: actualIntegrity, source};\n}\n"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"extension-dependencies.js","names":[],"sources":["../src/extension-dependencies.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert} from './assert';\nimport {validateExtensionApiManifestSourceMetadata} from './extension-api-manifest';\nimport type {EmbeddedExtension, ExtensionSource} from './types';\n\n/**\n * Whether an extension must be loaded with TurboWarp's \"Run without sandbox\" checked, declared by\n * its `// Unsandboxed:` header line.\n */\nexport type UnsandboxedRequirement = 'required' | 'optional' | 'not-needed';\n\nexport const unsandboxedRequirements: readonly UnsandboxedRequirement[] = Object.freeze([\n 'required',\n 'optional',\n 'not-needed',\n]);\n\nexport interface ExtensionHeaderMetadata {\n author: string | null;\n description: string | null;\n id: string | null;\n license: string | null;\n name: string | null;\n /** The raw `// Unsandboxed:` value; see {@link unsandboxedRequirement} to validate it. */\n unsandboxed: string | null;\n}\n\nexport interface ManagedExtensionContents {\n actualId: string | null;\n integrity: string;\n source: ExtensionSource;\n}\n\nexport function extensionIntegrity(contents: Uint8Array | string): string {\n return `sha256-${createHash('sha256').update(contents).digest('base64')}`;\n}\n\nexport function extensionHeaderId(contents: Uint8Array | string): string | null {\n return extensionHeaderMetadata(contents).id;\n}\n\nexport function extensionHeaderMetadata(contents: Uint8Array | string): ExtensionHeaderMetadata {\n const source = Buffer.from(contents).toString('utf8');\n const readField = (field: string): string | null =>\n source.match(new RegExp(`^// ${field}: (.+)\\\\r?$`, 'mu'))?.[1]?.trim() ?? null;\n const id = readField('ID');\n return {\n author: readField('By'),\n description: readField('Description'),\n id: id && /^[A-Za-z0-9._-]+$/u.test(id) ? id : null,\n license: readField('License'),\n name: readField('Name'),\n unsandboxed: readField('Unsandboxed'),\n };\n}\n\n/** Validates a header's `// Unsandboxed:` value; `null` means the extension declares nothing. */\nexport function unsandboxedRequirement(\n metadata: ExtensionHeaderMetadata,\n): UnsandboxedRequirement | null {\n if (metadata.unsandboxed === null) return null;\n assert(\n (unsandboxedRequirements as readonly string[]).includes(metadata.unsandboxed),\n `Extension ${metadata.id ?? '(unknown)'} declares an invalid // Unsandboxed: header ` +\n `${JSON.stringify(metadata.unsandboxed)}; use ${unsandboxedRequirements.join(', ')}.`,\n );\n return metadata.unsandboxed as UnsandboxedRequirement;\n}\n\nexport function validateExtensionSourceMetadata(\n extension: EmbeddedExtension,\n): ExtensionSource | null {\n if (extension.source === undefined) {\n return null;\n }\n\n const source = extension.source as unknown as Record<string, unknown> | undefined;\n assert(\n source && typeof source === 'object' && !Array.isArray(source),\n `Managed extension source must be an object: ${extension.id}`,\n );\n if (source.provider === 'github') {\n assert(\n typeof source.repository === 'string' &&\n /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\\/[A-Za-z0-9._-]+$/u.test(source.repository),\n `Invalid GitHub repository for extension ${extension.id}: ${source.repository}`,\n );\n assert(\n typeof source.ref === 'string' &&\n source.ref.length > 0 &&\n !/[\\u0000-\\u0020\\u007f]/u.test(source.ref),\n `Invalid Git ref for extension ${extension.id}: ${source.ref}`,\n );\n assert(\n typeof source.resolvedCommit === 'string' && /^[a-f0-9]{40}$/u.test(source.resolvedCommit),\n `Managed extension ${extension.id} requires a 40-character resolvedCommit.`,\n );\n } else if (source.provider === 'npm') {\n assert(\n typeof source.package === 'string' &&\n /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u.test(source.package),\n `Invalid npm package for extension ${extension.id}: ${source.package}`,\n );\n assert(\n typeof source.version === 'string' &&\n /^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/u.test(source.version),\n `Managed npm extension ${extension.id} requires an exact semantic version.`,\n );\n } else {\n throw new Error(\n `Unsupported extension source provider for ${extension.id}: ${source.provider}`,\n );\n }\n assert(\n typeof source.artifact === 'string' && source.artifact.length > 0,\n `Managed extension ${extension.id} requires an artifact path.`,\n );\n validateArchiveEntryName(source.artifact);\n assert(\n !source.artifact.endsWith('/'),\n `Managed extension artifact must be a file: ${source.artifact}`,\n );\n assert(\n typeof source.integrity === 'string' && /^sha256-[A-Za-z0-9+/]{43}=$/u.test(source.integrity),\n `Managed extension ${extension.id} requires SHA-256 integrity.`,\n );\n validateExtensionApiManifestSourceMetadata(extension);\n return source as unknown as ExtensionSource;\n}\n\nexport function validateManagedExtensionContents(\n extension: EmbeddedExtension,\n contents: Uint8Array | string,\n): ManagedExtensionContents | null {\n const source = validateExtensionSourceMetadata(extension);\n if (!source) {\n return null;\n }\n\n const actualIntegrity = extensionIntegrity(contents);\n assert(\n actualIntegrity === source.integrity,\n `Managed extension integrity mismatch for ${extension.id}: ` +\n `expected ${source.integrity}, got ${actualIntegrity}`,\n );\n const actualId = extensionHeaderId(contents);\n assert(\n actualId === extension.id,\n `Managed extension header ID mismatch for ${extension.id}: ` +\n `expected ${extension.id}, got ${actualId ?? '(missing)'}`,\n );\n return {actualId, integrity: actualIntegrity, source};\n}\n"],"mappings":";;;;;AAeA,IAAa,0BAA6D,OAAO,OAAO;CACtF;CACA;CACA;AACF,CAAC;AAkBD,SAAgB,mBAAmB,UAAuC;CACxE,OAAO,UAAU,WAAW,QAAQ,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,OAAO,QAAQ;AACxE;AAEA,SAAgB,kBAAkB,UAA8C;CAC9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ACzF,qBAAqB,UAAU,GAAG,yCACpC;CACF,OAAO,IAAI,OAAO,aAAa,OAAO;EACpC,OACE,OAAO,OAAO,YAAY,YACxB,sDAAsD,KAAK,OAAO,OAAO,GAC3E,qCAAqC,UAAU,GAAG,IAAI,OAAO,SAC/D;EACA,OACE,OAAO,OAAO,YAAY,YACxB,qEAAqE,KAAK,OAAO,OAAO,GAC1F,yBAAyB,UAAU,GAAG,qCACxC;CACF,OACE,MAAM,IAAI,MACR,6CAA6C,UAAU,GAAG,IAAI,OAAO,UACvE;CAEF,OACE,OAAO,OAAO,aAAa,YAAY,OAAO,SAAS,SAAS,GAChE,qBAAqB,UAAU,GAAG,4BACpC;CACA,yBAAyB,OAAO,QAAQ;CACxC,OACE,CAAC,OAAO,SAAS,SAAS,GAAG,GAC7B,8CAA8C,OAAO,UACvD;CACA,OACE,OAAO,OAAO,cAAc,YAAY,+BAA+B,KAAK,OAAO,SAAS,GAC5F,qBAAqB,UAAU,GAAG,6BACpC;CACA,2CAA2C,SAAS;CACpD,OAAO;AACT;AAEA,SAAgB,iCACd,WACA,UACiC;CACjC,MAAM,SAAS,gCAAgC,SAAS;CACxD,IAAI,CAAC,QACH,OAAO;CAGT,MAAM,kBAAkB,mBAAmB,QAAQ;CACnD,OACE,oBAAoB,OAAO,WAC3B,4CAA4C,UAAU,GAAG,aAC3C,OAAO,UAAU,QAAQ,iBACzC;CACA,MAAM,WAAW,kBAAkB,QAAQ;CAC3C,OACE,aAAa,UAAU,IACvB,4CAA4C,UAAU,GAAG,aAC3C,UAAU,GAAG,QAAQ,YAAY,aACjD;CACA,OAAO;EAAC;EAAU,WAAW;EAAiB;CAAM;AACtD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,11 +3,11 @@ export { assert } from './assert';
|
|
|
3
3
|
export { validateArchiveEntryName } from './archive';
|
|
4
4
|
export { buildSb3 } from './build';
|
|
5
5
|
export { packageName, packageVersion } from './constants';
|
|
6
|
-
export { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, validateExtensionSourceMetadata, validateManagedExtensionContents, } from './extension-dependencies';
|
|
6
|
+
export { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandboxedRequirement, unsandboxedRequirements, validateExtensionSourceMetadata, validateManagedExtensionContents, } from './extension-dependencies';
|
|
7
7
|
export { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, tryParseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest, } from './extension-api-manifest';
|
|
8
8
|
export { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions, } from './extension-bundle-configuration';
|
|
9
9
|
export { planBundledSb3Unbundle, unbundleSb3 } from './extension-bundle-archive';
|
|
10
|
-
export { buildExtensionBundles, createStaticExtensionBundle, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations, } from './extension-bundle';
|
|
10
|
+
export { buildExtensionBundles, createStaticExtensionBundle, bundleUnsandboxedRequirement, defaultSandboxedNotices, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations, } from './extension-bundle';
|
|
11
11
|
export { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId, } from './extension-id-migration';
|
|
12
12
|
export { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions, } from './extension-sync';
|
|
13
13
|
export { decodeExtensionDataUrl, importSb3 } from './import';
|
|
@@ -21,6 +21,7 @@ export type { CliOptions } from './cli';
|
|
|
21
21
|
export type { ExtensionApiCompatibilityChange, ExtensionApiManifest, ExtensionApiManifestArgument, ExtensionApiManifestBlock, ExtensionApiManifestDataReferenceType, ExtensionApiManifestEffect, ExtensionApiManifestFormatVersion, ExtensionApiManifestMenu, ExtensionApiManifestParseFailure, ExtensionApiManifestParseResult, ExtensionApiManifestParseSuccess, ExtensionApiManifestPathSegmentType, ExtensionApiManifestResultType, ExtensionApiManifestServer, } from './extension-api-manifest';
|
|
22
22
|
export type { BuildExtensionBundlesResult, ExtensionBundleComponent, ExtensionBundleCounts, ExtensionBundlePlan, } from './extension-bundle';
|
|
23
23
|
export type { BundledSb3UnbundlePlan } from './extension-bundle-archive';
|
|
24
|
+
export type { ExtensionHeaderMetadata, UnsandboxedRequirement } from './extension-dependencies';
|
|
24
25
|
export type { ExtensionIdMigrationCounts, ExtensionIdReference, RewriteExtensionIdDocumentsResult, } from './extension-id-migration';
|
|
25
26
|
export type { ExtensionSyncConfirmContext, SyncExtensionsOptions, UpdateExtensionsOptions, } from './extension-sync';
|
|
26
27
|
export type { DecodedExtensionDataUrl, ImportSb3Options, ImportSb3Result, OutputReplacementContext, } from './import';
|
package/dist/index.js
CHANGED
|
@@ -2,8 +2,8 @@ import { assert } from "./assert.js";
|
|
|
2
2
|
import { compareDirectories, inspectGitOutputState, validateOutputDirectoryPath } from "./output-safety.js";
|
|
3
3
|
import { validateArchiveEntryName } from "./archive.js";
|
|
4
4
|
import { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, tryParseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
|
|
5
|
-
import { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
6
|
-
import { buildExtensionBundles, createStaticExtensionBundle, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations } from "./extension-bundle.js";
|
|
5
|
+
import { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandboxedRequirement, unsandboxedRequirements, validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
6
|
+
import { buildExtensionBundles, bundleUnsandboxedRequirement, createStaticExtensionBundle, defaultSandboxedNotices, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations } from "./extension-bundle.js";
|
|
7
7
|
import { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion } from "./project-asset-additions.js";
|
|
8
8
|
import { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from "./turbowarp-clean-up.js";
|
|
9
9
|
import { createDeterministicSb3, fixedZipTimestamp, sourceFormatVersion, validateSb3Source } from "./source.js";
|
|
@@ -15,4 +15,4 @@ import { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleE
|
|
|
15
15
|
import { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId } from "./extension-id-migration.js";
|
|
16
16
|
import { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
|
|
17
17
|
import { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate } from "./release-snapshot.js";
|
|
18
|
-
export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildSb3, bundleExtensions, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
|
|
18
|
+
export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
|
package/dist/types.d.ts
CHANGED
|
@@ -360,6 +360,58 @@ Set `"recoveryCapsule": true` on a bundle, or pass `--include-recovery-capsule`
|
|
|
360
360
|
to append an `SB3-Toolchain-Reversible-Bundle-v1` capsule. It records each original member data URL,
|
|
361
361
|
member order, and the original `extensions` and `extensionURLs` order, at the cost of a larger output.
|
|
362
362
|
|
|
363
|
+
### Declare unsandboxed loading
|
|
364
|
+
|
|
365
|
+
Each extension can declare, in its own header, whether the user must check TurboWarp's "Run
|
|
366
|
+
without sandbox" when allowing it:
|
|
367
|
+
|
|
368
|
+
```js
|
|
369
|
+
// Name: Extension One
|
|
370
|
+
// ID: extensionone
|
|
371
|
+
// By: Example Author
|
|
372
|
+
// License: MPL-2.0
|
|
373
|
+
// Unsandboxed: required
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
| Value | Meaning |
|
|
377
|
+
| ------------ | ---------------------------------------------------------- |
|
|
378
|
+
| `required` | The extension cannot work sandboxed |
|
|
379
|
+
| `optional` | It works sandboxed, but some features need unsandboxed use |
|
|
380
|
+
| `not-needed` | It works fully sandboxed |
|
|
381
|
+
|
|
382
|
+
Any other value fails the build. The declaration travels with the file, so it holds whether the
|
|
383
|
+
extension is bundled or loaded on its own; extensions without the line behave exactly as before.
|
|
384
|
+
|
|
385
|
+
A bundle derives its requirement from its members: `required` if any member is, otherwise
|
|
386
|
+
`optional` if any member is, and `not-needed` only when every member says so. The generated header
|
|
387
|
+
records the result as `// Unsandboxed:` along with each member's own value. TurboWarp's permission
|
|
388
|
+
dialog itself cannot be changed by an extension, so the bundle acts on what happens after the user
|
|
389
|
+
answers it:
|
|
390
|
+
|
|
391
|
+
- `required` and loaded sandboxed: no member runs. The bundle registers a placeholder under its
|
|
392
|
+
ID whose palette shows the bundle name and how to reload the project unsandboxed, and logs the
|
|
393
|
+
same text as a console error. Without it, a member that throws because it is sandboxed stops the
|
|
394
|
+
whole bundle: in TurboWarp's sandboxed iframe the project never finishes loading, and in a worker
|
|
395
|
+
the user sees only a generic load failure. With the placeholder the project loads, its bundle
|
|
396
|
+
blocks stay in the scripts, and loading the project again unsandboxed restores them.
|
|
397
|
+
- `optional` and loaded sandboxed: the members run, and the palette starts with a notice that some
|
|
398
|
+
features are unavailable, also logged as a console warning.
|
|
399
|
+
- `not-needed`, no declaration, or loaded unsandboxed: nothing is added.
|
|
400
|
+
|
|
401
|
+
The notices have built-in English and Japanese text and follow `Scratch.translate.language`,
|
|
402
|
+
falling back to the primary language subtag and then to English. Override or add locales with the
|
|
403
|
+
bundle's `sandboxedNotice`, an object mapping lowercase language tags to messages; `\n` starts a
|
|
404
|
+
new palette label. It is accepted only when the bundle derives `required` or `optional`:
|
|
405
|
+
|
|
406
|
+
```json
|
|
407
|
+
{
|
|
408
|
+
"id": "projectbundle",
|
|
409
|
+
"name": "Project Extension Bundle",
|
|
410
|
+
"members": ["extensionone", "extensiontwo"],
|
|
411
|
+
"sandboxedNotice": {"de": "Projekt erneut laden\nund ohne Sandbox ausführen."}
|
|
412
|
+
}
|
|
413
|
+
```
|
|
414
|
+
|
|
363
415
|
## Restore from expanded source
|
|
364
416
|
|
|
365
417
|
Choose the restoration path based on which artifact is available:
|
|
@@ -350,6 +350,57 @@ bundleに`"recoveryCapsule": true`を指定するか、設定時に`--include-re
|
|
|
350
350
|
`SB3-Toolchain-Reversible-Bundle-v1`カプセルを追加します。カプセルは各メンバーの元のdata URL、メンバー順、
|
|
351
351
|
元の`extensions`と`extensionURLs`の順序を記録しますが、出力サイズは増加します。
|
|
352
352
|
|
|
353
|
+
### unsandboxedでの読み込みを宣言する
|
|
354
|
+
|
|
355
|
+
各機能拡張は、許可するときにTurboWarpの「サンドボックスなしで実行する」へのチェックが必要かどうかを、
|
|
356
|
+
自身のヘッダーで宣言できます。
|
|
357
|
+
|
|
358
|
+
```js
|
|
359
|
+
// Name: Extension One
|
|
360
|
+
// ID: extensionone
|
|
361
|
+
// By: Example Author
|
|
362
|
+
// License: MPL-2.0
|
|
363
|
+
// Unsandboxed: required
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
| 値 | 意味 |
|
|
367
|
+
| ------------ | ------------------------------------------------------------ |
|
|
368
|
+
| `required` | チェック必須。サンドボックス内では動作しない |
|
|
369
|
+
| `optional` | チェック任意。サンドボックス内でも動くが、一部機能が使えない |
|
|
370
|
+
| `not-needed` | チェック不要。サンドボックス内で完全に動作する |
|
|
371
|
+
|
|
372
|
+
それ以外の値はビルドエラーになります。宣言はファイルと一緒に移動するので、bundleしても単体で読み込んでも
|
|
373
|
+
有効です。この行がない機能拡張の動作は従来と変わりません。
|
|
374
|
+
|
|
375
|
+
bundleの要件はメンバーから導出されます。いずれかが`required`なら`required`、そうでなくいずれかが
|
|
376
|
+
`optional`なら`optional`、全員が`not-needed`のときだけ`not-needed`です。生成ヘッダーには結果が
|
|
377
|
+
`// Unsandboxed:`として、各メンバー自身の値とともに記録されます。TurboWarpの権限ダイアログそのものは
|
|
378
|
+
機能拡張から変更できないため、bundleはユーザーがそれに答えた後の動作を制御します。
|
|
379
|
+
|
|
380
|
+
- `required`でサンドボックス内に読み込まれた場合: メンバーを一切実行しません。bundle IDでプレースホルダーを
|
|
381
|
+
登録し、パレットにbundle名とサンドボックスなしで開き直す手順を表示し、同じ内容をコンソールにエラーとして
|
|
382
|
+
出力します。これがないと、サンドボックスのために例外を投げたメンバーがbundle全体を止めます。TurboWarpの
|
|
383
|
+
sandboxed iframeではプロジェクトの読み込みが終わらず、workerでは汎用的な読み込み失敗しか表示されません。
|
|
384
|
+
プレースホルダーがあればプロジェクトは読み込まれ、bundleのブロックはスクリプトに残り、サンドボックスなしで
|
|
385
|
+
開き直すと元に戻ります。
|
|
386
|
+
- `optional`でサンドボックス内に読み込まれた場合: メンバーは実行され、パレットの先頭に一部機能が使えない旨の
|
|
387
|
+
通知が表示され、コンソールにも警告が出力されます。
|
|
388
|
+
- `not-needed`、宣言なし、またはサンドボックスなしで読み込まれた場合: 何も追加しません。
|
|
389
|
+
|
|
390
|
+
通知文は英語と日本語を内蔵し、`Scratch.translate.language`に従います。一致しない場合は主言語サブタグ、
|
|
391
|
+
次に英語を使います。bundleの`sandboxedNotice`で、小文字の言語タグからメッセージへの対応を指定すると、
|
|
392
|
+
ロケールを上書き・追加できます。`\n`でパレットのラベルを改行します。bundleが`required`または
|
|
393
|
+
`optional`になる場合だけ指定できます。
|
|
394
|
+
|
|
395
|
+
```json
|
|
396
|
+
{
|
|
397
|
+
"id": "projectbundle",
|
|
398
|
+
"name": "Project Extension Bundle",
|
|
399
|
+
"members": ["extensionone", "extensiontwo"],
|
|
400
|
+
"sandboxedNotice": {"de": "Projekt erneut laden\nund ohne Sandbox ausführen."}
|
|
401
|
+
}
|
|
402
|
+
```
|
|
403
|
+
|
|
353
404
|
## 展開ソースからの復元
|
|
354
405
|
|
|
355
406
|
利用可能な成果物に応じて復元経路を選択します。
|
|
@@ -169,6 +169,9 @@ APIマニフェストファイルは展開ソースの検証入力であり、SB
|
|
|
169
169
|
LABELエントリとseparatorは変更されない
|
|
170
170
|
- `recoveryCapsule`: 任意の真偽値で、既定値は`false`。追加サイズを許容でき、生成SB3単体からの直接unbundleが
|
|
171
171
|
必要な場合に限り`true`を指定する
|
|
172
|
+
- `sandboxedNotice`: 任意のオブジェクトで、bundleがサンドボックス内で読み込まれたときの通知文を小文字の言語タグ
|
|
173
|
+
ごとに指定する。メンバーの`// Unsandboxed:`ヘッダーによってbundleが`required`または`optional`になる場合だけ
|
|
174
|
+
指定でき、省略時は内蔵の`en`と`ja`の通知文を使う。[`extension-bundles.md`](extension-bundles.md)を参照
|
|
172
175
|
|
|
173
176
|
1つのメンバーを複数のbundleに所属させることはできません。個別エントリ、個別JavaScript、`source`、
|
|
174
177
|
`project.source.json`が引き続き信頼できる情報源です。`build`は各元opcodeに`memberId + "__"`を加え、
|
package/docs/source-format-v1.md
CHANGED
|
@@ -173,6 +173,7 @@ only in the generated SB3.
|
|
|
173
173
|
- `name`: single-line name displayed in the permission prompt and extension category
|
|
174
174
|
- `members`: two or more individual extension IDs; their order defines block and menu composition order. The palette receives a decorated, metadata-bearing bundle LABEL heading and a double separator between groups, while LABEL entries and separators from the original extensions remain unchanged
|
|
175
175
|
- `recoveryCapsule`: optional boolean, default `false`. Set it to `true` only when the extra size is acceptable and direct unbundling from the generated SB3 is required
|
|
176
|
+
- `sandboxedNotice`: optional object mapping lowercase language tags to the message shown when the bundle is loaded sandboxed. Allowed only when a member's `// Unsandboxed:` header makes the bundle `required` or `optional`; built-in `en` and `ja` messages apply otherwise. See [`extension-bundles.md`](extension-bundles.md#declare-unsandboxed-loading)
|
|
176
177
|
|
|
177
178
|
A member cannot belong to more than one bundle. Individual entries, individual JavaScript, `source`,
|
|
178
179
|
and `project.source.json` remain authoritative. `build` adds `memberId + "__"` to each original opcode
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubohiroya/sb3-toolchain",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.1",
|
|
4
4
|
"description": "Git-friendly source management and deterministic builds for Scratch 3 and TurboWarp SB3 projects",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MPL-2.0",
|
|
@@ -77,5 +77,11 @@
|
|
|
77
77
|
"turbowarp",
|
|
78
78
|
"source-control",
|
|
79
79
|
"reproducible-builds"
|
|
80
|
-
]
|
|
80
|
+
],
|
|
81
|
+
"gitHead": "3f98b508498d3b5084eb0f7bad47ff21956ac429",
|
|
82
|
+
"x-turbowarp-source": {
|
|
83
|
+
"revision": "3f98b508498d3b5084eb0f7bad47ff21956ac429",
|
|
84
|
+
"revisionRole": "base-commit",
|
|
85
|
+
"sourceState": "working-tree-release-overlay"
|
|
86
|
+
}
|
|
81
87
|
}
|