generated from MetaMask/metamask-module-template
-
Notifications
You must be signed in to change notification settings - Fork 7
build: Bundle vats with vite #763
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
grypez
wants to merge
10
commits into
main
Choose a base branch
from
grypez/bundle-with-vite
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+640
−155
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
d3bf48c
build: Support bundling with vite
grypez b674425
build: Remove @endo/import-bundle support
grypez 7bfa20d
respin yarn
grypez 94482c2
fix test mock
grypez eccd27f
Apply some suggestions from code review
grypez ebbfee6
address remaining review comments
grypez bf74145
small fixes
grypez 7e46603
add isVatBundle to index test
grypez 84cebfa
build: fix bundle import scrubber (#772)
grypez cc26d68
test: reproduce bugbot claims
grypez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import type { Plugin, RenderedModule } from 'rollup'; | ||
|
|
||
| export type BundleMetadata = { | ||
| exports: string[]; | ||
| modules: Record< | ||
| string, | ||
| { renderedExports: string[]; removedExports: string[] } | ||
| >; | ||
| }; | ||
|
|
||
| /** | ||
| * Rollup plugin that captures export metadata from the bundle. | ||
| * | ||
| * Uses the `generateBundle` hook to extract the exports array and | ||
| * per-module metadata (renderedExports and removedExports) from the | ||
| * entry chunk. | ||
| * | ||
| * @returns A plugin with an additional `getMetadata()` method. | ||
| */ | ||
| export function exportMetadataPlugin(): Plugin & { | ||
| getMetadata: () => BundleMetadata; | ||
| } { | ||
| const metadata: BundleMetadata = { exports: [], modules: {} }; | ||
|
|
||
| return { | ||
| name: 'export-metadata', | ||
| generateBundle(_, bundle) { | ||
| for (const chunk of Object.values(bundle)) { | ||
| if (chunk.type === 'chunk' && chunk.isEntry) { | ||
| const outputChunk = chunk; | ||
| metadata.exports = outputChunk.exports; | ||
| metadata.modules = Object.fromEntries( | ||
| Object.entries(outputChunk.modules).map( | ||
| ([id, info]: [string, RenderedModule]) => [ | ||
| id, | ||
| { | ||
| renderedExports: info.renderedExports, | ||
| removedExports: info.removedExports, | ||
| }, | ||
| ], | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
| }, | ||
| getMetadata: () => metadata, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
|
|
||
| import { stripCommentsPlugin } from './strip-comments-plugin.ts'; | ||
|
|
||
| describe('stripCommentsPlugin', () => { | ||
| const plugin = stripCommentsPlugin(); | ||
| const renderChunk = plugin.renderChunk as (code: string) => string | null; | ||
|
|
||
| it.each([ | ||
| [ | ||
| 'single-line comment', | ||
| 'const x = 1; // comment\nconst y = 2;', | ||
| 'const x = 1; \nconst y = 2;', | ||
| ], | ||
| [ | ||
| 'multi-line comment', | ||
| 'const x = 1; /* comment */ const y = 2;', | ||
| 'const x = 1; const y = 2;', | ||
| ], | ||
| [ | ||
| 'multiple comments', | ||
| '/* a */ const x = 1; // b\n/* c */', | ||
| ' const x = 1; \n', | ||
| ], | ||
| [ | ||
| 'comment containing import()', | ||
| 'const x = 1; // import("module")\nconst y = 2;', | ||
| 'const x = 1; \nconst y = 2;', | ||
| ], | ||
| [ | ||
| 'comment with string content preserved', | ||
| 'const x = "// in string"; // real comment', | ||
| 'const x = "// in string"; ', | ||
| ], | ||
| ['code that is only a comment', '// just a comment', ''], | ||
| ])('removes %s', (_name, code, expected) => { | ||
| expect(renderChunk(code)).toBe(expected); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ['string with // pattern', 'const x = "// not a comment";'], | ||
| ['string with /* */ pattern', 'const x = "/* not a comment */";'], | ||
| ['regex literal like //', 'const re = /\\/\\//;'], | ||
| ['template literal with // pattern', 'const x = `// not a comment`;'], | ||
| ['nested quotes in string', 'const x = "a \\"// not comment\\" b";'], | ||
| ['no comments', 'const x = 1;'], | ||
| ['empty code', ''], | ||
| ])('returns null for %s', (_name, code) => { | ||
| expect(renderChunk(code)).toBeNull(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import type { Comment } from 'acorn'; | ||
| import { parse } from 'acorn'; | ||
| import type { Plugin } from 'rollup'; | ||
|
|
||
| /** | ||
| * Rollup plugin that strips comments from bundled code using AST parsing. | ||
| * | ||
| * SES rejects code containing `import(` patterns, even when they appear | ||
| * in comments. This plugin uses Acorn to definitively identify comment nodes | ||
| * and removes them to avoid triggering that detection. | ||
| * | ||
| * Uses the `renderChunk` hook to process the final output. | ||
| * | ||
| * @returns A Rollup plugin. | ||
| */ | ||
| export function stripCommentsPlugin(): Plugin { | ||
| return { | ||
| name: 'strip-comments', | ||
| renderChunk(code) { | ||
| const comments: Comment[] = []; | ||
|
|
||
| parse(code, { | ||
| ecmaVersion: 'latest', | ||
| sourceType: 'module', | ||
| onComment: comments, | ||
| }); | ||
|
|
||
| if (comments.length === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| // Build result by copying non-comment ranges. | ||
| // Comments are sorted by position since acorn parses linearly. | ||
| let result = ''; | ||
| let position = 0; | ||
|
|
||
| for (const comment of comments) { | ||
| result += code.slice(position, comment.start); | ||
| position = comment.end; | ||
| } | ||
|
|
||
| result += code.slice(position); | ||
| return result; | ||
| }, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import type { VatBundle } from '@metamask/kernel-utils'; | ||
| import { build } from 'vite'; | ||
| import type { Rollup, PluginOption } from 'vite'; | ||
|
|
||
| import { exportMetadataPlugin } from './export-metadata-plugin.ts'; | ||
| import { stripCommentsPlugin } from './strip-comments-plugin.ts'; | ||
|
|
||
| export type { VatBundle }; | ||
|
|
||
| /** | ||
| * Bundle a vat source file using vite. | ||
| * | ||
| * Produces an IIFE bundle that assigns exports to a `__vatExports__` global, | ||
| * along with metadata about the bundle's exports and modules. | ||
| * | ||
| * @param sourcePath - Absolute path to the vat entry point. | ||
| * @returns The bundle object containing code and metadata. | ||
| */ | ||
| export async function bundleVat(sourcePath: string): Promise<VatBundle> { | ||
| const metadataPlugin = exportMetadataPlugin(); | ||
|
|
||
| const result = await build({ | ||
| configFile: false, | ||
| logLevel: 'silent', | ||
| build: { | ||
| write: false, | ||
| lib: { | ||
| entry: sourcePath, | ||
| formats: ['iife'], | ||
| name: '__vatExports__', | ||
| }, | ||
| rollupOptions: { | ||
| output: { | ||
| exports: 'named', | ||
| inlineDynamicImports: true, | ||
| }, | ||
| plugins: [ | ||
| stripCommentsPlugin() as unknown as PluginOption, | ||
| metadataPlugin as unknown as PluginOption, | ||
| ], | ||
| }, | ||
| minify: false, | ||
| }, | ||
| }); | ||
|
|
||
| const output = Array.isArray(result) ? result[0] : result; | ||
| const chunk = (output as Rollup.RollupOutput).output.find( | ||
| (item): item is Rollup.OutputChunk => item.type === 'chunk' && item.isEntry, | ||
| ); | ||
|
|
||
| if (!chunk) { | ||
| throw new Error(`Failed to produce bundle for ${sourcePath}`); | ||
| } | ||
|
|
||
| return { | ||
| moduleFormat: 'iife', | ||
| code: chunk.code, | ||
| ...metadataPlugin.getMetadata(), | ||
| }; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wrong sourceType for parsing IIFE bundle output
Low Severity
The
stripCommentsPluginusessourceType: 'module'to parse vite's IIFE output, but IIFE bundles are scripts, not modules. Module parsing implies strict mode, which rejects certain legacy JavaScript patterns (octal literals,withstatements, etc.). If bundled dependencies contain non-strict-mode code that wasn't transpiled,parse()throws a SyntaxError, preventing comment stripping and causing the build to fail unexpectedly.