@kubohiroya/sb3-toolchain 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +30 -4
  2. package/README.ja.md +17 -1
  3. package/README.md +17 -1
  4. package/dist/archive.d.ts +1 -0
  5. package/dist/archive.js +16 -0
  6. package/dist/archive.js.map +1 -0
  7. package/dist/assert.d.ts +2 -0
  8. package/dist/assert.js +11 -0
  9. package/dist/assert.js.map +1 -0
  10. package/dist/bin.d.ts +1 -0
  11. package/dist/bin.js +12 -0
  12. package/dist/bin.js.map +1 -0
  13. package/dist/build.d.ts +23 -0
  14. package/dist/build.js +111 -0
  15. package/dist/build.js.map +1 -0
  16. package/dist/cli.d.ts +87 -0
  17. package/dist/cli.js +544 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/constants.d.ts +2 -0
  20. package/dist/constants.js +7 -0
  21. package/dist/constants.js.map +1 -0
  22. package/dist/extension-api-manifest.d.ts +65 -0
  23. package/dist/extension-api-manifest.js +231 -0
  24. package/dist/extension-api-manifest.js.map +1 -0
  25. package/dist/extension-bundle-archive.d.ts +36 -0
  26. package/dist/extension-bundle-archive.js +302 -0
  27. package/dist/extension-bundle-archive.js.map +1 -0
  28. package/dist/extension-bundle-configuration.d.ts +55 -0
  29. package/dist/extension-bundle-configuration.js +200 -0
  30. package/dist/extension-bundle-configuration.js.map +1 -0
  31. package/dist/extension-bundle.d.ts +39 -0
  32. package/dist/extension-bundle.js +580 -0
  33. package/dist/extension-bundle.js.map +1 -0
  34. package/dist/extension-dependencies.d.ts +18 -0
  35. package/dist/extension-dependencies.js +59 -0
  36. package/dist/extension-dependencies.js.map +1 -0
  37. package/dist/extension-id-migration.d.ts +83 -0
  38. package/dist/extension-id-migration.js +292 -0
  39. package/dist/extension-id-migration.js.map +1 -0
  40. package/dist/extension-sync.d.ts +111 -0
  41. package/dist/extension-sync.js +463 -0
  42. package/dist/extension-sync.js.map +1 -0
  43. package/dist/import.d.ts +39 -0
  44. package/dist/import.js +244 -0
  45. package/dist/import.js.map +1 -0
  46. package/dist/index.d.ts +31 -0
  47. package/dist/index.js +18 -0
  48. package/dist/npm-extension-source.d.ts +13 -0
  49. package/dist/npm-extension-source.js +63 -0
  50. package/dist/npm-extension-source.js.map +1 -0
  51. package/dist/output-safety.d.ts +29 -0
  52. package/dist/output-safety.js +213 -0
  53. package/dist/output-safety.js.map +1 -0
  54. package/dist/project-asset-additions.d.ts +29 -0
  55. package/dist/project-asset-additions.js +412 -0
  56. package/dist/project-asset-additions.js.map +1 -0
  57. package/dist/release-snapshot.d.ts +75 -0
  58. package/dist/release-snapshot.js +177 -0
  59. package/dist/release-snapshot.js.map +1 -0
  60. package/dist/source.d.ts +41 -0
  61. package/dist/source.js +282 -0
  62. package/dist/source.js.map +1 -0
  63. package/dist/turbowarp-clean-up.d.ts +18 -0
  64. package/dist/turbowarp-clean-up.js +266 -0
  65. package/dist/turbowarp-clean-up.js.map +1 -0
  66. package/dist/types.d.ts +80 -0
  67. package/package.json +31 -20
  68. package/bin/sb3-toolchain.mjs +0 -9
  69. package/src/archive.js +0 -35
  70. package/src/build.js +0 -188
  71. package/src/cli.js +0 -748
  72. package/src/constants.js +0 -4
  73. package/src/extension-api-manifest.js +0 -336
  74. package/src/extension-bundle-archive.js +0 -422
  75. package/src/extension-bundle-configuration.js +0 -265
  76. package/src/extension-bundle.js +0 -695
  77. package/src/extension-dependencies.js +0 -114
  78. package/src/extension-id-migration.js +0 -496
  79. package/src/extension-sync.js +0 -754
  80. package/src/import.js +0 -397
  81. package/src/index.js +0 -75
  82. package/src/npm-extension-source.js +0 -111
  83. package/src/output-safety.js +0 -322
  84. package/src/project-asset-additions.js +0 -560
  85. package/src/release-snapshot.js +0 -247
  86. package/src/source.js +0 -468
  87. package/src/turbowarp-clean-up.js +0 -295
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-sync.js","names":[],"sources":["../src/extension-sync.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {cp, lstat, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert, errorMessage} from './assert';\nimport {\n compareExtensionApiManifests,\n defaultExtensionApiManifestSizeLimit,\n extensionApiManifestIntegrity,\n formatExtensionApiCompatibilityChanges,\n parseExtensionApiManifest,\n validateExtensionApiManifestSourceMetadata,\n validateManagedExtensionApiManifest,\n} from './extension-api-manifest';\nimport type {ExtensionApiCompatibilityChange, ExtensionApiManifest} from './extension-api-manifest';\nimport {\n extensionHeaderId,\n extensionIntegrity,\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {rewriteExtensionIdDocuments, validateNewExtensionId} from './extension-id-migration';\nimport type {RewriteExtensionIdDocumentsResult} from './extension-id-migration';\nimport {readNpmExtensionSource} from './npm-extension-source';\nimport {\n assertNoInterruptedRollback,\n compareDirectories,\n pathExists,\n replaceDirectoryTransactionally,\n} from './output-safety';\nimport type {DirectoryComparison} from './output-safety';\nimport {\n createDeterministicSb3,\n inspectSb3SourceForExtensionSync,\n validateSb3Source,\n} from './source';\nimport type {InspectedSb3Source} from './source';\nimport type {\n EmbeddedExtension,\n EmbeddedExtensionManifest,\n ExtensionSource,\n GitHubExtensionSource,\n ProjectJson,\n} from './types';\n\nexport const defaultExtensionArtifactSizeLimit = 5 * 1024 * 1024;\nconst githubApiResponseSizeLimit = 1024 * 1024;\n\nexport type FetchImplementation = typeof globalThis.fetch;\n\nexport type ExtensionSyncMode = 'sync' | 'update';\n\n/** The candidate manifest is edited in place as a JSON document before it is written back. */\ninterface MutableExtensionSource {\n apiManifest?: {artifact: string; formatVersion: number; integrity: string; path: string};\n artifact: string;\n integrity: string;\n package?: string;\n provider: string;\n ref?: string;\n resolvedCommit?: string;\n version?: string;\n}\n\ninterface MutableManifestExtension {\n id: string;\n path: string;\n source?: MutableExtensionSource;\n [key: string]: unknown;\n}\n\ninterface MutableExtensionManifest {\n extensions: MutableManifestExtension[];\n [key: string]: unknown;\n}\n\ninterface ApiManifestDownload {\n contents: Buffer;\n manifest: ExtensionApiManifest;\n}\n\ninterface ExtensionDownload {\n apiManifestDownload: ApiManifestDownload | null;\n commit: string | null;\n compatibilityChanges: ExtensionApiCompatibilityChange[];\n contents: Buffer;\n effectiveExtension: EmbeddedExtension;\n extension: EmbeddedExtension;\n npmVersion?: string;\n}\n\nexport interface ExtensionSyncConfirmContext {\n comparison: DirectoryComparison;\n sourceDirectory: string;\n}\n\ninterface UpdateCandidateInput {\n allowBreakingApi: boolean;\n apiManifestArtifact: string | undefined;\n confirmReplace?: (context: ExtensionSyncConfirmContext) => boolean | Promise<boolean>;\n fetchImplementation?: FetchImplementation;\n maximumArtifactBytes: number;\n maximumManifestBytes: number;\n migrateToId: string | undefined;\n mode: ExtensionSyncMode;\n selectedExtensionId: string | undefined;\n sourceArtifact: string | undefined;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface SyncExtensionsOptions {\n confirmReplace?: (context: ExtensionSyncConfirmContext) => boolean | Promise<boolean>;\n fetch?: FetchImplementation;\n maximumArtifactBytes?: number;\n maximumManifestBytes?: number;\n sourceDirectory: string;\n yes?: boolean;\n}\n\nexport interface UpdateExtensionsOptions extends SyncExtensionsOptions {\n allowBreakingApi?: boolean;\n apiManifestArtifact?: string;\n extensionId?: string;\n migrateToId?: string;\n sourceArtifact?: string;\n}\n\nfunction assertFetch(fetchImplementation: FetchImplementation | undefined): FetchImplementation {\n assert(\n typeof fetchImplementation === 'function',\n 'A Fetch API implementation is required for GitHub extension operations.',\n );\n return fetchImplementation;\n}\n\nfunction githubHeaders(accept: string): Record<string, string> {\n return {\n Accept: accept,\n 'User-Agent': 'sb3-toolchain',\n 'X-GitHub-Api-Version': '2022-11-28',\n };\n}\n\nfunction rawArtifactUrl(\n source: GitHubExtensionSource,\n commit: string,\n artifactPath: string = source.artifact,\n): string {\n const artifact = artifactPath\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n return `https://raw.githubusercontent.com/${source.repository}/${commit}/${artifact}`;\n}\n\nasync function downloadExtensionApiManifest(\n extension: EmbeddedExtension,\n commit: string,\n fetchImplementation: FetchImplementation,\n maximumManifestBytes: number,\n expectedId: string = extension.id,\n): Promise<ApiManifestDownload | null> {\n const metadata = validateExtensionApiManifestSourceMetadata(extension);\n if (!metadata) return null;\n const contents = await fetchBytes(\n fetchImplementation,\n rawArtifactUrl(extension.source as GitHubExtensionSource, commit, metadata.artifact),\n maximumManifestBytes,\n `GitHub extension API manifest download for ${extension.id}`,\n 'application/json',\n );\n const manifest = parseExtensionApiManifest(contents, {expectedId});\n return {contents, manifest};\n}\n\nfunction githubCommitUrl(source: GitHubExtensionSource): string {\n return (\n `https://api.github.com/repos/${source.repository}/commits/` + encodeURIComponent(source.ref)\n );\n}\n\nasync function readLimitedResponse(\n response: Response,\n maximumBytes: number,\n description: string,\n): Promise<Buffer> {\n const contentLength = response.headers?.get?.('content-length');\n if (contentLength !== null && contentLength !== undefined) {\n const parsedLength = Number(contentLength);\n assert(\n Number.isSafeInteger(parsedLength) && parsedLength >= 0,\n `${description} returned an invalid Content-Length.`,\n );\n assert(parsedLength <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);\n }\n\n if (!response.body?.getReader) {\n const contents = Buffer.from(await response.arrayBuffer());\n assert(\n contents.length <= maximumBytes,\n `${description} exceeds the ${maximumBytes}-byte limit.`,\n );\n return contents;\n }\n\n const reader = response.body.getReader();\n const chunks: Buffer[] = [];\n let totalLength = 0;\n try {\n while (true) {\n const {done, value} = await reader.read();\n if (done) break;\n totalLength += value.byteLength;\n assert(totalLength <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);\n chunks.push(Buffer.from(value));\n }\n } catch (error) {\n await reader.cancel(error).catch(() => {});\n throw error;\n }\n return Buffer.concat(chunks, totalLength);\n}\n\nasync function fetchBytes(\n fetchImplementation: FetchImplementation,\n url: string,\n maximumBytes: number,\n description: string,\n accept: string,\n): Promise<Buffer> {\n const parsedUrl = new URL(url);\n assert(parsedUrl.protocol === 'https:', `${description} requires HTTPS.`);\n let response: Response;\n try {\n response = await fetchImplementation(url, {\n headers: githubHeaders(accept),\n redirect: 'error',\n });\n } catch (error) {\n throw new Error(`${description} request failed: ${errorMessage(error)}`, {cause: error});\n }\n assert(\n response && typeof response === 'object',\n `${description} request returned an invalid response.`,\n );\n assert(\n response.redirected !== true &&\n (!response.url || new URL(response.url).href === parsedUrl.href),\n `${description} refused a redirected response.`,\n );\n assert(response.ok, `${description} request failed with HTTP ${response.status ?? '(unknown)'}.`);\n return readLimitedResponse(response, maximumBytes, description);\n}\n\nasync function resolveGithubCommit(\n extension: EmbeddedExtension,\n fetchImplementation: FetchImplementation,\n): Promise<string> {\n const source = extension.source as GitHubExtensionSource;\n if (/^[a-f0-9]{40}$/u.test(source.ref)) {\n return source.ref;\n }\n const contents = await fetchBytes(\n fetchImplementation,\n githubCommitUrl(source),\n githubApiResponseSizeLimit,\n `GitHub ref lookup for ${extension.id}`,\n 'application/vnd.github+json',\n );\n let response: {sha?: unknown} | null;\n try {\n response = JSON.parse(contents.toString('utf8'));\n } catch (error) {\n throw new Error(`GitHub ref lookup for ${extension.id} returned invalid JSON.`, {cause: error});\n }\n assert(\n typeof response?.sha === 'string' && /^[a-f0-9]{40}$/u.test(response.sha),\n `GitHub ref lookup for ${extension.id} returned an invalid commit SHA.`,\n );\n return response.sha as string;\n}\n\nasync function downloadExtension(\n extension: EmbeddedExtension,\n commit: string,\n fetchImplementation: FetchImplementation,\n maximumArtifactBytes: number,\n expectedId: string = extension.id,\n): Promise<Buffer> {\n const contents = await fetchBytes(\n fetchImplementation,\n rawArtifactUrl(extension.source as GitHubExtensionSource, commit),\n maximumArtifactBytes,\n `GitHub artifact download for ${extension.id}`,\n 'application/javascript, text/javascript;q=0.9, */*;q=0.1',\n );\n const actualId = extensionHeaderId(contents);\n assert(\n actualId === expectedId,\n `Downloaded extension header ID mismatch for ${extension.id}: ` +\n `expected ${expectedId}, got ${actualId ?? '(missing)'}`,\n );\n return contents;\n}\n\nfunction managedExtensions(source: InspectedSb3Source): EmbeddedExtension[] {\n return source.extensions.filter((extension) => extension.source !== undefined);\n}\n\nasync function inspectExtensionSource(\n sourceDirectory: string,\n {willReplace = false}: {willReplace?: boolean} = {},\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n if (willReplace) {\n assert(\n resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root,\n 'Refusing to replace a filesystem root during extension synchronization.',\n );\n assert(\n !(await pathExists(path.join(resolvedSourceDirectory, '.git'))),\n 'Refusing to replace a Git repository root during extension synchronization.',\n );\n }\n const stats = await lstat(resolvedSourceDirectory);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`,\n );\n if (willReplace) {\n await assertNoInterruptedRollback(resolvedSourceDirectory);\n }\n return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);\n}\n\nasync function installCandidate({\n candidateDirectory,\n confirmReplace,\n initialSourceFingerprint,\n sourceDirectory,\n yes,\n}: {\n candidateDirectory: string;\n confirmReplace?: (context: ExtensionSyncConfirmContext) => boolean | Promise<boolean>;\n initialSourceFingerprint: string;\n sourceDirectory: string;\n yes: boolean;\n}): Promise<{\n changed: boolean;\n comparison: DirectoryComparison;\n rollbackCleanupWarning: string | null;\n}> {\n const comparison = await compareDirectories(sourceDirectory, candidateDirectory);\n assert(\n comparison.existingFingerprint === initialSourceFingerprint,\n 'SB3 source changed while extension artifacts were being fetched; refusing to replace it.',\n );\n if (comparison.identical) {\n await rm(candidateDirectory, {recursive: true, force: true});\n return {changed: false, comparison, rollbackCleanupWarning: null};\n }\n\n const context = {comparison, sourceDirectory};\n if (!yes) {\n assert(\n typeof confirmReplace === 'function',\n `Managed extension files differ in ${sourceDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n assert(\n await confirmReplace(context),\n 'Extension synchronization cancelled; the existing source was not changed.',\n );\n }\n\n const latestComparison = await compareDirectories(sourceDirectory, candidateDirectory);\n assert(\n latestComparison.existingFingerprint === comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === comparison.candidateFingerprint,\n 'SB3 source or extension candidate changed during synchronization; refusing to replace it.',\n );\n const replacement = await replaceDirectoryTransactionally(candidateDirectory, sourceDirectory);\n return {changed: true, comparison, ...replacement};\n}\n\nasync function updateCandidate({\n allowBreakingApi,\n apiManifestArtifact,\n confirmReplace,\n fetchImplementation,\n maximumArtifactBytes,\n maximumManifestBytes,\n migrateToId,\n mode,\n selectedExtensionId,\n sourceArtifact,\n sourceDirectory,\n yes,\n}: UpdateCandidateInput) {\n assert(\n Number.isSafeInteger(maximumArtifactBytes) && maximumArtifactBytes > 0,\n 'maximumArtifactBytes must be a positive integer.',\n );\n assert(\n Number.isSafeInteger(maximumManifestBytes) && maximumManifestBytes > 0,\n 'maximumManifestBytes must be a positive integer.',\n );\n assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');\n const source = await inspectExtensionSource(sourceDirectory, {willReplace: true});\n const initialComparison = await compareDirectories(\n source.resolvedSourceDirectory,\n source.resolvedSourceDirectory,\n );\n assert(\n initialComparison.identical &&\n initialComparison.existingFingerprint === initialComparison.candidateFingerprint,\n 'SB3 source changed while its initial state was being inspected.',\n );\n const managed = managedExtensions(source);\n assert(managed.length > 0, 'No managed embedded extensions were found.');\n if (selectedExtensionId !== undefined) {\n assert(\n managed.some((extension) => extension.id === selectedExtensionId),\n `Managed extension was not found: ${selectedExtensionId}`,\n );\n }\n const selected = managed.filter(\n (extension) => selectedExtensionId === undefined || extension.id === selectedExtensionId,\n );\n if (migrateToId !== undefined) {\n assert(mode === 'update', 'Extension ID migration is only available during update.');\n assert(\n selectedExtensionId !== undefined,\n 'Extension ID migration requires an explicit existing extension ID.',\n );\n validateNewExtensionId(migrateToId);\n assert(\n selected.every((extension) => extension.source?.provider === 'github'),\n 'Extension ID migration is not supported for npm-managed extensions.',\n );\n }\n assert(\n sourceArtifact === undefined || migrateToId !== undefined,\n 'A replacement artifact path requires an extension ID migration.',\n );\n assert(\n apiManifestArtifact === undefined || migrateToId !== undefined,\n 'A replacement API manifest artifact path requires an extension ID migration.',\n );\n if (migrateToId !== undefined) {\n const extensionManifest = JSON.parse(\n await readFile(\n path.join(source.resolvedSourceDirectory, source.sourceManifest.embeddedExtensions),\n 'utf8',\n ),\n ) as EmbeddedExtensionManifest;\n assert(selectedExtensionId !== undefined, 'Extension ID migration requires an extension ID.');\n rewriteExtensionIdDocuments({\n apiManifestArtifact,\n extensionManifest,\n newId: migrateToId,\n oldId: selectedExtensionId,\n project: source.project,\n sourceArtifact,\n });\n }\n\n const downloads: ExtensionDownload[] = await Promise.all(\n selected.map(async (extension): Promise<ExtensionDownload> => {\n let effectiveExtension = extension;\n if (sourceArtifact !== undefined || apiManifestArtifact !== undefined) {\n const effectiveSource = {...extension.source} as ExtensionSource;\n if (sourceArtifact !== undefined) effectiveSource.artifact = sourceArtifact;\n if (apiManifestArtifact !== undefined) {\n assert(\n effectiveSource.apiManifest,\n `Extension ${extension.id} has no managed API manifest metadata.`,\n );\n effectiveSource.apiManifest = {\n ...effectiveSource.apiManifest,\n artifact: apiManifestArtifact,\n };\n }\n effectiveExtension = {...extension, source: effectiveSource};\n }\n validateExtensionSourceMetadata(effectiveExtension);\n if (effectiveExtension.source?.provider === 'npm') {\n const npmSource = await readNpmExtensionSource(\n effectiveExtension,\n source.resolvedSourceDirectory,\n {\n allowVersionMismatch: mode === 'update',\n maximumArtifactBytes,\n maximumManifestBytes,\n },\n );\n const apiManifestDownload = npmSource.apiManifestContents\n ? {\n contents: npmSource.apiManifestContents,\n manifest: parseExtensionApiManifest(npmSource.apiManifestContents, {\n expectedId: extension.id,\n }),\n }\n : null;\n let compatibilityChanges: ExtensionApiCompatibilityChange[] = [];\n if (mode === 'sync') {\n validateManagedExtensionContents(extension, npmSource.contents);\n if (apiManifestDownload) {\n validateManagedExtensionApiManifest(extension, apiManifestDownload.contents);\n }\n } else if (apiManifestDownload) {\n const installedApiManifestContents = source.extensionApiManifestContents.get(\n extension.id,\n );\n assert(\n installedApiManifestContents,\n `Managed extension API manifest is missing for ${extension.id}.`,\n );\n const installedApiManifest = validateManagedExtensionApiManifest(\n extension,\n installedApiManifestContents,\n )?.manifest;\n assert(\n installedApiManifest,\n `Managed extension API manifest is invalid: ${extension.id}`,\n );\n compatibilityChanges = compareExtensionApiManifests(\n installedApiManifest,\n apiManifestDownload.manifest,\n );\n }\n return {\n apiManifestDownload,\n commit: null,\n compatibilityChanges,\n contents: npmSource.contents,\n effectiveExtension,\n extension,\n npmVersion: npmSource.version,\n };\n }\n const githubFetch = assertFetch(fetchImplementation);\n const commit =\n mode === 'sync'\n ? (extension.source as GitHubExtensionSource).resolvedCommit\n : await resolveGithubCommit(extension, githubFetch);\n const expectedId = migrateToId ?? extension.id;\n const [contents, apiManifestDownload] = await Promise.all([\n downloadExtension(\n effectiveExtension,\n commit,\n githubFetch,\n maximumArtifactBytes,\n expectedId,\n ),\n downloadExtensionApiManifest(\n effectiveExtension,\n commit,\n githubFetch,\n maximumManifestBytes,\n expectedId,\n ),\n ]);\n let compatibilityChanges: ExtensionApiCompatibilityChange[] = [];\n if (mode === 'sync') {\n validateManagedExtensionContents(extension, contents);\n if (apiManifestDownload) {\n validateManagedExtensionApiManifest(extension, apiManifestDownload.contents);\n }\n } else if (apiManifestDownload) {\n const installedApiManifestContents = source.extensionApiManifestContents.get(extension.id);\n assert(\n installedApiManifestContents,\n `Managed extension API manifest is missing for ${extension.id}.`,\n );\n const installedApiManifest = validateManagedExtensionApiManifest(\n extension,\n installedApiManifestContents,\n )?.manifest;\n assert(installedApiManifest, `Managed extension API manifest is invalid: ${extension.id}`);\n compatibilityChanges = compareExtensionApiManifests(\n installedApiManifest,\n apiManifestDownload.manifest,\n );\n }\n return {\n apiManifestDownload,\n commit,\n compatibilityChanges,\n contents,\n effectiveExtension,\n extension,\n };\n }),\n );\n const breakingApiChanges = downloads.flatMap((download) =>\n download.compatibilityChanges\n .filter((change) => change.breaking)\n .map((change) => ({...change, extensionId: download.extension.id})),\n );\n if (breakingApiChanges.length > 0 && !allowBreakingApi) {\n const details = downloads\n .filter((download) => download.compatibilityChanges.some((change) => change.breaking))\n .map((download) =>\n formatExtensionApiCompatibilityChanges(\n download.extension.id,\n download.compatibilityChanges.filter((change) => change.breaking),\n ),\n )\n .join('\\n');\n throw new Error(\n `Extension API update contains ${breakingApiChanges.length} breaking change(s). ` +\n 'Review the reported paths, then use --allow-breaking-api with --yes to apply.\\n' +\n details,\n );\n }\n\n const parentDirectory = path.dirname(source.resolvedSourceDirectory);\n const candidateDirectory = await mkdtemp(\n path.join(parentDirectory, `.${path.basename(source.resolvedSourceDirectory)}.extensions-`),\n );\n let installed = false;\n try {\n await cp(source.resolvedSourceDirectory, candidateDirectory, {\n preserveTimestamps: true,\n recursive: true,\n verbatimSymlinks: true,\n });\n const manifestPath = path.join(candidateDirectory, source.sourceManifest.embeddedExtensions);\n const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as MutableExtensionManifest;\n const projectPath = path.join(candidateDirectory, source.sourceManifest.project);\n const entriesById = new Map(manifest.extensions.map((entry) => [entry.id, entry]));\n let manifestChanged = false;\n let migration: RewriteExtensionIdDocumentsResult | undefined;\n for (const {\n apiManifestDownload,\n commit,\n contents,\n effectiveExtension,\n extension,\n npmVersion,\n } of downloads) {\n if (migrateToId !== undefined) {\n const project = JSON.parse(await readFile(projectPath, 'utf8')) as ProjectJson;\n migration = rewriteExtensionIdDocuments({\n apiManifestArtifact,\n extensionManifest: manifest as unknown as EmbeddedExtensionManifest,\n newId: migrateToId,\n oldId: extension.id,\n project,\n sourceArtifact: effectiveExtension.source?.artifact,\n });\n const migratedExtension = migration.extensionManifest.extensions[\n migration.extensionIndex\n ] as unknown as MutableManifestExtension;\n const migratedSource = migratedExtension.source;\n assert(migratedSource, `Migrated extension has no source metadata: ${extension.id}`);\n migratedSource.resolvedCommit = commit ?? undefined;\n migratedSource.integrity = extensionIntegrity(contents);\n if (apiManifestDownload && migratedSource.apiManifest) {\n migratedSource.apiManifest.integrity = extensionApiManifestIntegrity(\n apiManifestDownload.contents,\n );\n }\n const writes = [\n writeFile(projectPath, `${JSON.stringify(migration.project, null, 2)}\\n`),\n writeFile(manifestPath, `${JSON.stringify(migration.extensionManifest, null, 2)}\\n`),\n writeFile(path.join(candidateDirectory, migration.newPath), contents),\n ];\n if (apiManifestDownload && migration.newApiManifestPath) {\n writes.push(\n writeFile(\n path.join(candidateDirectory, migration.newApiManifestPath),\n apiManifestDownload.contents,\n ),\n );\n }\n await Promise.all(writes);\n await rm(path.join(candidateDirectory, migration.oldPath));\n if (migration.oldApiManifestPath) {\n await rm(path.join(candidateDirectory, migration.oldApiManifestPath));\n }\n continue;\n }\n await writeFile(path.join(candidateDirectory, extension.path), contents);\n if (apiManifestDownload) {\n const apiManifestPath = extension.source?.apiManifest?.path;\n assert(apiManifestPath, `Managed extension API manifest path is missing: ${extension.id}`);\n await writeFile(\n path.join(candidateDirectory, apiManifestPath),\n apiManifestDownload.contents,\n );\n }\n if (mode === 'update') {\n const candidateExtension = entriesById.get(extension.id);\n assert(candidateExtension, `Extension manifest entry disappeared: ${extension.id}`);\n const candidateSource = candidateExtension.source;\n assert(candidateSource, `Extension manifest entry has no source: ${extension.id}`);\n const integrity = extensionIntegrity(contents);\n manifestChanged = manifestChanged || candidateSource.integrity !== integrity;\n if (candidateSource.provider === 'npm') {\n manifestChanged = manifestChanged || candidateSource.version !== npmVersion;\n candidateSource.version = npmVersion;\n } else {\n manifestChanged = manifestChanged || candidateSource.resolvedCommit !== commit;\n candidateSource.resolvedCommit = commit ?? undefined;\n }\n candidateSource.integrity = integrity;\n if (apiManifestDownload && candidateSource.apiManifest) {\n const apiManifestIntegrity = extensionApiManifestIntegrity(apiManifestDownload.contents);\n manifestChanged =\n manifestChanged || candidateSource.apiManifest.integrity !== apiManifestIntegrity;\n candidateSource.apiManifest.integrity = apiManifestIntegrity;\n candidateSource.apiManifest.formatVersion = apiManifestDownload.manifest.formatVersion;\n }\n }\n }\n if (manifestChanged && migrateToId === undefined) {\n await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n }\n if (migration) {\n await createDeterministicSb3(candidateDirectory);\n } else {\n await validateSb3Source(candidateDirectory);\n }\n const result = await installCandidate({\n candidateDirectory,\n confirmReplace,\n initialSourceFingerprint: initialComparison.existingFingerprint,\n sourceDirectory: source.resolvedSourceDirectory,\n yes,\n });\n installed = true;\n return {\n ...result,\n apiCompatibility: downloads\n .filter(({apiManifestDownload}) => apiManifestDownload !== null)\n .map(({compatibilityChanges, extension}) => ({\n changes: compatibilityChanges,\n id: migrateToId ?? extension.id,\n previousId: migrateToId === undefined ? undefined : extension.id,\n })),\n extensions: downloads.map(({commit, extension, npmVersion}) => {\n const extensionSource = extension.source;\n return extensionSource?.provider === 'npm'\n ? {\n id: extension.id,\n package: extensionSource.package,\n version: npmVersion,\n }\n : {\n id: migrateToId ?? extension.id,\n previousId: migrateToId === undefined ? undefined : extension.id,\n resolvedCommit: commit,\n };\n }),\n migration:\n migration === undefined\n ? null\n : {\n counts: migration.counts,\n fromId: selectedExtensionId,\n toId: migrateToId,\n totalChanges: migration.totalChanges,\n unclassifiedReferences: migration.unclassifiedReferences,\n },\n mode,\n sourceDirectory: source.resolvedSourceDirectory,\n };\n } finally {\n if (!installed) {\n await rm(candidateDirectory, {recursive: true, force: true});\n }\n }\n}\n\nexport async function extensionStatus(\n sourceDirectory: string,\n {fetch: fetchImplementation = globalThis.fetch}: {fetch?: FetchImplementation} = {},\n) {\n const source = await inspectExtensionSource(sourceDirectory);\n return Promise.all(\n managedExtensions(source).map(async (extension) => {\n const extensionSource = extension.source;\n assert(extensionSource, `Managed extension has no source metadata: ${extension.id}`);\n let local = 'valid';\n try {\n const contents = source.extensionContents.get(extension.id);\n assert(contents, `Managed extension contents are missing: ${extension.id}`);\n validateManagedExtensionContents(extension, contents);\n if (extensionSource.apiManifest) {\n const apiManifestContents = source.extensionApiManifestContents.get(extension.id);\n assert(apiManifestContents, `Managed extension API manifest is missing: ${extension.id}`);\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n } catch {\n local = 'modified';\n }\n if (extensionSource.provider === 'npm') {\n const npmSource = await readNpmExtensionSource(extension, source.resolvedSourceDirectory, {\n allowVersionMismatch: true,\n maximumArtifactBytes: defaultExtensionArtifactSizeLimit,\n maximumManifestBytes: defaultExtensionApiManifestSizeLimit,\n });\n if (npmSource.version === extensionSource.version) {\n validateManagedExtensionContents(extension, npmSource.contents);\n if (npmSource.apiManifestContents) {\n validateManagedExtensionApiManifest(extension, npmSource.apiManifestContents);\n }\n }\n return {\n id: extension.id,\n installedVersion: npmSource.version,\n local,\n package: extensionSource.package,\n state: npmSource.version === extensionSource.version ? 'current' : 'update-available',\n version: extensionSource.version,\n };\n }\n const remoteCommit = await resolveGithubCommit(extension, assertFetch(fetchImplementation));\n return {\n id: extension.id,\n local,\n ref: extensionSource.ref,\n remoteCommit,\n resolvedCommit: extensionSource.resolvedCommit,\n state: remoteCommit === extensionSource.resolvedCommit ? 'current' : 'update-available',\n };\n }),\n );\n}\n\nexport async function syncExtensions({\n confirmReplace,\n fetch: fetchImplementation = globalThis.fetch,\n maximumArtifactBytes = defaultExtensionArtifactSizeLimit,\n maximumManifestBytes = defaultExtensionApiManifestSizeLimit,\n sourceDirectory,\n yes = false,\n}: SyncExtensionsOptions) {\n return updateCandidate({\n allowBreakingApi: false,\n apiManifestArtifact: undefined,\n confirmReplace,\n fetchImplementation,\n maximumArtifactBytes,\n maximumManifestBytes,\n migrateToId: undefined,\n mode: 'sync',\n selectedExtensionId: undefined,\n sourceArtifact: undefined,\n sourceDirectory,\n yes,\n });\n}\n\nexport async function updateExtensions({\n allowBreakingApi = false,\n apiManifestArtifact,\n confirmReplace,\n extensionId,\n fetch: fetchImplementation = globalThis.fetch,\n maximumArtifactBytes = defaultExtensionArtifactSizeLimit,\n maximumManifestBytes = defaultExtensionApiManifestSizeLimit,\n migrateToId,\n sourceArtifact,\n sourceDirectory,\n yes = false,\n}: UpdateExtensionsOptions) {\n return updateCandidate({\n allowBreakingApi,\n apiManifestArtifact,\n confirmReplace,\n fetchImplementation,\n maximumArtifactBytes,\n maximumManifestBytes,\n migrateToId,\n mode: 'update',\n selectedExtensionId: extensionId,\n sourceArtifact,\n sourceDirectory,\n yes,\n });\n}\n"],"mappings":";;;;;;;;;;AA8CA,IAAa,oCAAoC;AACjD,IAAM,6BAA6B;AAkFnC,SAAS,YAAY,qBAA2E;CAC9F,OACE,OAAO,wBAAwB,YAC/B,yEACF;CACA,OAAO;AACT;AAEA,SAAS,cAAc,QAAwC;CAC7D,OAAO;EACL,QAAQ;EACR,cAAc;EACd,wBAAwB;CAC1B;AACF;AAEA,SAAS,eACP,QACA,QACA,eAAuB,OAAO,UACtB;CACR,MAAM,WAAW,aACd,MAAM,GAAG,CAAC,CACV,KAAK,YAAY,mBAAmB,OAAO,CAAC,CAAC,CAC7C,KAAK,GAAG;CACX,OAAO,qCAAqC,OAAO,WAAW,GAAG,OAAO,GAAG;AAC7E;AAEA,eAAe,6BACb,WACA,QACA,qBACA,sBACA,aAAqB,UAAU,IACM;CACrC,MAAM,WAAW,2CAA2C,SAAS;CACrE,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,WAAW,MAAM,WACrB,qBACA,eAAe,UAAU,QAAiC,QAAQ,SAAS,QAAQ,GACnF,sBACA,8CAA8C,UAAU,MACxD,kBACF;CAEA,OAAO;EAAC;EAAU,UADD,0BAA0B,UAAU,EAAC,WAAU,CAC9C;CAAQ;AAC5B;AAEA,SAAS,gBAAgB,QAAuC;CAC9D,OACE,gCAAgC,OAAO,WAAW,aAAa,mBAAmB,OAAO,GAAG;AAEhG;AAEA,eAAe,oBACb,UACA,cACA,aACiB;CACjB,MAAM,gBAAgB,SAAS,SAAS,MA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BAAqB;EACrB;EACA;EACA;CACF,CAAC;AACH"}
@@ -0,0 +1,39 @@
1
+ import { DirectoryComparison, GitOutputState } from './output-safety';
2
+ import { ExtensionEncoding } from './types';
3
+ export { validateOutputDirectoryPath } from './output-safety';
4
+ export interface DecodedExtensionDataUrl {
5
+ encoding: ExtensionEncoding;
6
+ mediaType: string;
7
+ parameters: string[];
8
+ source: Buffer;
9
+ }
10
+ export interface OutputReplacementContext {
11
+ comparison: DirectoryComparison;
12
+ discardLocalChanges: boolean;
13
+ gitState: GitOutputState;
14
+ outputDirectory: string;
15
+ }
16
+ export interface ImportSb3Options {
17
+ confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;
18
+ discardLocalChanges?: boolean;
19
+ inputPath: string;
20
+ outputDirectory: string;
21
+ protectedRoot?: string;
22
+ yes?: boolean;
23
+ }
24
+ export interface ImportSb3Result {
25
+ archiveEntryCount: number;
26
+ assetCount: number;
27
+ changed: boolean;
28
+ differenceCounts: {
29
+ added: number;
30
+ modified: number;
31
+ removed: number;
32
+ } | null;
33
+ embeddedExtensionCount: number;
34
+ inputPath: string;
35
+ outputDirectory: string;
36
+ rollbackCleanupWarning: string | null;
37
+ }
38
+ export declare function decodeExtensionDataUrl(dataUrl: unknown): DecodedExtensionDataUrl;
39
+ export declare function importSb3({ inputPath, outputDirectory, protectedRoot, discardLocalChanges, yes, confirmReplace, }: ImportSb3Options): Promise<ImportSb3Result>;
package/dist/import.js ADDED
@@ -0,0 +1,244 @@
1
+ import { assert, errorMessage } from "./assert.js";
2
+ import { assertNoInterruptedRollback, assertRecognizedOutputDirectory, compareDirectories, inspectGitOutputState, pathExists, replaceDirectoryTransactionally, validateOutputDirectoryPath } from "./output-safety.js";
3
+ import { validateArchiveEntryName } from "./archive.js";
4
+ import { validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
5
+ import { validateManagedExtensionContents } from "./extension-dependencies.js";
6
+ import "./source.js";
7
+ import process from "node:process";
8
+ import path from "node:path";
9
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10
+ import { strFromU8, unzipSync } from "fflate";
11
+ //#region src/import.ts
12
+ function isObject(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ function summarizeGitChanges(gitState) {
16
+ const entries = [...gitState.statusEntries, ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`)];
17
+ return `${entries.slice(0, 8).join(", ")}${entries.length > 8 ? `, and ${entries.length - 8} more` : ""}`;
18
+ }
19
+ async function authorizeOutputReplacement({ candidateDirectory, confirmReplace, discardLocalChanges, outputDirectory, yes }) {
20
+ await assertNoInterruptedRollback(outputDirectory);
21
+ if (!await pathExists(outputDirectory)) return {
22
+ action: "create",
23
+ comparison: null,
24
+ gitState: null
25
+ };
26
+ await assertRecognizedOutputDirectory(outputDirectory, 1);
27
+ const comparison = await compareDirectories(outputDirectory, candidateDirectory);
28
+ if (comparison.identical) return {
29
+ action: "unchanged",
30
+ comparison,
31
+ gitState: null
32
+ };
33
+ const gitState = await inspectGitOutputState(outputDirectory, comparison.existingFilePaths);
34
+ assert(gitState.managed, `Existing output differs from the SB3 candidate but is not tracked by Git: ${outputDirectory}. Import to a new output directory instead of replacing unrecoverable content.`);
35
+ assert(gitState.clean || discardLocalChanges, `Existing output differs from the SB3 candidate and has uncommitted Git changes: ${summarizeGitChanges(gitState)}. Commit or stash them first, or explicitly use --discard-local-changes.`);
36
+ const context = {
37
+ comparison,
38
+ discardLocalChanges,
39
+ gitState,
40
+ outputDirectory
41
+ };
42
+ if (yes) return {
43
+ action: "replace",
44
+ ...context
45
+ };
46
+ assert(typeof confirmReplace === "function", `Output directory already exists: ${outputDirectory}. Refusing to replace differing content without interactive confirmation or --yes.`);
47
+ assert(await confirmReplace(context), "SB3 import cancelled; the existing output was not changed.");
48
+ return {
49
+ action: "replace",
50
+ ...context
51
+ };
52
+ }
53
+ async function revalidateOutputReplacement({ candidateDirectory, decision, discardLocalChanges, outputDirectory }) {
54
+ const latestComparison = await compareDirectories(outputDirectory, candidateDirectory);
55
+ assert(latestComparison.existingFingerprint === decision.comparison.existingFingerprint && latestComparison.candidateFingerprint === decision.comparison.candidateFingerprint, "Output or candidate content changed during SB3 import; refusing to replace it.");
56
+ const latestGitState = await inspectGitOutputState(outputDirectory, latestComparison.existingFilePaths);
57
+ assert(latestGitState.managed, "Output stopped being Git-managed during SB3 import; refusing to replace it.");
58
+ assert(latestGitState.fingerprint === decision.gitState.fingerprint, "Git state changed during SB3 import; refusing to replace the output.");
59
+ assert(latestGitState.clean || discardLocalChanges, "Output gained uncommitted Git changes during SB3 import; refusing to replace it.");
60
+ }
61
+ function extensionSourcePath(extensionId) {
62
+ assert(/^[A-Za-z0-9._-]+$/u.test(extensionId), `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`);
63
+ return `extensions/${extensionId}.js`;
64
+ }
65
+ async function readExistingExtensionSources(outputDirectory) {
66
+ if (!await pathExists(outputDirectory)) return /* @__PURE__ */ new Map();
67
+ const manifestPath = path.join(outputDirectory, "embedded-extensions.json");
68
+ if (!await pathExists(manifestPath)) return /* @__PURE__ */ new Map();
69
+ let manifest;
70
+ try {
71
+ manifest = JSON.parse(await readFile(manifestPath, "utf8"));
72
+ } catch (error) {
73
+ throw new Error(`Existing embedded extension manifest is not valid JSON: ${manifestPath}`, { cause: error });
74
+ }
75
+ assert(isObject(manifest) && Array.isArray(manifest.extensions), `Existing embedded extension manifest is invalid: ${manifestPath}`);
76
+ const sources = /* @__PURE__ */ new Map();
77
+ for (const extension of manifest.extensions) {
78
+ if (!isObject(extension) || typeof extension.id !== "string" || typeof extension.path !== "string" || extension.source === void 0) continue;
79
+ sources.set(`${extension.id}\u0000${extension.path}`, extension.source);
80
+ }
81
+ return sources;
82
+ }
83
+ function decodeExtensionDataUrl(dataUrl) {
84
+ assert(typeof dataUrl === "string" && dataUrl.startsWith("data:"), "Embedded extension URL must be a data URL.");
85
+ const commaIndex = dataUrl.indexOf(",");
86
+ assert(commaIndex >= 0, "Embedded extension data URL has no payload separator.");
87
+ const metadata = dataUrl.slice(5, commaIndex).split(";");
88
+ const mediaType = metadata.shift() || "text/plain";
89
+ const base64Index = metadata.indexOf("base64");
90
+ const encoding = base64Index >= 0 ? "base64" : "percent";
91
+ if (base64Index >= 0) metadata.splice(base64Index, 1);
92
+ const payload = dataUrl.slice(commaIndex + 1);
93
+ let source;
94
+ if (encoding === "base64") {
95
+ assert(/^[A-Za-z0-9+/]*={0,2}$/u.test(payload), "Embedded extension data URL contains invalid base64.");
96
+ const unpaddedPayload = payload.replace(/=+$/u, "");
97
+ assert(unpaddedPayload.length % 4 !== 1, "Embedded extension data URL contains invalid base64.");
98
+ source = Buffer.from(unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, "="), "base64");
99
+ } else try {
100
+ source = Buffer.from(decodeURIComponent(payload), "utf8");
101
+ } catch {
102
+ throw new Error("Embedded extension data URL contains invalid percent encoding.");
103
+ }
104
+ return {
105
+ encoding,
106
+ mediaType,
107
+ parameters: metadata,
108
+ source
109
+ };
110
+ }
111
+ async function importSb3({ inputPath, outputDirectory, protectedRoot = process.cwd(), discardLocalChanges = false, yes = false, confirmReplace }) {
112
+ assert(typeof inputPath === "string", "Input SB3 path is required.");
113
+ assert(typeof outputDirectory === "string", "SB3 source output directory is required.");
114
+ const resolvedInputPath = path.resolve(inputPath);
115
+ const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);
116
+ const archive = unzipSync(new Uint8Array(await readFile(resolvedInputPath)));
117
+ const archiveEntries = Object.entries(archive);
118
+ assert(archiveEntries.length > 0, "SB3 archive is empty.");
119
+ for (const [entryName] of archiveEntries) validateArchiveEntryName(entryName);
120
+ const projectEntry = archive["project.json"];
121
+ assert(projectEntry, "SB3 archive does not contain project.json.");
122
+ let project;
123
+ let decision;
124
+ let rollbackCleanupWarning = null;
125
+ try {
126
+ project = JSON.parse(strFromU8(projectEntry));
127
+ } catch (error) {
128
+ throw new Error(`SB3 project.json is invalid JSON: ${errorMessage(error)}`, { cause: error });
129
+ }
130
+ assert(isObject(project), "SB3 project.json must contain a JSON object.");
131
+ const projectJson = project;
132
+ const extensionUrls = projectJson.extensionURLs ?? {};
133
+ assert(isObject(extensionUrls), "SB3 project.json extensionURLs must be an object when present.");
134
+ const existingExtensionSources = await readExistingExtensionSources(resolvedOutputDirectory);
135
+ const embeddedExtensions = [];
136
+ const decodedExtensionSources = [];
137
+ for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {
138
+ if (typeof extensionUrl !== "string" || !extensionUrl.startsWith("data:")) continue;
139
+ const sourcePath = extensionSourcePath(extensionId);
140
+ const decoded = decodeExtensionDataUrl(extensionUrl);
141
+ extensionUrls[extensionId] = `embedded-extension:${sourcePath}`;
142
+ const extension = {
143
+ id: extensionId,
144
+ path: sourcePath,
145
+ mediaType: decoded.mediaType,
146
+ parameters: decoded.parameters,
147
+ encoding: decoded.encoding
148
+ };
149
+ const existingSource = existingExtensionSources.get(`${extensionId}\u0000${sourcePath}`);
150
+ let existingApiManifestContents = null;
151
+ if (existingSource !== void 0) {
152
+ extension.source = structuredClone(existingSource);
153
+ validateManagedExtensionContents(extension, decoded.source);
154
+ if (extension.source.apiManifest) {
155
+ existingApiManifestContents = await readFile(path.join(resolvedOutputDirectory, extension.source.apiManifest.path));
156
+ validateManagedExtensionApiManifest(extension, existingApiManifestContents);
157
+ }
158
+ }
159
+ embeddedExtensions.push(extension);
160
+ decodedExtensionSources.push({
161
+ path: sourcePath,
162
+ source: decoded.source
163
+ });
164
+ if (existingApiManifestContents && extension.source?.apiManifest) decodedExtensionSources.push({
165
+ path: extension.source.apiManifest.path,
166
+ source: existingApiManifestContents
167
+ });
168
+ }
169
+ const outputParent = path.dirname(resolvedOutputDirectory);
170
+ await mkdir(outputParent, { recursive: true });
171
+ const temporaryDirectory = await mkdtemp(path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`));
172
+ try {
173
+ const assetsDirectory = path.join(temporaryDirectory, "assets");
174
+ await mkdir(assetsDirectory, { recursive: true });
175
+ await mkdir(path.join(temporaryDirectory, "extensions"), { recursive: true });
176
+ for (const [entryName, contents] of archiveEntries) {
177
+ if (entryName === "project.json" || entryName.endsWith("/")) continue;
178
+ const assetPath = path.resolve(assetsDirectory, entryName);
179
+ assert(assetPath.startsWith(`${assetsDirectory}${path.sep}`), `SB3 archive entry escapes the assets directory: ${JSON.stringify(entryName)}`);
180
+ await mkdir(path.dirname(assetPath), { recursive: true });
181
+ await writeFile(assetPath, contents);
182
+ }
183
+ for (const extension of decodedExtensionSources) await writeFile(path.join(temporaryDirectory, extension.path), extension.source);
184
+ const sourceManifest = {
185
+ formatVersion: 1,
186
+ project: "project.source.json",
187
+ embeddedExtensions: "embedded-extensions.json",
188
+ assetsDirectory: "assets",
189
+ archiveEntries: archiveEntries.map(([entryName]) => entryName)
190
+ };
191
+ await Promise.all([
192
+ writeFile(path.join(temporaryDirectory, "project.source.json"), `${JSON.stringify(projectJson, null, 2)}\n`),
193
+ writeFile(path.join(temporaryDirectory, "embedded-extensions.json"), `${JSON.stringify({
194
+ formatVersion: 1,
195
+ extensions: embeddedExtensions
196
+ }, null, 2)}\n`),
197
+ writeFile(path.join(temporaryDirectory, "sb3-source.json"), `${JSON.stringify(sourceManifest, null, 2)}\n`)
198
+ ]);
199
+ decision = await authorizeOutputReplacement({
200
+ candidateDirectory: temporaryDirectory,
201
+ confirmReplace,
202
+ discardLocalChanges,
203
+ outputDirectory: resolvedOutputDirectory,
204
+ yes
205
+ });
206
+ if (decision.action === "unchanged") await rm(temporaryDirectory, {
207
+ recursive: true,
208
+ force: true
209
+ });
210
+ else {
211
+ if (decision.action === "replace") await revalidateOutputReplacement({
212
+ candidateDirectory: temporaryDirectory,
213
+ decision,
214
+ discardLocalChanges,
215
+ outputDirectory: resolvedOutputDirectory
216
+ });
217
+ ({rollbackCleanupWarning} = await replaceDirectoryTransactionally(temporaryDirectory, resolvedOutputDirectory));
218
+ }
219
+ } catch (error) {
220
+ await rm(temporaryDirectory, {
221
+ recursive: true,
222
+ force: true
223
+ });
224
+ throw error;
225
+ }
226
+ return {
227
+ archiveEntryCount: archiveEntries.length,
228
+ assetCount: archiveEntries.filter(([entryName]) => entryName !== "project.json" && !entryName.endsWith("/")).length,
229
+ embeddedExtensionCount: embeddedExtensions.length,
230
+ changed: decision.action !== "unchanged",
231
+ differenceCounts: decision.comparison ? {
232
+ added: decision.comparison.differences.added.length,
233
+ modified: decision.comparison.differences.modified.length,
234
+ removed: decision.comparison.differences.removed.length
235
+ } : null,
236
+ inputPath: resolvedInputPath,
237
+ outputDirectory: resolvedOutputDirectory,
238
+ rollbackCleanupWarning
239
+ };
240
+ }
241
+ //#endregion
242
+ export { decodeExtensionDataUrl, importSb3 };
243
+
244
+ //# sourceMappingURL=import.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"import.js","names":[],"sources":["../src/import.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\nimport {strFromU8, unzipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateManagedExtensionContents} from './extension-dependencies';\nimport {\n assertNoInterruptedRollback,\n assertRecognizedOutputDirectory,\n compareDirectories,\n inspectGitOutputState,\n pathExists,\n replaceDirectoryTransactionally,\n validateOutputDirectoryPath,\n} from './output-safety';\nimport type {DirectoryComparison, GitOutputState} from './output-safety';\nimport {sourceFormatVersion} from './source';\nimport type {\n EmbeddedExtension,\n ExtensionEncoding,\n ExtensionSource,\n ProjectJson,\n UnknownRecord,\n} from './types';\n\nexport {validateOutputDirectoryPath} from './output-safety';\n\nexport interface DecodedExtensionDataUrl {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Buffer;\n}\n\nexport interface OutputReplacementContext {\n comparison: DirectoryComparison;\n discardLocalChanges: boolean;\n gitState: GitOutputState;\n outputDirectory: string;\n}\n\ninterface OutputReplacementDecision {\n action: 'create' | 'unchanged' | 'replace';\n comparison: DirectoryComparison | null;\n discardLocalChanges?: boolean;\n gitState: GitOutputState | null;\n outputDirectory?: string;\n}\n\nexport interface ImportSb3Options {\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges?: boolean;\n inputPath: string;\n outputDirectory: string;\n protectedRoot?: string;\n yes?: boolean;\n}\n\nexport interface ImportSb3Result {\n archiveEntryCount: number;\n assetCount: number;\n changed: boolean;\n differenceCounts: {added: number; modified: number; removed: number} | null;\n embeddedExtensionCount: number;\n inputPath: string;\n outputDirectory: string;\n rollbackCleanupWarning: string | null;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction summarizeGitChanges(gitState: GitOutputState): string {\n const entries = [\n ...gitState.statusEntries,\n ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`),\n ];\n const visibleEntries = entries.slice(0, 8).join(', ');\n const remainder = entries.length > 8 ? `, and ${entries.length - 8} more` : '';\n return `${visibleEntries}${remainder}`;\n}\n\nasync function authorizeOutputReplacement({\n candidateDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory,\n yes,\n}: {\n candidateDirectory: string;\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges: boolean;\n outputDirectory: string;\n yes: boolean;\n}): Promise<OutputReplacementDecision> {\n await assertNoInterruptedRollback(outputDirectory);\n if (!(await pathExists(outputDirectory))) {\n return {action: 'create', comparison: null, gitState: null};\n }\n\n await assertRecognizedOutputDirectory(outputDirectory, sourceFormatVersion);\n const comparison = await compareDirectories(outputDirectory, candidateDirectory);\n if (comparison.identical) {\n return {action: 'unchanged', comparison, gitState: null};\n }\n\n const gitState = await inspectGitOutputState(outputDirectory, comparison.existingFilePaths);\n assert(\n gitState.managed,\n `Existing output differs from the SB3 candidate but is not tracked by Git: ${outputDirectory}. ` +\n 'Import to a new output directory instead of replacing unrecoverable content.',\n );\n assert(\n gitState.clean || discardLocalChanges,\n `Existing output differs from the SB3 candidate and has uncommitted Git changes: ` +\n `${summarizeGitChanges(gitState)}. Commit or stash them first, or explicitly use ` +\n '--discard-local-changes.',\n );\n\n const context = {\n comparison,\n discardLocalChanges,\n gitState,\n outputDirectory,\n };\n if (yes) {\n return {action: 'replace', ...context};\n }\n assert(\n typeof confirmReplace === 'function',\n `Output directory already exists: ${outputDirectory}. ` +\n 'Refusing to replace differing content without interactive confirmation or --yes.',\n );\n assert(\n await confirmReplace(context),\n 'SB3 import cancelled; the existing output was not changed.',\n );\n return {action: 'replace', ...context};\n}\n\nasync function revalidateOutputReplacement({\n candidateDirectory,\n decision,\n discardLocalChanges,\n outputDirectory,\n}: {\n candidateDirectory: string;\n decision: OutputReplacementContext;\n discardLocalChanges: boolean;\n outputDirectory: string;\n}): Promise<void> {\n const latestComparison = await compareDirectories(outputDirectory, candidateDirectory);\n assert(\n latestComparison.existingFingerprint === decision.comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === decision.comparison.candidateFingerprint,\n 'Output or candidate content changed during SB3 import; refusing to replace it.',\n );\n const latestGitState = await inspectGitOutputState(\n outputDirectory,\n latestComparison.existingFilePaths,\n );\n assert(\n latestGitState.managed,\n 'Output stopped being Git-managed during SB3 import; refusing to replace it.',\n );\n assert(\n latestGitState.fingerprint === decision.gitState.fingerprint,\n 'Git state changed during SB3 import; refusing to replace the output.',\n );\n assert(\n latestGitState.clean || discardLocalChanges,\n 'Output gained uncommitted Git changes during SB3 import; refusing to replace it.',\n );\n}\n\nfunction extensionSourcePath(extensionId: string): string {\n assert(\n /^[A-Za-z0-9._-]+$/u.test(extensionId),\n `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`,\n );\n return `extensions/${extensionId}.js`;\n}\n\nasync function readExistingExtensionSources(\n outputDirectory: string,\n): Promise<Map<string, ExtensionSource>> {\n if (!(await pathExists(outputDirectory))) {\n return new Map();\n }\n\n const manifestPath = path.join(outputDirectory, 'embedded-extensions.json');\n if (!(await pathExists(manifestPath))) {\n return new Map();\n }\n\n let manifest: unknown;\n try {\n manifest = JSON.parse(await readFile(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(`Existing embedded extension manifest is not valid JSON: ${manifestPath}`, {\n cause: error,\n });\n }\n assert(\n isObject(manifest) && Array.isArray(manifest.extensions),\n `Existing embedded extension manifest is invalid: ${manifestPath}`,\n );\n\n const sources = new Map<string, ExtensionSource>();\n for (const extension of manifest.extensions as unknown[]) {\n if (\n !isObject(extension) ||\n typeof extension.id !== 'string' ||\n typeof extension.path !== 'string' ||\n extension.source === undefined\n ) {\n continue;\n }\n sources.set(`${extension.id}\\u0000${extension.path}`, extension.source as ExtensionSource);\n }\n return sources;\n}\n\nexport function decodeExtensionDataUrl(dataUrl: unknown): DecodedExtensionDataUrl {\n assert(\n typeof dataUrl === 'string' && dataUrl.startsWith('data:'),\n 'Embedded extension URL must be a data URL.',\n );\n const commaIndex = dataUrl.indexOf(',');\n assert(commaIndex >= 0, 'Embedded extension data URL has no payload separator.');\n\n const metadata = dataUrl.slice('data:'.length, commaIndex).split(';');\n const mediaType = metadata.shift() || 'text/plain';\n const base64Index = metadata.indexOf('base64');\n const encoding: ExtensionEncoding = base64Index >= 0 ? 'base64' : 'percent';\n if (base64Index >= 0) {\n metadata.splice(base64Index, 1);\n }\n\n const payload = dataUrl.slice(commaIndex + 1);\n let source: Buffer;\n if (encoding === 'base64') {\n assert(\n /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),\n 'Embedded extension data URL contains invalid base64.',\n );\n const unpaddedPayload = payload.replace(/=+$/u, '');\n assert(\n unpaddedPayload.length % 4 !== 1,\n 'Embedded extension data URL contains invalid base64.',\n );\n source = Buffer.from(\n unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, '='),\n 'base64',\n );\n } else {\n try {\n source = Buffer.from(decodeURIComponent(payload), 'utf8');\n } catch {\n throw new Error('Embedded extension data URL contains invalid percent encoding.');\n }\n }\n\n return {\n encoding,\n mediaType,\n parameters: metadata,\n source,\n };\n}\n\nexport async function importSb3({\n inputPath,\n outputDirectory,\n protectedRoot = process.cwd(),\n discardLocalChanges = false,\n yes = false,\n confirmReplace,\n}: ImportSb3Options): Promise<ImportSb3Result> {\n assert(typeof inputPath === 'string', 'Input SB3 path is required.');\n assert(typeof outputDirectory === 'string', 'SB3 source output directory is required.');\n const resolvedInputPath = path.resolve(inputPath);\n const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);\n\n const archive = unzipSync(new Uint8Array(await readFile(resolvedInputPath)));\n const archiveEntries = Object.entries(archive);\n assert(archiveEntries.length > 0, 'SB3 archive is empty.');\n for (const [entryName] of archiveEntries) {\n validateArchiveEntryName(entryName);\n }\n\n const projectEntry = archive['project.json'];\n assert(projectEntry, 'SB3 archive does not contain project.json.');\n\n let project: unknown;\n let decision: OutputReplacementDecision | undefined;\n let rollbackCleanupWarning: string | null = null;\n try {\n project = JSON.parse(strFromU8(projectEntry));\n } catch (error) {\n throw new Error(`SB3 project.json is invalid JSON: ${errorMessage(error)}`, {cause: error});\n }\n assert(isObject(project), 'SB3 project.json must contain a JSON object.');\n const projectJson: ProjectJson = project;\n\n const extensionUrls: unknown = projectJson.extensionURLs ?? {};\n assert(isObject(extensionUrls), 'SB3 project.json extensionURLs must be an object when present.');\n\n const existingExtensionSources = await readExistingExtensionSources(resolvedOutputDirectory);\n const embeddedExtensions: EmbeddedExtension[] = [];\n const decodedExtensionSources: {path: string; source: Buffer}[] = [];\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n if (typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:')) {\n continue;\n }\n const sourcePath = extensionSourcePath(extensionId);\n const decoded = decodeExtensionDataUrl(extensionUrl);\n extensionUrls[extensionId] = `embedded-extension:${sourcePath}`;\n const extension: EmbeddedExtension = {\n id: extensionId,\n path: sourcePath,\n mediaType: decoded.mediaType,\n parameters: decoded.parameters,\n encoding: decoded.encoding,\n };\n const existingSource = existingExtensionSources.get(`${extensionId}\\u0000${sourcePath}`);\n let existingApiManifestContents: Buffer | null = null;\n if (existingSource !== undefined) {\n extension.source = structuredClone(existingSource);\n validateManagedExtensionContents(extension, decoded.source);\n if (extension.source.apiManifest) {\n existingApiManifestContents = await readFile(\n path.join(resolvedOutputDirectory, extension.source.apiManifest.path),\n );\n validateManagedExtensionApiManifest(extension, existingApiManifestContents);\n }\n }\n embeddedExtensions.push(extension);\n decodedExtensionSources.push({path: sourcePath, source: decoded.source});\n if (existingApiManifestContents && extension.source?.apiManifest) {\n decodedExtensionSources.push({\n path: extension.source.apiManifest.path,\n source: existingApiManifestContents,\n });\n }\n }\n\n const outputParent = path.dirname(resolvedOutputDirectory);\n await mkdir(outputParent, {recursive: true});\n const temporaryDirectory = await mkdtemp(\n path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`),\n );\n\n try {\n const assetsDirectory = path.join(temporaryDirectory, 'assets');\n await mkdir(assetsDirectory, {recursive: true});\n await mkdir(path.join(temporaryDirectory, 'extensions'), {recursive: true});\n\n for (const [entryName, contents] of archiveEntries) {\n if (entryName === 'project.json' || entryName.endsWith('/')) {\n continue;\n }\n const assetPath = path.resolve(assetsDirectory, entryName);\n assert(\n assetPath.startsWith(`${assetsDirectory}${path.sep}`),\n `SB3 archive entry escapes the assets directory: ${JSON.stringify(entryName)}`,\n );\n await mkdir(path.dirname(assetPath), {recursive: true});\n await writeFile(assetPath, contents);\n }\n\n for (const extension of decodedExtensionSources) {\n await writeFile(path.join(temporaryDirectory, extension.path), extension.source);\n }\n\n const sourceManifest = {\n formatVersion: sourceFormatVersion,\n project: 'project.source.json',\n embeddedExtensions: 'embedded-extensions.json',\n assetsDirectory: 'assets',\n archiveEntries: archiveEntries.map(([entryName]) => entryName),\n };\n await Promise.all([\n writeFile(\n path.join(temporaryDirectory, 'project.source.json'),\n `${JSON.stringify(projectJson, null, 2)}\\n`,\n ),\n writeFile(\n path.join(temporaryDirectory, 'embedded-extensions.json'),\n `${JSON.stringify({formatVersion: sourceFormatVersion, extensions: embeddedExtensions}, null, 2)}\\n`,\n ),\n writeFile(\n path.join(temporaryDirectory, 'sb3-source.json'),\n `${JSON.stringify(sourceManifest, null, 2)}\\n`,\n ),\n ]);\n decision = await authorizeOutputReplacement({\n candidateDirectory: temporaryDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n yes,\n });\n if (decision.action === 'unchanged') {\n await rm(temporaryDirectory, {recursive: true, force: true});\n } else {\n if (decision.action === 'replace') {\n await revalidateOutputReplacement({\n candidateDirectory: temporaryDirectory,\n decision: decision as OutputReplacementContext,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n });\n }\n ({rollbackCleanupWarning} = await replaceDirectoryTransactionally(\n temporaryDirectory,\n resolvedOutputDirectory,\n ));\n }\n } catch (error) {\n await rm(temporaryDirectory, {recursive: true, force: true});\n throw error;\n }\n\n return {\n archiveEntryCount: archiveEntries.length,\n assetCount: archiveEntries.filter(\n ([entryName]) => entryName !== 'project.json' && !entryName.endsWith('/'),\n ).length,\n embeddedExtensionCount: embeddedExtensions.length,\n changed: decision.action !== 'unchanged',\n differenceCounts: decision.comparison\n ? {\n added: decision.comparison.differences.added.length,\n modified: decision.comparison.differences.modified.length,\n removed: decision.comparison.differences.removed.length,\n }\n : null,\n inputPath: resolvedInputPath,\n outputDirectory: resolvedOutputDirectory,\n rollbackCleanupWarning,\n };\n}\n"],"mappings":";;;;;;;;;;;AA2EA,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,oBAAoB,UAAkC;CAC7D,MAAM,UAAU,CACd,GAAG,SAAS,eACZ,GAAG,SA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D,IAAI,SAAS,WAAW,aACtB,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;OACtD;GACL,IAAI,SAAS,WAAW,WACtB,MAAM,4BAA4B;IAChC,oBAAoB;IACV;IACV;IACA,iBAAiB;GACnB,CAAC;GAEH,CAAC,CAAC,0BAA0B,MAAM,gCAChC,oBACA,uBACF;EACF;CACF,SAAS,OAAO;EACd,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;EAC3D,MAAM;CACR;CAEA,OAAO;EACL,mBAAmB,eAAe;EAClC,YAAY,eAAe,QACxB,CAAC,eAAe,cAAc,kBAAkB,CAAC,UAAU,SAAS,GAAG,CAC1E,CAAC,CAAC;EACF,wBAAwB,mBAAmB;EAC3C,SAAS,SAAS,WAAW;EAC7B,kBAAkB,SAAS,aACvB;GACE,OAAO,SAAS,WAAW,YAAY,MAAM;GAC7C,UAAU,SAAS,WAAW,YAAY,SAAS;GACnD,SAAS,SAAS,WAAW,YAAY,QAAQ;EACnD,IACA;EACJ,WAAW;EACX,iBAAiB;EACjB;CACF;AACF"}
@@ -0,0 +1,31 @@
1
+ export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionEncoding, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types';
2
+ export { assert } from './assert';
3
+ export { validateArchiveEntryName } from './archive';
4
+ export { buildSb3 } from './build';
5
+ export { packageName, packageVersion } from './constants';
6
+ export { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, validateExtensionSourceMetadata, validateManagedExtensionContents, } from './extension-dependencies';
7
+ export { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestFormatVersion, extensionApiManifestIntegrity, extensionApiManifestLocalPath, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, tryParseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest, } from './extension-api-manifest';
8
+ export { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions, } from './extension-bundle-configuration';
9
+ export { planBundledSb3Unbundle, unbundleSb3 } from './extension-bundle-archive';
10
+ export { buildExtensionBundles, createStaticExtensionBundle, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations, } from './extension-bundle';
11
+ export { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId, } from './extension-id-migration';
12
+ export { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions, } from './extension-sync';
13
+ export { decodeExtensionDataUrl, importSb3 } from './import';
14
+ export { compareDirectories, inspectGitOutputState, validateOutputDirectoryPath, } from './output-safety';
15
+ export { createDeterministicSb3, fixedZipTimestamp, sourceFormatVersion, validateSb3Source, } from './source';
16
+ export { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion, } from './project-asset-additions';
17
+ export { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate, } from './release-snapshot';
18
+ export { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from './turbowarp-clean-up';
19
+ export type { BuildSb3Options, WriteSb3ArchiveOptions, WriteSb3ArchiveResult } from './build';
20
+ export type { CliOptions } from './cli';
21
+ export type { ExtensionApiCompatibilityChange, ExtensionApiManifest, ExtensionApiManifestArgument, ExtensionApiManifestBlock, ExtensionApiManifestMenu, ExtensionApiManifestParseFailure, ExtensionApiManifestParseResult, ExtensionApiManifestParseSuccess, } from './extension-api-manifest';
22
+ export type { BuildExtensionBundlesResult, ExtensionBundleComponent, ExtensionBundleCounts, ExtensionBundlePlan, } from './extension-bundle';
23
+ export type { BundledSb3UnbundlePlan } from './extension-bundle-archive';
24
+ export type { ExtensionIdMigrationCounts, ExtensionIdReference, RewriteExtensionIdDocumentsResult, } from './extension-id-migration';
25
+ export type { ExtensionSyncConfirmContext, SyncExtensionsOptions, UpdateExtensionsOptions, } from './extension-sync';
26
+ export type { DecodedExtensionDataUrl, ImportSb3Options, ImportSb3Result, OutputReplacementContext, } from './import';
27
+ export type { DirectoryComparison, DirectoryDifferences, GitOutputState } from './output-safety';
28
+ export type { ProjectAssetAdditionsSummary } from './project-asset-additions';
29
+ export type { Sb3ReleaseSnapshotMetadata } from './release-snapshot';
30
+ export type { DeterministicSb3, InspectedSb3Source } from './source';
31
+ export type { TurboWarpCleanUpResult } from './turbowarp-clean-up';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ import { assert } from "./assert.js";
2
+ import { compareDirectories, inspectGitOutputState, validateOutputDirectoryPath } from "./output-safety.js";
3
+ import { validateArchiveEntryName } from "./archive.js";
4
+ import { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestFormatVersion, extensionApiManifestIntegrity, extensionApiManifestLocalPath, 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";
7
+ import { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion } from "./project-asset-additions.js";
8
+ import { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from "./turbowarp-clean-up.js";
9
+ import { createDeterministicSb3, fixedZipTimestamp, sourceFormatVersion, validateSb3Source } from "./source.js";
10
+ import { buildSb3 } from "./build.js";
11
+ import { packageName, packageVersion } from "./constants.js";
12
+ import { decodeExtensionDataUrl, importSb3 } from "./import.js";
13
+ import { planBundledSb3Unbundle, unbundleSb3 } from "./extension-bundle-archive.js";
14
+ import { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions } from "./extension-bundle-configuration.js";
15
+ import { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId } from "./extension-id-migration.js";
16
+ import { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
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, extensionApiManifestFormatVersion, extensionApiManifestIntegrity, extensionApiManifestLocalPath, 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 };
@@ -0,0 +1,13 @@
1
+ import { EmbeddedExtension } from './types';
2
+ export interface NpmExtensionSourceOptions {
3
+ allowVersionMismatch?: boolean;
4
+ maximumArtifactBytes: number;
5
+ maximumManifestBytes: number;
6
+ }
7
+ export interface NpmExtensionSourceResult {
8
+ apiManifestContents: Buffer | null;
9
+ contents: Buffer;
10
+ packageDirectory: string;
11
+ version: string;
12
+ }
13
+ export declare function readNpmExtensionSource(extension: EmbeddedExtension, sourceDirectory: string, { allowVersionMismatch, maximumArtifactBytes, maximumManifestBytes, }: NpmExtensionSourceOptions): Promise<NpmExtensionSourceResult>;
@@ -0,0 +1,63 @@
1
+ import { assert, errorMessage } from "./assert.js";
2
+ import { validateExtensionApiManifestSourceMetadata } from "./extension-api-manifest.js";
3
+ import { extensionHeaderId, validateExtensionSourceMetadata } from "./extension-dependencies.js";
4
+ import path from "node:path";
5
+ import { lstat, readFile, realpath } from "node:fs/promises";
6
+ //#region src/npm-extension-source.ts
7
+ function packageSegments(packageName) {
8
+ return packageName.startsWith("@") ? packageName.split("/") : [packageName];
9
+ }
10
+ async function findPackageDirectory(sourceDirectory, packageName) {
11
+ let current = path.resolve(sourceDirectory);
12
+ while (true) {
13
+ const candidate = path.join(current, "node_modules", ...packageSegments(packageName));
14
+ try {
15
+ await lstat(path.join(candidate, "package.json"));
16
+ return candidate;
17
+ } catch (error) {
18
+ const code = error?.code;
19
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
20
+ }
21
+ const parent = path.dirname(current);
22
+ if (parent === current) break;
23
+ current = parent;
24
+ }
25
+ throw new Error(`Installed npm package was not found for managed extension: ${packageName}. Run the project's package manager install command.`);
26
+ }
27
+ async function readPackageArtifact(packageDirectory, artifact, maximumBytes, description) {
28
+ const [resolvedPackageDirectory, resolvedArtifact] = await Promise.all([realpath(packageDirectory), realpath(path.join(packageDirectory, ...artifact.split("/")))]);
29
+ const relativeArtifact = path.relative(resolvedPackageDirectory, resolvedArtifact);
30
+ assert(relativeArtifact !== "" && relativeArtifact !== ".." && !relativeArtifact.startsWith(`..${path.sep}`) && !path.isAbsolute(relativeArtifact), `${description} resolves outside its npm package: ${artifact}`);
31
+ const stats = await lstat(resolvedArtifact);
32
+ assert(stats.isFile(), `${description} must be a regular file: ${artifact}`);
33
+ assert(stats.size <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);
34
+ return readFile(resolvedArtifact);
35
+ }
36
+ async function readNpmExtensionSource(extension, sourceDirectory, { allowVersionMismatch = false, maximumArtifactBytes, maximumManifestBytes }) {
37
+ const source = validateExtensionSourceMetadata(extension);
38
+ assert(source?.provider === "npm", `Extension is not managed by npm: ${extension.id}`);
39
+ const packageDirectory = await findPackageDirectory(sourceDirectory, source.package);
40
+ let packageManifest;
41
+ try {
42
+ packageManifest = JSON.parse(await readFile(path.join(packageDirectory, "package.json"), "utf8"));
43
+ } catch (error) {
44
+ throw new Error(`Invalid package.json for npm extension ${extension.id}: ${errorMessage(error)}`, { cause: error });
45
+ }
46
+ assert(packageManifest?.name === source.package, `npm package name mismatch for extension ${extension.id}: expected ${source.package}, got ${packageManifest?.name ?? "(missing)"}`);
47
+ assert(typeof packageManifest.version === "string" && /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(packageManifest.version), `npm package has an invalid semantic version for extension ${extension.id}: ${packageManifest?.version ?? "(missing)"}`);
48
+ if (!allowVersionMismatch) assert(packageManifest.version === source.version, `npm package version mismatch for extension ${extension.id}: expected ${source.version}, got ${packageManifest?.version ?? "(missing)"}`);
49
+ const contents = await readPackageArtifact(packageDirectory, source.artifact, maximumArtifactBytes, `npm extension artifact for ${extension.id}`);
50
+ const actualId = extensionHeaderId(contents);
51
+ assert(actualId === extension.id, `npm extension header ID mismatch for ${extension.id}: expected ${extension.id}, got ${actualId ?? "(missing)"}`);
52
+ const apiMetadata = validateExtensionApiManifestSourceMetadata(extension);
53
+ return {
54
+ apiManifestContents: apiMetadata ? await readPackageArtifact(packageDirectory, apiMetadata.artifact, maximumManifestBytes, `npm extension API manifest for ${extension.id}`) : null,
55
+ contents,
56
+ packageDirectory,
57
+ version: packageManifest.version
58
+ };
59
+ }
60
+ //#endregion
61
+ export { readNpmExtensionSource };
62
+
63
+ //# sourceMappingURL=npm-extension-source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"npm-extension-source.js","names":[],"sources":["../src/npm-extension-source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {lstat, readFile, realpath} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert, errorMessage} from './assert';\nimport {validateExtensionApiManifestSourceMetadata} from './extension-api-manifest';\nimport {extensionHeaderId, validateExtensionSourceMetadata} from './extension-dependencies';\nimport type {EmbeddedExtension} from './types';\n\nexport interface NpmExtensionSourceOptions {\n allowVersionMismatch?: boolean;\n maximumArtifactBytes: number;\n maximumManifestBytes: number;\n}\n\nexport interface NpmExtensionSourceResult {\n apiManifestContents: Buffer | null;\n contents: Buffer;\n packageDirectory: string;\n version: string;\n}\n\nfunction packageSegments(packageName: string): string[] {\n return packageName.startsWith('@') ? packageName.split('/') : [packageName];\n}\n\nasync function findPackageDirectory(sourceDirectory: string, packageName: string): Promise<string> {\n let current = path.resolve(sourceDirectory);\n while (true) {\n const candidate = path.join(current, 'node_modules', ...packageSegments(packageName));\n try {\n await lstat(path.join(candidate, 'package.json'));\n return candidate;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n throw new Error(\n `Installed npm package was not found for managed extension: ${packageName}. Run the project's package manager install command.`,\n );\n}\n\nasync function readPackageArtifact(\n packageDirectory: string,\n artifact: string,\n maximumBytes: number,\n description: string,\n): Promise<Buffer> {\n const [resolvedPackageDirectory, resolvedArtifact] = await Promise.all([\n realpath(packageDirectory),\n realpath(path.join(packageDirectory, ...artifact.split('/'))),\n ]);\n const relativeArtifact = path.relative(resolvedPackageDirectory, resolvedArtifact);\n assert(\n relativeArtifact !== '' &&\n relativeArtifact !== '..' &&\n !relativeArtifact.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativeArtifact),\n `${description} resolves outside its npm package: ${artifact}`,\n );\n const stats = await lstat(resolvedArtifact);\n assert(stats.isFile(), `${description} must be a regular file: ${artifact}`);\n assert(stats.size <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);\n return readFile(resolvedArtifact);\n}\n\nexport async function readNpmExtensionSource(\n extension: EmbeddedExtension,\n sourceDirectory: string,\n {\n allowVersionMismatch = false,\n maximumArtifactBytes,\n maximumManifestBytes,\n }: NpmExtensionSourceOptions,\n): Promise<NpmExtensionSourceResult> {\n const source = validateExtensionSourceMetadata(extension);\n assert(source?.provider === 'npm', `Extension is not managed by npm: ${extension.id}`);\n const packageDirectory = await findPackageDirectory(sourceDirectory, source.package);\n let packageManifest: {name?: unknown; version?: unknown};\n try {\n packageManifest = JSON.parse(\n await readFile(path.join(packageDirectory, 'package.json'), 'utf8'),\n );\n } catch (error) {\n throw new Error(\n `Invalid package.json for npm extension ${extension.id}: ${errorMessage(error)}`,\n {\n cause: error,\n },\n );\n }\n assert(\n packageManifest?.name === source.package,\n `npm package name mismatch for extension ${extension.id}: expected ${source.package}, got ${packageManifest?.name ?? '(missing)'}`,\n );\n assert(\n typeof packageManifest.version === 'string' &&\n /^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/u.test(\n packageManifest.version,\n ),\n `npm package has an invalid semantic version for extension ${extension.id}: ${packageManifest?.version ?? '(missing)'}`,\n );\n if (!allowVersionMismatch) {\n assert(\n packageManifest.version === source.version,\n `npm package version mismatch for extension ${extension.id}: expected ${source.version}, got ${packageManifest?.version ?? '(missing)'}`,\n );\n }\n const contents = await readPackageArtifact(\n packageDirectory,\n source.artifact,\n maximumArtifactBytes,\n `npm extension artifact for ${extension.id}`,\n );\n const actualId = extensionHeaderId(contents);\n assert(\n actualId === extension.id,\n `npm extension header ID mismatch for ${extension.id}: expected ${extension.id}, got ${actualId ?? '(missing)'}`,\n );\n const apiMetadata = validateExtensionApiManifestSourceMetadata(extension);\n const apiManifestContents = apiMetadata\n ? await readPackageArtifact(\n packageDirectory,\n apiMetadata.artifact,\n maximumManifestBytes,\n `npm extension API manifest for ${extension.id}`,\n )\n : null;\n return {\n apiManifestContents,\n contents,\n packageDirectory,\n version: packageManifest.version as string,\n };\n}\n"],"mappings":";;;;;;AAuBA,SAAS,gBAAgB,aAA+B;CACtD,OAAO,YAAY,WAAW,GAAG,IAAI,YAAY,MAAM,GAAG,IAAI,CAAC,WAAW;AAC5E;AAEA,eAAe,qBAAqB,iBAAyB,aAAsC;CACjG,IAAI,UAAU,KAAK,QAAQ,eAAe;CAC1C,OAAO,MAAM;EACX,MAAM,YAAY,KAAK,KAAK,SAAS,gBAAgB,GAAG,gBAAgB,WAAW,CAAC;EACpF,IAAI;GACF,MAAM,MAAM,KAAK,KAAK,WAAW,cAAc,CAAC;GAChD,OAAO;EACT,SAAS,OAAO;GACd,MAAM,OAAQ,OAAwC;GACtD,IAAI,SAAS,YAAY,SAAS,WAAW,MAAM;EACrD;EACA,MAAM,SAAS,KAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SAAS;EACxB,UAAU;CACZ;CACA,MAAM,IAAI,MACR,8DAA8D,YAAY,qDAC5E;AACF;AAEA,eAAe,oBACb,kBACA,UACA,cACA,aACiB;CACjB,MAAM,CAAC,0BAA0B,oBAAoB,MAAM,QAAQ,IAAI,CACrE,SAAS,gBAAgB,GACzB,SAAS,KAAK,KAAK,kBAAkB,GAAG,SAAS,MAAM,GAAG,CAAC,CAAC,CAC9D,CAAC;CACD,MAAM,mB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AAkB,QAAQ;CAC3C,OACE,aAAa,UAAU,IACvB,wCAAwC,UAAU,GAAG,aAAa,UAAU,GAAG,QAAQ,YAAY,aACrG;CACA,MAAM,cAAc,2CAA2C,SAAS;CASxE,OAAO;EACL,qBAT0B,cACxB,MAAM,oBACJ,kBACA,YAAY,UACZ,sBACA,kCAAkC,UAAU,IAC9C,IACA;EAGF;EACA;EACA,SAAS,gBAAgB;CAC3B;AACF"}
@@ -0,0 +1,29 @@
1
+ export interface DirectoryDifferences {
2
+ added: string[];
3
+ modified: string[];
4
+ removed: string[];
5
+ }
6
+ export interface DirectoryComparison {
7
+ candidateFingerprint: string;
8
+ differences: DirectoryDifferences;
9
+ existingFilePaths: string[];
10
+ existingFingerprint: string;
11
+ identical: boolean;
12
+ }
13
+ export interface GitOutputState {
14
+ clean: boolean;
15
+ fingerprint: string;
16
+ managed: boolean;
17
+ repositoryRoot: string | null;
18
+ statusEntries: string[];
19
+ untrackedContent: string[];
20
+ }
21
+ export declare function pathExists(targetPath: string): Promise<boolean>;
22
+ export declare function validateOutputDirectoryPath(outputDirectory: string, protectedRoot: string): string;
23
+ export declare function assertRecognizedOutputDirectory(outputDirectory: string, sourceFormatVersion: number): Promise<void>;
24
+ export declare function compareDirectories(existingDirectory: string, candidateDirectory: string): Promise<DirectoryComparison>;
25
+ export declare function inspectGitOutputState(outputDirectory: string, existingFilePaths: string[]): Promise<GitOutputState>;
26
+ export declare function assertNoInterruptedRollback(outputDirectory: string): Promise<void>;
27
+ export declare function replaceDirectoryTransactionally(temporaryDirectory: string, outputDirectory: string): Promise<{
28
+ rollbackCleanupWarning: string | null;
29
+ }>;