@kubohiroya/sb3-toolchain 0.19.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ import { assert } from "./assert.js";
2
+ import { validateArchiveEntryName } from "./archive.js";
3
+ import { extensionHeaderId } from "./extension-dependencies.js";
4
+ import { fixedZipTimestamp } from "./source.js";
5
+ import { writeSb3Archive } from "./build.js";
6
+ import { decodeExtensionDataUrl } from "./import.js";
7
+ import path from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { lstat, readFile, realpath } from "node:fs/promises";
10
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
11
+ import { lt, valid } from "semver";
12
+ //#region src/extension-sb3-replacement.ts
13
+ var defaultKamishibaiManifestUrl = "https://kubohiroya.github.io/turbowarp-kamishibai-samples/stories/tutorial/public-surfaces.json";
14
+ var kamishibaiReplacementIds = Object.freeze(["kubohiroyakamishibai4", "kubohiroyakamishibaiauthoring4"]);
15
+ var archiveSizeLimit = 67108864;
16
+ var expandedSizeLimit = 268435456;
17
+ function isObject(value) {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+ function sha256(contents) {
21
+ return createHash("sha256").update(contents).digest("hex");
22
+ }
23
+ async function readArchive(filePath) {
24
+ assert(path.extname(filePath).toLowerCase() === ".sb3", `Expected an .sb3 file: ${filePath}`);
25
+ const stats = await lstat(filePath);
26
+ assert(stats.isFile() && !stats.isSymbolicLink(), `Expected a regular SB3 file: ${filePath}`);
27
+ assert(stats.size <= archiveSizeLimit, `SB3 exceeds the 64 MiB limit: ${filePath}`);
28
+ return readFile(filePath);
29
+ }
30
+ function parseArchive(contents) {
31
+ const names = /* @__PURE__ */ new Set();
32
+ let expandedSize = 0;
33
+ const entries = unzipSync(contents, { filter: (entry) => {
34
+ validateArchiveEntryName(entry.name);
35
+ assert(!names.has(entry.name), `Duplicate SB3 archive entry: ${entry.name}`);
36
+ assert(!/^(?:0|[1-9][0-9]*)$/u.test(entry.name), "Integer ZIP entry names are unsupported.");
37
+ names.add(entry.name);
38
+ expandedSize += entry.originalSize;
39
+ assert(names.size <= 4096 && expandedSize <= expandedSizeLimit, "SB3 expansion limit exceeded.");
40
+ return true;
41
+ } });
42
+ assert(Object.hasOwn(entries, "project.json"), "SB3 archive does not contain project.json.");
43
+ const project = JSON.parse(strFromU8(entries["project.json"]));
44
+ assert(isObject(project) && isObject(project.extensionURLs), "SB3 requires an extensionURLs object.");
45
+ return {
46
+ entries,
47
+ project,
48
+ urls: project.extensionURLs
49
+ };
50
+ }
51
+ function embeddedSource(urls, id) {
52
+ const dataUrl = urls[id];
53
+ assert(typeof dataUrl === "string" && dataUrl.startsWith("data:"), `Missing embedded extension: ${id}`);
54
+ const decoded = decodeExtensionDataUrl(dataUrl);
55
+ assert(decoded.mediaType === "text/javascript" || decoded.mediaType === "application/javascript", `Embedded extension must contain JavaScript: ${id}`);
56
+ const source = Buffer.from(decoded.source);
57
+ const literalId = source.toString("utf8").match(/getInfo\s*\(\)\s*\{\s*return\s*\{\s*"id"\s*:\s*"([a-z0-9]+)"/u)?.[1];
58
+ const actualId = extensionHeaderId(source) ?? literalId;
59
+ assert(actualId === id, `Embedded extension ID mismatch: expected ${id}, got ${actualId ?? "(missing)"}.`);
60
+ return source;
61
+ }
62
+ function runtimeVersion(source) {
63
+ const value = source.toString("utf8").match(/^\/\/ Version: (.+)\r?$/mu)?.[1]?.trim();
64
+ return value && valid(value) ? value : null;
65
+ }
66
+ async function download(url, limit, fetchImplementation) {
67
+ const response = await fetchImplementation(url, {
68
+ redirect: "error",
69
+ signal: AbortSignal.timeout(3e4),
70
+ cache: "no-store"
71
+ });
72
+ assert(response.ok, `Download failed (${response.status}): ${url}`);
73
+ assert(response.body, `Empty download: ${url}`);
74
+ const reader = response.body.getReader();
75
+ const chunks = [];
76
+ let size = 0;
77
+ try {
78
+ for (;;) {
79
+ const { done, value } = await reader.read();
80
+ if (done) break;
81
+ size += value.byteLength;
82
+ assert(size <= limit, `Download exceeds the size limit: ${url}`);
83
+ chunks.push(value);
84
+ }
85
+ } catch (error) {
86
+ await reader.cancel().catch(() => void 0);
87
+ throw error;
88
+ } finally {
89
+ reader.releaseLock();
90
+ }
91
+ return Buffer.concat(chunks, size);
92
+ }
93
+ async function publishedDonor(fetchImplementation) {
94
+ const manifest = JSON.parse((await download(defaultKamishibaiManifestUrl, 1048576, fetchImplementation)).toString("utf8"));
95
+ assert(isObject(manifest), "Invalid Kamishibai public surfaces manifest.");
96
+ assert(manifest.formatVersion === 1 && manifest.status === "published" && manifest.published === true, "Kamishibai donor must be a published format 1 release.");
97
+ assert(typeof manifest.version === "string" && valid(manifest.version), "Invalid published version.");
98
+ assert(isObject(manifest.runtime) && manifest.runtime.version === manifest.version, "Published runtime version mismatch.");
99
+ assert(isObject(manifest.surfaces) && typeof manifest.surfaces.sb3BlocksUrl === "string", "Missing published block SB3 URL.");
100
+ assert(isObject(manifest.artifacts) && isObject(manifest.artifacts.sb3Blocks), "Missing block SB3 artifact.");
101
+ const artifact = manifest.artifacts.sb3Blocks;
102
+ assert(typeof artifact.size === "number" && Number.isSafeInteger(artifact.size) && artifact.size > 0 && artifact.size <= archiveSizeLimit, "Invalid block SB3 size.");
103
+ assert(typeof artifact.sha256 === "string" && /^[a-f0-9]{64}$/u.test(artifact.sha256), "Invalid block SB3 SHA-256.");
104
+ const url = new URL(manifest.surfaces.sb3BlocksUrl);
105
+ const manifestUrl = new URL(defaultKamishibaiManifestUrl);
106
+ assert(url.origin === manifestUrl.origin && !url.username && !url.password && url.pathname.startsWith("/turbowarp-kamishibai-samples/"), "Block SB3 URL must remain on the official samples site.");
107
+ const archive = await download(url.href, archiveSizeLimit, fetchImplementation);
108
+ assert(archive.byteLength === artifact.size, "Downloaded block SB3 size mismatch.");
109
+ assert(sha256(archive) === artifact.sha256, "Downloaded block SB3 SHA-256 mismatch.");
110
+ return {
111
+ archive,
112
+ source: url.href,
113
+ version: manifest.version
114
+ };
115
+ }
116
+ async function assertDistinctOutput(outputPath, protectedPaths) {
117
+ for (const protectedPath of protectedPaths) {
118
+ assert(path.resolve(outputPath) !== path.resolve(protectedPath), "Output must differ from input and donor SB3 paths.");
119
+ try {
120
+ assert(await realpath(outputPath) !== await realpath(protectedPath), "Output must differ from input and donor SB3 paths.");
121
+ } catch (error) {
122
+ if (!isObject(error) || error.code !== "ENOENT") throw error;
123
+ }
124
+ }
125
+ }
126
+ /** Replaces the Kamishibai runtime bundle and Block Script without executing donor code. */
127
+ async function replaceSb3Extensions({ confirmReplace, fetch: fetchImplementation = globalThis.fetch, fromPath, inputPath, outputPath, yes = false }) {
128
+ const protectedPaths = fromPath ? [inputPath, fromPath] : [inputPath];
129
+ await assertDistinctOutput(outputPath, protectedPaths);
130
+ const input = parseArchive(await readArchive(inputPath));
131
+ const extensionIds = kamishibaiReplacementIds.filter((id) => Object.hasOwn(input.urls, id));
132
+ assert(extensionIds.length > 0, "Input contains no supported Kamishibai embedded extensions.");
133
+ const inputSources = new Map(extensionIds.map((id) => [id, embeddedSource(input.urls, id)]));
134
+ const donor = fromPath ? {
135
+ archive: await readArchive(fromPath),
136
+ source: path.resolve(fromPath),
137
+ version: null
138
+ } : await publishedDonor(fetchImplementation);
139
+ const replacement = parseArchive(donor.archive);
140
+ for (const id of extensionIds) embeddedSource(replacement.urls, id);
141
+ const runtimeId = kamishibaiReplacementIds[0];
142
+ const donorRuntime = Object.hasOwn(replacement.urls, runtimeId) ? embeddedSource(replacement.urls, runtimeId) : null;
143
+ const donorVersion = donor.version ?? (donorRuntime ? runtimeVersion(donorRuntime) : null);
144
+ if (!fromPath && donorVersion) {
145
+ const inputRuntime = inputSources.get(runtimeId);
146
+ const inputVersion = inputRuntime ? runtimeVersion(inputRuntime) : null;
147
+ assert(!inputVersion || !lt(donorVersion, inputVersion), `Published donor ${donorVersion} is older than input ${inputVersion}. Wait for publication or select an intentional donor with --from.`);
148
+ const declaredVersion = donorRuntime ? runtimeVersion(donorRuntime) : null;
149
+ assert(!declaredVersion || declaredVersion === donorVersion, "Donor runtime header does not match the published version.");
150
+ }
151
+ for (const id of extensionIds) input.urls[id] = replacement.urls[id];
152
+ input.entries["project.json"] = strToU8(`${JSON.stringify(input.project)}\n`);
153
+ const archive = zipSync(input.entries, {
154
+ level: 6,
155
+ mtime: fixedZipTimestamp
156
+ });
157
+ await assertDistinctOutput(outputPath, protectedPaths);
158
+ return {
159
+ ...await writeSb3Archive({
160
+ archive,
161
+ confirmReplace,
162
+ outputPath,
163
+ yes
164
+ }),
165
+ extensionIds,
166
+ donor: {
167
+ source: donor.source,
168
+ sha256: sha256(donor.archive),
169
+ version: donorVersion
170
+ }
171
+ };
172
+ }
173
+ //#endregion
174
+ export { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions };
175
+
176
+ //# sourceMappingURL=extension-sb3-replacement.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-sb3-replacement.js","names":[],"sources":["../src/extension-sb3-replacement.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readFile, realpath} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strFromU8, strToU8, unzipSync, zipSync} from 'fflate';\nimport {lt, valid} from 'semver';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert} from './assert';\nimport {writeSb3Archive} from './build';\nimport type {WriteSb3ArchiveOptions, WriteSb3ArchiveResult} from './build';\nimport {extensionHeaderId} from './extension-dependencies';\nimport type {FetchImplementation} from './extension-sync';\nimport {decodeExtensionDataUrl} from './import';\nimport {fixedZipTimestamp} from './source';\nimport type {UnknownRecord} from './types';\n\nexport const defaultKamishibaiManifestUrl =\n 'https://kubohiroya.github.io/turbowarp-kamishibai-samples/stories/tutorial/public-surfaces.json';\n\nexport const kamishibaiReplacementIds: readonly string[] = Object.freeze([\n 'kubohiroyakamishibai4',\n 'kubohiroyakamishibaiauthoring4',\n]);\n\nconst archiveSizeLimit = 64 * 1024 * 1024;\nconst expandedSizeLimit = 256 * 1024 * 1024;\n\nexport interface ReplaceSb3ExtensionsOptions {\n confirmReplace?: WriteSb3ArchiveOptions['confirmReplace'];\n fetch?: FetchImplementation;\n fromPath?: string;\n inputPath: string;\n outputPath: string;\n yes?: boolean;\n}\n\nexport interface ReplaceSb3ExtensionsResult extends WriteSb3ArchiveResult {\n extensionIds: string[];\n donor: {source: string; sha256: string; version: string | null};\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction sha256(contents: Uint8Array): string {\n return createHash('sha256').update(contents).digest('hex');\n}\n\nasync function readArchive(filePath: string): Promise<Buffer> {\n assert(path.extname(filePath).toLowerCase() === '.sb3', `Expected an .sb3 file: ${filePath}`);\n const stats = await lstat(filePath);\n assert(stats.isFile() && !stats.isSymbolicLink(), `Expected a regular SB3 file: ${filePath}`);\n assert(stats.size <= archiveSizeLimit, `SB3 exceeds the 64 MiB limit: ${filePath}`);\n return readFile(filePath);\n}\n\nfunction parseArchive(contents: Uint8Array) {\n const names = new Set<string>();\n let expandedSize = 0;\n const entries = unzipSync(contents, {\n filter: (entry) => {\n validateArchiveEntryName(entry.name);\n assert(!names.has(entry.name), `Duplicate SB3 archive entry: ${entry.name}`);\n assert(!/^(?:0|[1-9][0-9]*)$/u.test(entry.name), 'Integer ZIP entry names are unsupported.');\n names.add(entry.name);\n expandedSize += entry.originalSize;\n assert(\n names.size <= 4096 && expandedSize <= expandedSizeLimit,\n 'SB3 expansion limit exceeded.',\n );\n return true;\n },\n });\n assert(Object.hasOwn(entries, 'project.json'), 'SB3 archive does not contain project.json.');\n const project: unknown = JSON.parse(strFromU8(entries['project.json']));\n assert(\n isObject(project) && isObject(project.extensionURLs),\n 'SB3 requires an extensionURLs object.',\n );\n return {entries, project, urls: project.extensionURLs};\n}\n\nfunction embeddedSource(urls: UnknownRecord, id: string): Buffer {\n const dataUrl = urls[id];\n assert(\n typeof dataUrl === 'string' && dataUrl.startsWith('data:'),\n `Missing embedded extension: ${id}`,\n );\n const decoded = decodeExtensionDataUrl(dataUrl);\n assert(\n decoded.mediaType === 'text/javascript' || decoded.mediaType === 'application/javascript',\n `Embedded extension must contain JavaScript: ${id}`,\n );\n const source = Buffer.from(decoded.source);\n // Generated Block Script declares its ID in a literal getInfo() result, without a header.\n const literalId = source\n .toString('utf8')\n .match(/getInfo\\s*\\(\\)\\s*\\{\\s*return\\s*\\{\\s*\"id\"\\s*:\\s*\"([a-z0-9]+)\"/u)?.[1];\n const actualId = extensionHeaderId(source) ?? literalId;\n assert(\n actualId === id,\n `Embedded extension ID mismatch: expected ${id}, got ${actualId ?? '(missing)'}.`,\n );\n return source;\n}\n\nfunction runtimeVersion(source: Buffer): string | null {\n const value = source\n .toString('utf8')\n .match(/^\\/\\/ Version: (.+)\\r?$/mu)?.[1]\n ?.trim();\n return value && valid(value) ? value : null;\n}\n\nasync function download(\n url: string,\n limit: number,\n fetchImplementation: FetchImplementation,\n): Promise<Buffer> {\n const response = await fetchImplementation(url, {\n redirect: 'error',\n signal: AbortSignal.timeout(30_000),\n cache: 'no-store',\n });\n assert(response.ok, `Download failed (${response.status}): ${url}`);\n assert(response.body, `Empty download: ${url}`);\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) break;\n size += value.byteLength;\n assert(size <= limit, `Download exceeds the size limit: ${url}`);\n chunks.push(value);\n }\n } catch (error) {\n await reader.cancel().catch(() => undefined);\n throw error;\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks, size);\n}\n\nasync function publishedDonor(fetchImplementation: FetchImplementation) {\n const manifest: unknown = JSON.parse(\n (await download(defaultKamishibaiManifestUrl, 1024 * 1024, fetchImplementation)).toString(\n 'utf8',\n ),\n );\n assert(isObject(manifest), 'Invalid Kamishibai public surfaces manifest.');\n assert(\n manifest.formatVersion === 1 && manifest.status === 'published' && manifest.published === true,\n 'Kamishibai donor must be a published format 1 release.',\n );\n assert(\n typeof manifest.version === 'string' && valid(manifest.version),\n 'Invalid published version.',\n );\n assert(\n isObject(manifest.runtime) && manifest.runtime.version === manifest.version,\n 'Published runtime version mismatch.',\n );\n assert(\n isObject(manifest.surfaces) && typeof manifest.surfaces.sb3BlocksUrl === 'string',\n 'Missing published block SB3 URL.',\n );\n assert(\n isObject(manifest.artifacts) && isObject(manifest.artifacts.sb3Blocks),\n 'Missing block SB3 artifact.',\n );\n const artifact = manifest.artifacts.sb3Blocks;\n assert(\n typeof artifact.size === 'number' &&\n Number.isSafeInteger(artifact.size) &&\n artifact.size > 0 &&\n artifact.size <= archiveSizeLimit,\n 'Invalid block SB3 size.',\n );\n assert(\n typeof artifact.sha256 === 'string' && /^[a-f0-9]{64}$/u.test(artifact.sha256),\n 'Invalid block SB3 SHA-256.',\n );\n const url = new URL(manifest.surfaces.sb3BlocksUrl);\n const manifestUrl = new URL(defaultKamishibaiManifestUrl);\n assert(\n url.origin === manifestUrl.origin &&\n !url.username &&\n !url.password &&\n url.pathname.startsWith('/turbowarp-kamishibai-samples/'),\n 'Block SB3 URL must remain on the official samples site.',\n );\n const archive = await download(url.href, archiveSizeLimit, fetchImplementation);\n assert(archive.byteLength === artifact.size, 'Downloaded block SB3 size mismatch.');\n assert(sha256(archive) === artifact.sha256, 'Downloaded block SB3 SHA-256 mismatch.');\n return {archive, source: url.href, version: manifest.version};\n}\n\nasync function assertDistinctOutput(outputPath: string, protectedPaths: string[]): Promise<void> {\n for (const protectedPath of protectedPaths) {\n assert(\n path.resolve(outputPath) !== path.resolve(protectedPath),\n 'Output must differ from input and donor SB3 paths.',\n );\n try {\n assert(\n (await realpath(outputPath)) !== (await realpath(protectedPath)),\n 'Output must differ from input and donor SB3 paths.',\n );\n } catch (error) {\n if (!isObject(error) || error.code !== 'ENOENT') throw error;\n }\n }\n}\n\n/** Replaces the Kamishibai runtime bundle and Block Script without executing donor code. */\nexport async function replaceSb3Extensions({\n confirmReplace,\n fetch: fetchImplementation = globalThis.fetch,\n fromPath,\n inputPath,\n outputPath,\n yes = false,\n}: ReplaceSb3ExtensionsOptions): Promise<ReplaceSb3ExtensionsResult> {\n const protectedPaths = fromPath ? [inputPath, fromPath] : [inputPath];\n await assertDistinctOutput(outputPath, protectedPaths);\n const input = parseArchive(await readArchive(inputPath));\n const extensionIds = kamishibaiReplacementIds.filter((id) => Object.hasOwn(input.urls, id));\n assert(extensionIds.length > 0, 'Input contains no supported Kamishibai embedded extensions.');\n const inputSources = new Map(extensionIds.map((id) => [id, embeddedSource(input.urls, id)]));\n const donor = fromPath\n ? {archive: await readArchive(fromPath), source: path.resolve(fromPath), version: null}\n : await publishedDonor(fetchImplementation);\n const replacement = parseArchive(donor.archive);\n for (const id of extensionIds) embeddedSource(replacement.urls, id);\n const runtimeId = kamishibaiReplacementIds[0];\n const donorRuntime = Object.hasOwn(replacement.urls, runtimeId)\n ? embeddedSource(replacement.urls, runtimeId)\n : null;\n const donorVersion = donor.version ?? (donorRuntime ? runtimeVersion(donorRuntime) : null);\n if (!fromPath && donorVersion) {\n const inputRuntime = inputSources.get(runtimeId);\n const inputVersion = inputRuntime ? runtimeVersion(inputRuntime) : null;\n assert(\n !inputVersion || !lt(donorVersion, inputVersion),\n `Published donor ${donorVersion} is older than input ${inputVersion}. Wait for publication or select an intentional donor with --from.`,\n );\n const declaredVersion = donorRuntime ? runtimeVersion(donorRuntime) : null;\n assert(\n !declaredVersion || declaredVersion === donorVersion,\n 'Donor runtime header does not match the published version.',\n );\n }\n for (const id of extensionIds) input.urls[id] = replacement.urls[id];\n input.entries['project.json'] = strToU8(`${JSON.stringify(input.project)}\\n`);\n const archive = zipSync(input.entries, {level: 6, mtime: fixedZipTimestamp});\n await assertDistinctOutput(outputPath, protectedPaths);\n const written = await writeSb3Archive({archive, confirmReplace, outputPath, yes});\n return {\n ...written,\n extensionIds,\n donor: {source: donor.source, sha256: sha256(donor.archive), version: donorVers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AI,SAAS;EAC/C,MAAM,eAAe,eAAe,eAAe,YAAY,IAAI;EACnE,OACE,CAAC,gBAAgB,CAAC,GAAG,cAAc,YAAY,GAC/C,mBAAmB,aAAa,uBAAuB,aAAa,mEACtE;EACA,MAAM,kBAAkB,eAAe,eAAe,YAAY,IAAI;EACtE,OACE,CAAC,mBAAmB,oBAAoB,cACxC,4DACF;CACF;CACA,KAAK,MAAM,MAAM,cAAc,MAAM,KAAK,MAAM,YAAY,KAAK;CACjE,MAAM,QAAQ,kBAAkB,QAAQ,GAAG,KAAK,UAAU,MAAM,OAAO,EAAE,GAAG;CAC5E,MAAM,UAAU,QAAQ,MAAM,SAAS;EAAC,OAAO;EAAG,OAAO;CAAiB,CAAC;CAC3E,MAAM,qBAAqB,YAAY,cAAc;CAErD,OAAO;EACL,GAAG,MAFiB,gBAAgB;GAAC;GAAS;GAAgB;GAAY;EAAG,CAAC;EAG9E;EACA,OAAO;GAAC,QAAQ,MAAM;GAAQ,QAAQ,OAAO,MAAM,OAAO;GAAG,SAAS;EAAY;CACpF;AACF"}
package/dist/index.d.ts CHANGED
@@ -7,6 +7,8 @@ export { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandb
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 { extensionSourceTypes, formatExtensionDigestInventory, inspectSb3ExtensionDigests, inventoryExtensionDigests, projectManifestKey, readProjectManifest, } from './extension-digest-inventory';
11
+ export type { ExtensionDigestEntry, ExtensionDigestInventory, ExtensionDigestUsage, ExtensionExecutionMode, ExtensionSourceType, Sb3ExtensionDigests, } from './extension-digest-inventory';
10
12
  export { buildExtensionBundles, createStaticExtensionBundle, bundleUnsandboxedRequirement, defaultSandboxedNotices, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations, } from './extension-bundle';
11
13
  export { buildExtensionBundlesWithModules } from './extension-module-bundle';
12
14
  export type { ExtensionModuleBuildReport } from './extension-module-bundle';
@@ -32,3 +34,5 @@ export type { ProjectAssetAdditionsSummary } from './project-asset-additions';
32
34
  export type { Sb3ReleaseSnapshotMetadata } from './release-snapshot';
33
35
  export type { DeterministicSb3, InspectedSb3Source } from './source';
34
36
  export type { TurboWarpCleanUpResult } from './turbowarp-clean-up';
37
+ export { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions, } from './extension-sb3-replacement';
38
+ export type { ReplaceSb3ExtensionsOptions, ReplaceSb3ExtensionsResult, } from './extension-sb3-replacement';
package/dist/index.js CHANGED
@@ -13,7 +13,9 @@ import { packageName, packageVersion } from "./constants.js";
13
13
  import { decodeExtensionDataUrl, importSb3 } from "./import.js";
14
14
  import { planBundledSb3Unbundle, unbundleSb3 } from "./extension-bundle-archive.js";
15
15
  import { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions } from "./extension-bundle-configuration.js";
16
+ import { extensionSourceTypes, formatExtensionDigestInventory, inspectSb3ExtensionDigests, inventoryExtensionDigests, projectManifestKey, readProjectManifest } from "./extension-digest-inventory.js";
16
17
  import { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId } from "./extension-id-migration.js";
18
+ import { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions } from "./extension-sb3-replacement.js";
17
19
  import { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
18
20
  import { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate } from "./release-snapshot.js";
19
- export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
21
+ export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultKamishibaiManifestUrl, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionSourceTypes, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, formatExtensionDigestInventory, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, inspectSb3ExtensionDigests, inventoryExtensionDigests, kamishibaiReplacementIds, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, projectManifestKey, readProjectManifest, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, replaceSb3Extensions, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
@@ -0,0 +1,83 @@
1
+ # Extension digests and retention forms
2
+
3
+ ```bash
4
+ sb3-toolchain extensions digests project.sb3 [another.sb3 ...] [--json]
5
+ ```
6
+
7
+ Reads what each SB3 says about itself and reports, for every extension its manifest names:
8
+
9
+ - the extension ID,
10
+ - the pinned `sha256`,
11
+ - which of the four retention forms the author chose — `remote-non-cacheable`, `remote-cacheable`,
12
+ `embedded-file`, or `embedded-data`,
13
+ - the number of bytes the archive actually holds for it,
14
+ - the digest of those held bytes, when it differs from the pinned one,
15
+ - the recorded URL and, for `embedded-file`, the archive entry path,
16
+ - the requested execution mode.
17
+
18
+ It also reports the project's own `uri`, which is the name a browser's caches and the opener's
19
+ recorded decisions are filed under, and, given more than one SB3, which digests several of those
20
+ projects name and which belong to a single project.
21
+
22
+ ## What this command cannot do
23
+
24
+ **It does not read browser storage.** An extension cache lives in IndexedDB, which belongs to an
25
+ origin _and_ to a browser profile, so no command line can reach the cache the person running it
26
+ actually has — driving a fresh automated browser would only show a profile nobody uses. Only the
27
+ browser knows which projects it has cached, so listing and deleting belong to the screen in
28
+ [`kubohiroya/turbowarp-title-menu#23`](https://github.com/kubohiroya/turbowarp-title-menu/issues/23).
29
+ This command produces the list to compare that state against.
30
+
31
+ **It never decides anything by reachability.** A project URI returns nothing until its author
32
+ publishes there, so a work saved but never published and a published work whose address rotted look
33
+ exactly alike. No URL in an SB3 is contacted, and nothing is ever treated as absent because a
34
+ request failed. An input that was not given is unknown, not absent.
35
+
36
+ ## What the report is for
37
+
38
+ 1. Deciding what belongs in the shared bucket: a digest several projects name is a copy worth
39
+ keeping once rather than per project.
40
+ 2. Feeding the title-menu screen's "remove caches no project still names" mode with the set of
41
+ digests the projects on hand actually name.
42
+ 3. Finding entries left behind after a project was converted from `remote-cacheable` to
43
+ `remote-non-cacheable`. Only `remote-cacheable` can ever leave a copy in a browser, so a digest
44
+ whose `cacheable` is false across every input is one no project still asks to be retained. An
45
+ author who decided those bytes should not be kept has had that decision undone if a browser
46
+ keeps them anyway.
47
+
48
+ ## Reading the output
49
+
50
+ The text report prints one `key=value; ...` line per extension, then one line per distinct digest
51
+ labelled `Shared` (named by more than one input) or `Single`. `size=not-held` means the SB3 carries
52
+ only a reference, so the bytes are not there to measure — not that they are missing. `--json` emits
53
+ the same inventory as JSON, with `projects` in input order and `digests` sorted by digest.
54
+
55
+ ## JavaScript API
56
+
57
+ ```js
58
+ import {inventoryExtensionDigests} from '@kubohiroya/sb3-toolchain';
59
+
60
+ const inventory = await inventoryExtensionDigests(['one.sb3', 'two.sb3']);
61
+
62
+ for (const usage of inventory.digests) {
63
+ if (!usage.cacheable) {
64
+ // No input keeps these bytes in the one form a browser may retain.
65
+ console.log(
66
+ usage.sha256,
67
+ usage.ids,
68
+ usage.projects.map((project) => project.uri),
69
+ );
70
+ }
71
+ }
72
+ ```
73
+
74
+ `inspectSb3ExtensionDigests(inputPath, contents)` reports one already-read archive, and
75
+ `readProjectManifest(project)` validates just the `turboWarpPlus` member of a parsed `project.json`,
76
+ returning `null` when a project carries no manifest. A manifest written before the four names
77
+ existed is refused by naming what replaces each retired spelling, rather than translated into a
78
+ choice its author never made.
79
+
80
+ ## Limits
81
+
82
+ Inputs are accepted up to 64 MiB compressed, 256 MiB expanded, and 4096 ZIP entries, with at most
83
+ 64 extensions per manifest. Duplicate inputs, symbolic links, and non-`.sb3` paths are refused.
package/docs/index.html CHANGED
@@ -69,7 +69,7 @@
69
69
  <body>
70
70
  <header>
71
71
  <h1>SB3 Toolchain</h1>
72
- <p><code>@kubohiroya/sb3-toolchain@0.19.1</code></p>
72
+ <p><code>@kubohiroya/sb3-toolchain@0.21.0</code></p>
73
73
  <nav aria-label="Documentation">
74
74
  <a href="#scope">責務</a><a href="#usage">使い方</a><a href="#api">API</a
75
75
  ><a href="#schemas">Schema</a><a href="#guides">関連文書</a>
@@ -90,7 +90,7 @@
90
90
  <section id="usage">
91
91
  <h2>使い方</h2>
92
92
  <p>公開済みの完全固定versionを使います。</p>
93
- <pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.19.1</code></pre>
93
+ <pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.21.0</code></pre>
94
94
  <pre><code>sb3-toolchain import tmp/project.sb3 --output app
95
95
  sb3-toolchain check app
96
96
  sb3-toolchain build app --output dist/project.sb3</code></pre>
@@ -121,6 +121,12 @@ sb3-toolchain build app --output dist/project.sb3</code></pre>
121
121
  <th><code>bundleExtensions</code></th>
122
122
  <td>管理対象の埋込拡張を一つの権限単位へ静的bundleします。</td>
123
123
  </tr>
124
+ <tr>
125
+ <th><code>inventoryExtensionDigests</code></th>
126
+ <td>
127
+ SB3が述べる各拡張のdigest・保持形式・サイズと作品のURIを読み、複数の作品が共有するdigestを示します。取得もブラウザー保存状態の読み取りも行いません。
128
+ </td>
129
+ </tr>
124
130
  </tbody>
125
131
  </table>
126
132
  <p>
@@ -143,9 +149,11 @@ sb3-toolchain build app --output dist/project.sb3</code></pre>
143
149
  <ul>
144
150
  <li><a href="extension-api-compatibility.md">extension-api-compatibility.md</a></li>
145
151
  <li><a href="extension-bundles.md">extension-bundles.md</a></li>
152
+ <li><a href="extension-digests.md">extension-digests.md</a></li>
146
153
  <li><a href="extension-id-migration.md">extension-id-migration.md</a></li>
147
154
  <li><a href="ja/extension-api-compatibility.md">ja/extension-api-compatibility.md</a></li>
148
155
  <li><a href="ja/extension-bundles.md">ja/extension-bundles.md</a></li>
156
+ <li><a href="ja/extension-digests.md">ja/extension-digests.md</a></li>
149
157
  <li><a href="ja/extension-id-migration.md">ja/extension-id-migration.md</a></li>
150
158
  <li><a href="ja/project-asset-additions.md">ja/project-asset-additions.md</a></li>
151
159
  <li><a href="ja/source-format-v1.md">ja/source-format-v1.md</a></li>
@@ -0,0 +1,81 @@
1
+ # 機能拡張のdigestと保持形式を出す
2
+
3
+ ```bash
4
+ sb3-toolchain extensions digests project.sb3 [another.sb3 ...] [--json]
5
+ ```
6
+
7
+ SB3が自分自身について述べていることを読み、マニフェストが挙げる各機能拡張について次を出力します。
8
+
9
+ - 機能拡張のID
10
+ - 固定された`sha256`
11
+ - 作者が選んだ4つの保持形式のどれか(`remote-non-cacheable` / `remote-cacheable` /
12
+ `embedded-file` / `embedded-data`)
13
+ - そのSB3が実際に保持しているバイト数
14
+ - 保持しているバイト列のdigest(固定値と異なる場合のみ表示)
15
+ - 記録されたURL、`embedded-file`の場合はアーカイブ内のパス
16
+ - 要求された実行モード
17
+
18
+ あわせて作品自身の`uri`を出力します。これはブラウザーのキャッシュと、開いた人の記録済みの判断が
19
+ ひも付けられる名前です。SB3を複数与えた場合は、どのdigestが複数の作品から名指され、どれが1作品だけの
20
+ ものかも出力します。
21
+
22
+ ## このコマンドができないこと
23
+
24
+ **ブラウザーの保存状態は読みません。** 機能拡張のキャッシュはIndexedDBにあり、これはオリジンに属すると
25
+ 同時に**ブラウザーのプロファイル**にも属します。コマンドラインからは、実行する人が実際に持っている
26
+ キャッシュには原理的に届きません。自動化されたブラウザーを新たに起動しても、誰も使っていない
27
+ プロファイルが見えるだけです。どの作品がキャッシュされているかを知っているのはブラウザーだけなので、
28
+ 一覧と削除は[`kubohiroya/turbowarp-title-menu#23`](https://github.com/kubohiroya/turbowarp-title-menu/issues/23)
29
+ の画面が担います。このコマンドは、その状態と照合するための一覧を作る側です。
30
+
31
+ **到達性で何も判断しません。** 作品のURIは作者がそこに公開するまで何も返しません。保存したが未公開の
32
+ 作品と、公開済みだが住所が腐った作品は見分けがつきません。SB3の中のURLには一切アクセスせず、
33
+ リクエストが失敗したことを根拠に何かを「無い」と扱うことはありません。与えなかった入力は「不明」で
34
+ あって「無い」ではありません。
35
+
36
+ ## 何に使うか
37
+
38
+ 1. 共通バケットに何を置くべきかの判断材料。複数の作品が名指すdigestは、作品ごとに持つのではなく
39
+ 一度だけ持つ価値のあるバイト列です。
40
+ 2. title-menuの画面の「どの作品からも名指されなくなったキャッシュを消す」モードへの入力。手元の
41
+ 作品群が実際に名指すdigestの集合を渡します。
42
+ 3. 作品を`remote-cacheable`から`remote-non-cacheable`に変換したあと、取り残された古いエントリーを
43
+ 見つける材料。キャッシュを持ちうるのは`remote-cacheable`だけなので、すべての入力で`cacheable`が
44
+ falseのdigestは、もうどの作品も保持を求めていないバイト列です。作者が「残すな」と決めたのに
45
+ ブラウザーに残り続けるなら、その判断は反故になっています。
46
+
47
+ ## 出力の読み方
48
+
49
+ テキスト出力は機能拡張ごとに`key=value; ...`の1行を、続いてdistinctなdigestごとに1行を出します。
50
+ 後者は複数の入力から名指されていれば`Shared`、1つだけなら`Single`と表示します。`size=not-held`は
51
+ そのSB3が参照だけを持っていて、測るべきバイト列がそこに無いという意味で、失われているのではありません。
52
+ `--json`は同じ内容をJSONで出力します。`projects`は入力順、`digests`はdigest順です。
53
+
54
+ ## JavaScript API
55
+
56
+ ```js
57
+ import {inventoryExtensionDigests} from '@kubohiroya/sb3-toolchain';
58
+
59
+ const inventory = await inventoryExtensionDigests(['one.sb3', 'two.sb3']);
60
+
61
+ for (const usage of inventory.digests) {
62
+ if (!usage.cacheable) {
63
+ // どの入力も、ブラウザーが保持しうる唯一の形式では持っていないバイト列。
64
+ console.log(
65
+ usage.sha256,
66
+ usage.ids,
67
+ usage.projects.map((project) => project.uri),
68
+ );
69
+ }
70
+ }
71
+ ```
72
+
73
+ `inspectSb3ExtensionDigests(inputPath, contents)`は既に読み込んだアーカイブ1件を対象にします。
74
+ `readProjectManifest(project)`は、解析済み`project.json`の`turboWarpPlus`メンバーだけを検証し、
75
+ マニフェストを持たない作品では`null`を返します。4つの名前が存在する前に書かれたマニフェストは、
76
+ 作者がしていない選択を勝手に補う代わりに、廃止された綴りごとに何がそれを置き換えるかを示して拒否します。
77
+
78
+ ## 制限
79
+
80
+ 入力は圧縮サイズ64 MiB、展開サイズ256 MiB、ZIPエントリー数4096まで、マニフェスト1件あたりの機能拡張は
81
+ 64件までです。入力の重複、シンボリックリンク、`.sb3`以外のパスは拒否します。
@@ -0,0 +1,41 @@
1
+ # Kamishibai作品SB3の埋め込み機能拡張を一括更新する
2
+
3
+ ```sh
4
+ sb3-toolchain extensions replace-sb3 ari-kirigirisu-20161029.sb3 --output ari-kirigirisu-updated.sb3
5
+ ```
6
+
7
+ `--from`を省略すると、[公式サンプルサイトの公開マニフェスト](https://kubohiroya.github.io/turbowarp-kamishibai-samples/stories/tutorial/public-surfaces.json)から
8
+ ブロック台本SB3のURLを解決し、自動取得します。公開済み状態・バージョンの整合性・ダウンロードしたSB3のサイズとSHA-256を検証してから、入力作品にある次の実装を差し替えます。
9
+
10
+ - `kubohiroyakamishibai4`: Kamishibai DSL 4.0 Runtimeを含むバンドル全体
11
+ - `kubohiroyakamishibaiauthoring4`: Kamishibai Block Script
12
+
13
+ 入力に両方あれば、同じ提供元SB3から両方を更新します。片方だけなら、その機能拡張だけを更新します。提供元に必要なIDがない場合は停止します。取得したコードは実行しません。
14
+
15
+ 取得するのはサンプルサイトで現在公開されているブロック台本です。開発中の候補版は使いません。アプリ本体だけが先に公開され、サンプルサイトの更新がまだの場合は、その本体版を取得できません。公開版が入力のRuntimeヘッダーに記載された版より古い場合は、自動ダウングレードを防ぐため停止します。入力にバージョンヘッダーがない場合は、新旧の比較を省略します。
16
+
17
+ 提供元を手元のファイルに固定する場合は、`--from`を指定します。この場合、ネットワーク通信は不要です。明示的に古い提供元を選ぶこともできます。
18
+
19
+ ```sh
20
+ sb3-toolchain extensions replace-sb3 input.sb3 --from 新版のブロック台本.sb3 --output updated.sb3
21
+ ```
22
+
23
+ 元ファイルを保護するため、入力と提供元は出力先に指定できません。既存の出力内容が異なる場合は、対話確認または`--yes`が必要です。検証失敗時には出力を変更しません。元の作品を開けば更新前の状態に戻れます。
24
+
25
+ 変更するのは`project.json`内の対象IDの`extensionURLs`の値です。その他の機能拡張、ブロック、座標、変数、リスト、`extensionStorage`、素材、および追加のZIPエントリーは保持します。ZIPの圧縮とタイムスタンプ、`project.json`の文字列表現は再生成します。出力には提供元・公開版・SHA-256・更新対象IDを表示します。ローカル提供元にバージョンヘッダーがない場合は`unknown`と表示します。
26
+
27
+ このコマンドはDSLや保存データの移行を行いません。例えば`/assets/SafetyPose`の参照が作品の保存データに残っている場合、そのデータは保持されます。コードの置換だけでは、旧版とのDSL互換性や再生の成功を保証できません。更新後の作品をエディターで再生して確認してください。
28
+
29
+ 入力・提供元の圧縮サイズは64 MiB、展開サイズは256 MiB、ZIPエントリー数は4096までです。ネットワーク取得には各30秒のタイムアウトを設け、マニフェストは1 MiBまで受け付けます。
30
+
31
+ JavaScript APIでも同じ処理を利用できます。
32
+
33
+ ```js
34
+ import {replaceSb3Extensions} from '@kubohiroya/sb3-toolchain';
35
+
36
+ const result = await replaceSb3Extensions({
37
+ inputPath: 'input.sb3',
38
+ outputPath: 'updated.sb3',
39
+ });
40
+ console.log(result.donor, result.extensionIds);
41
+ ```
@@ -1,5 +1,9 @@
1
1
  # SB3ソース管理ワークフロー
2
2
 
3
+ Kamishibai作品SB3に埋め込まれた実装を一括更新する場合は、[SB3の機能拡張更新](sb3-extension-replacement.md)を参照してください。
4
+
5
+ ブラウザーの機能拡張キャッシュと照合する一覧を作る場合は、[機能拡張のdigestと保持形式](extension-digests.md)を参照してください。
6
+
3
7
  [English](../workflows.md)
4
8
 
5
9
  この文書では、Scratch 3またはTurboWarpのSB3をGit内の展開ソースとして管理し、検証済みSB3を再ビルドする
package/docs/workflows.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # SB3 source-management workflows
2
2
 
3
+ To build the list to compare a browser's extension cache against, see
4
+ [extension digests and retention forms](extension-digests.md).
5
+
3
6
  [日本語版](ja/workflows.md)
4
7
 
5
8
  This document describes the common workflow for managing a Scratch 3 or TurboWarp SB3 as expanded
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/sb3-toolchain",
3
- "version": "0.19.1",
3
+ "version": "0.21.0",
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",
@@ -85,9 +85,9 @@
85
85
  "source-control",
86
86
  "reproducible-builds"
87
87
  ],
88
- "gitHead": "642f5c81d99c1892fdfc90b5a9bd52fe90e65184",
88
+ "gitHead": "80bdc3d0bf282234223257aca23c6a79fe31e9c6",
89
89
  "x-turbowarp-source": {
90
- "revision": "642f5c81d99c1892fdfc90b5a9bd52fe90e65184",
90
+ "revision": "80bdc3d0bf282234223257aca23c6a79fe31e9c6",
91
91
  "revisionRole": "base-commit",
92
92
  "sourceState": "local-release-overlay"
93
93
  }