Skip to content

Commit

Permalink
Add script to inline and strip Prism
Browse files Browse the repository at this point in the history
Related-to: GH-58.
Closes GH-61.

Co-authored-by: Andrey Okonetchnikov <andrey@okonet.dev>
  • Loading branch information
wooorm and okonet committed May 12, 2022
1 parent c5744cb commit 3e09ea1
Show file tree
Hide file tree
Showing 7 changed files with 2,666 additions and 73 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -3,4 +3,5 @@ node_modules/
*.d.ts
*.log
.DS_Store
package-lock.json
yarn.lock
1 change: 0 additions & 1 deletion .npmrc

This file was deleted.

68 changes: 2 additions & 66 deletions lib/core.js
Expand Up @@ -32,46 +32,11 @@
* @property {Languages} languages
*/

/* eslint-disable no-undef */
// Don’t allow Prism to run on page load in browser or to start messaging from
// workers.
/* c8 ignore next 15 */
/** @type {typeof globalThis} */
const ctx =
typeof globalThis === 'object'
? globalThis
: // @ts-expect-error
typeof self === 'object'
? // @ts-expect-error
self
: // @ts-expect-error
typeof window === 'object'
? // @ts-expect-error
window
: typeof global === 'object'
? global
: {}
/* eslint-enable no-undef */

const restore = capture()

/* c8 ignore next 5 */
ctx.Prism = ctx.Prism || {}
ctx.Prism.manual = true
ctx.Prism.disableWorkerMessageHandler = true

/* eslint-disable import/first */

// Load all stuff in `prism.js` itself, except for `prism-file-highlight.js`.
// The wrapped non-leaky grammars are loaded instead of Prism’s originals.
import {h} from 'hastscript'
import {parseEntities} from 'parse-entities'
// @ts-expect-error: untyped.
import Prism from 'prismjs/components/prism-core.js'

/* eslint-enable import/first */

restore()
import {Prism} from './prism-core.js'

const own = {}.hasOwnProperty

Expand Down Expand Up @@ -137,6 +102,7 @@ function highlight(value, language) {

return {
type: 'root',
// @ts-expect-error: we hacked Prism to accept and return the things we want.
children: Prism.highlight.call(refractor, value, grammar, name)
}
}
Expand Down Expand Up @@ -317,33 +283,3 @@ function attributes(attrs) {

return attrs
}

/**
* @returns {() => void}
*/
function capture() {
/** @type {boolean|undefined} */
let defined = 'Prism' in ctx
/* c8 ignore next */
let current = defined ? ctx.Prism : undefined

return restore

/**
* @returns {void}
*/
function restore() {
/* istanbul ignore else - Clean leaks after Prism. */
if (defined) {
// @ts-expect-error: hush.
ctx.Prism = current
/* c8 ignore next 4 */
} else {
// @ts-expect-error: hush.
delete ctx.Prism
}

defined = undefined
current = undefined
}
}

0 comments on commit 3e09ea1

Please sign in to comment.