-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
fix: fix error with <Prism /> component in Cloudflare Workers
#15723
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
Merged
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
9e180c5
fix: fix error with `<Prism />` component in Cloudflare Workers
rururux 8b7157c
add vite as a devDependency
rururux 0a5445d
omg
rururux bf6b547
fix knip error
rururux d57df04
try replacing all static imports of prism with dynamic imports
rururux fe8ec4f
remove unnecessary files
rururux da6244c
oops
rururux 86564b3
add explanatory comment
rururux 9e098d4
Merge branch 'main' into v6-cf-prism
rururux e334379
Merge branch 'main' into v6-cf-prism
rururux 8efd4b2
add `loadChainer` and verify that the language data is loading correctly
rururux 79d01a3
change to use static import and add ``@astro/prism` detection logic t…
rururux 3b1a04a
load prism language data files from a virtual module
rururux 37b971f
remove vite from astro-prism's dependencies
rururux 68f5b01
Merge branch 'main' into v6-cf-prism
rururux df376c0
Merge branch 'main' into v6-cf-prism
rururux 368adda
Merge branch 'main' into v6-cf-prism
rururux 782794c
update test
rururux 8994f97
fix type error
rururux eabe7ed
Merge branch 'main' into v6-cf-prism
rururux d187c79
improve stability when multiple `<Prism />` components are used
rururux 946c307
Merge branch 'main' into v6-cf-prism
rururux f63e1cf
update `tsconfig.build.json`
rururux ea86b2b
fix knip lint
rururux 1e1d716
format
rururux 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| '@astrojs/markdoc': patch | ||
| '@astrojs/markdown-remark': patch | ||
| --- | ||
|
|
||
| Updates internal type usage from `@astrojs/prism`. |
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,6 @@ | ||
| --- | ||
| '@astrojs/prism': patch | ||
| '@astrojs/cloudflare': patch | ||
| --- | ||
|
|
||
| Fixes an issue where the `<Prism />` component failed to work in Cloudflare Workers. |
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,5 @@ | ||
| import prismLoadLanguages from 'prismjs/components/index.js'; | ||
|
|
||
| export async function loadLanguages(languages: string | string[]) { | ||
| return prismLoadLanguages(languages); | ||
| } |
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,99 @@ | ||
| // This implementation was based from: https://github.com/PrismJS/prism/blob/76dde18a575831c91491895193f56081ac08b0c5/components/index.js | ||
| import Prism from 'prismjs'; | ||
| import components from 'prismjs/components.js'; | ||
| import getLoader, { type LoadChainer } from 'prismjs/dependencies.js'; | ||
| import { bundledLanguages } from 'virtual:astro-cloudflare:prism'; | ||
|
|
||
| // This `loadChainer` is required when working with Promises in Prism's loader. | ||
| // ref: https://github.com/PrismJS/prism/blob/76dde18a575831c91491895193f56081ac08b0c5/dependencies.js#L346-L360 | ||
| const loadChainer: LoadChainer<Promise<void>> = { | ||
| series: async (before, after) => { | ||
| await before; | ||
| await after(); | ||
| }, | ||
| parallel: async (values) => { | ||
| await Promise.all(values); | ||
| }, | ||
| }; | ||
|
|
||
| // Since Prism language files are written assuming the Prism instance is defined | ||
| // as a global variable, we will temporarily set the Prism instance globally. | ||
| // As loadLanguages can be called asynchronously multiple times, there is a risk | ||
| // that globalThis.Prism may be accessed again after cleanup, even when it appears | ||
| // to be no longer needed after a Promise resolves, potentially causing a | ||
| // `Prism is not defined` error. | ||
| // To avoid this, we track the number of active references and only perform cleanup | ||
| // when the count returns to zero. | ||
| let prismRefCount = 0; | ||
|
|
||
| const prismRefCounter = { | ||
| increment: () => { | ||
| if (prismRefCount === 0) { | ||
| globalThis.Prism = Prism; | ||
| } | ||
|
|
||
| prismRefCount += 1; | ||
| }, | ||
| decrement: () => { | ||
| prismRefCount -= 1; | ||
|
|
||
| if (prismRefCount === 0) { | ||
| // @ts-expect-error globalThis type | ||
| delete globalThis.Prism; | ||
| } | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
| * The set of all languages which have been loaded using the below function. | ||
| * | ||
| * @type {Set<string>} | ||
| */ | ||
| const loadedLanguages = new Set<string>(); | ||
|
|
||
| /** | ||
| * Loads the given languages and adds them to the current Prism instance. | ||
| * | ||
| * If no languages are provided, __all__ Prism languages will be loaded. | ||
| * | ||
| * @param {string|string[]} [languages] | ||
| * @returns {Promise<void>} | ||
| */ | ||
| export async function loadLanguages(languages: string | string[]) { | ||
| prismRefCounter.increment(); | ||
|
|
||
| if (languages === undefined) { | ||
| languages = Object.keys(components.languages).filter((l) => l !== 'meta'); | ||
| } else if (!Array.isArray(languages)) { | ||
| languages = [languages]; | ||
| } | ||
|
|
||
| // the user might have loaded languages via some other way or used `prism.js` which already includes some | ||
| // we don't need to validate the ids because `getLoader` will ignore invalid ones | ||
| const loaded = [...loadedLanguages, ...Object.keys(Prism.languages)]; | ||
|
|
||
| await getLoader(components, languages, loaded).load(async (lang: string) => { | ||
| if (!(lang in components.languages)) { | ||
| if (!loadLanguages.silent) { | ||
| console.warn('Language does not exist: ' + lang); | ||
|
ematipico marked this conversation as resolved.
|
||
| } | ||
| return; | ||
| } | ||
|
|
||
| // remove from Prism | ||
| delete Prism.languages[lang]; | ||
|
|
||
| if (Object.hasOwn(bundledLanguages, lang)) { | ||
| await bundledLanguages[lang](); | ||
| } | ||
|
|
||
| loadedLanguages.add(lang); | ||
| }, loadChainer); | ||
|
|
||
| prismRefCounter.decrement(); | ||
| } | ||
|
|
||
| /** | ||
| * Set this to `true` to prevent all warning messages `loadLanguages` logs. | ||
| */ | ||
| loadLanguages.silent = false; | ||
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 |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| { | ||
| "extends": "../../configs/tsconfig.build.json" | ||
| "extends": "../../configs/tsconfig.build.json", | ||
| "include": ["./src", "./virtual.d.ts"] | ||
| } |
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,3 @@ | ||
| declare module 'virtual:astro-cloudflare:prism' { | ||
| export const bundledLanguages: Record<string, () => Promise<void>>; | ||
| } |
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,63 @@ | ||
| import { fileURLToPath } from 'node:url'; | ||
| import type { Plugin } from 'vite'; | ||
| import components from 'prismjs/components.js'; | ||
|
|
||
| const MODULE_ID = 'virtual:astro-cloudflare:prism'; | ||
| const RESOLVED_MODULE_ID = '\0' + MODULE_ID; | ||
|
|
||
| const languages = Object.keys(components.languages).filter((l) => l !== 'meta'); | ||
|
|
||
| export default function cfPrismPlugin(): Plugin { | ||
| return { | ||
| name: '@astrojs/cloudflare:prism', | ||
| configEnvironment(environmentName) { | ||
| if (environmentName === 'ssr') { | ||
| return { | ||
| // Because this virtual module adds a large number of dynamic import statements, | ||
| // Vite’s logs will consequently display the message “new dependencies optimized” for all languages. | ||
| // To avoid this, we explicitly specify that the module should be optimized in advance. | ||
| optimizeDeps: { | ||
| include: ['prismjs/components/prism-*.js'], | ||
| }, | ||
| }; | ||
| } | ||
| }, | ||
| resolveId: { | ||
| filter: { | ||
| id: new RegExp(`^${MODULE_ID}$`), | ||
| }, | ||
| handler() { | ||
| return RESOLVED_MODULE_ID; | ||
| }, | ||
| }, | ||
| load: { | ||
| filter: { | ||
| id: new RegExp(`^${RESOLVED_MODULE_ID}$`), | ||
| }, | ||
| async handler() { | ||
| const importerPath = fileURLToPath(import.meta.url); | ||
|
|
||
| const resolvedModules = await Promise.all( | ||
| languages.map(async (lang) => { | ||
| const resolvedId = await this.resolve( | ||
| `prismjs/components/prism-${lang}.js`, | ||
| importerPath, | ||
| ); | ||
|
|
||
| return { resolvedId: resolvedId?.id, lang }; | ||
| }), | ||
| ); | ||
| const prismBundledLanguages = resolvedModules | ||
| .filter(({ resolvedId }) => resolvedId !== undefined) | ||
| .map( | ||
| ({ resolvedId, lang }) => | ||
| `${JSON.stringify(lang)}: () => import(${JSON.stringify(resolvedId)})`, | ||
| ); | ||
|
|
||
| return ` | ||
| export const bundledLanguages = { ${prismBundledLanguages.join(',')} }; | ||
| `; | ||
| }, | ||
| }, | ||
| }; | ||
| } |
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.
how does this work? What causes this to be loaded?
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.
This is due to this feature.
In PR #15565 as well, a similar approach was taken to address an issue that only occurs in the workerd environment.
https://developers.cloudflare.com/workers/wrangler/bundling/#conditional-exports