file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
src/root.client.js
JavaScript
import {Suspense} from 'react' export function Root(props) { const {response} = props return ( <Suspense fallback={null}> <Content /> </Suspense> ) function Content() { return response.readRoot() } }
wooorm/server-components-mdx-demo
123
React server components + MDX
JavaScript
wooorm
Titus
complex-types.d.ts
TypeScript
export type Components = import('mdx/types').MDXComponents /** * Props passed to the `MdxContent` component. * Could be anything. * The `components` prop is special: it defines what to use for components * inside the content. */ export type MdxContentProps = import('mdx/types').MDXProps /** * A function component which renders the MDX content using a JSX implementation. * * @param props * Props passed to the `MdxContent` component. * Could be anything. * The `components` prop is special: it defines what to use for components * inside the content. * @returns * A JSX element. * The meaning of this may depend on the project configuration. * As in, it could be a React, Preact, or Vue element. */ export type MdxContent = import('mdx/types').MDXContent export type MdxModule = import('mdx/types').MDXModule
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
esbuild.js
JavaScript
export {esbuild as default} from './lib/integration/esbuild.js'
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
esm-loader.js
JavaScript
import {createLoader} from './lib/integration/node.js' const {load, getFormat, transformSource} = createLoader() export {load, getFormat, transformSource} export {createLoader} from './lib/integration/node.js'
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
index.js
JavaScript
/// <reference types="./registry" /> export {createProcessor} from './lib/core.js' export {compile, compileSync} from './lib/compile.js' export {evaluate, evaluateSync} from './lib/evaluate.js' export {run, runSync} from './lib/run.js' export {nodeTypes} from './lib/node-types.js'
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/compile.js
JavaScript
/** * @typedef {import('vfile').VFileCompatible} VFileCompatible * @typedef {import('vfile').VFile} VFile * @typedef {import('./core.js').PluginOptions} PluginOptions * @typedef {import('./core.js').BaseProcessorOptions} BaseProcessorOptions * @typedef {Omit<BaseProcessorOptions, 'format'>} CoreProcessorOptions * * @typedef ExtraOptions * @property {'detect'|'mdx'|'md'} [format='detect'] Format of `file` * * @typedef {CoreProcessorOptions & PluginOptions & ExtraOptions} CompileOptions */ import {createProcessor} from './core.js' import {resolveFileAndOptions} from './util/resolve-file-and-options.js' /** * Compile MDX to JS. * * @param {VFileCompatible} vfileCompatible MDX document to parse (`string`, `Buffer`, `vfile`, anything that can be given to `vfile`) * @param {CompileOptions} [compileOptions] * @return {Promise<VFile>} */ export function compile(vfileCompatible, compileOptions) { const {file, options} = resolveFileAndOptions(vfileCompatible, compileOptions) return createProcessor(options).process(file) } /** * Synchronously compile MDX to JS. * * @param {VFileCompatible} vfileCompatible MDX document to parse (`string`, `Buffer`, `vfile`, anything that can be given to `vfile`) * @param {CompileOptions} [compileOptions] * @return {VFile} */ export function compileSync(vfileCompatible, compileOptions) { const {file, options} = resolveFileAndOptions(vfileCompatible, compileOptions) return createProcessor(options).processSync(file) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/condition.browser.js
JavaScript
export const development = false
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/condition.js
JavaScript
import process from 'node:process' export const development = process.env.NODE_ENV === 'development'
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/core.js
JavaScript
/** * @typedef {import('unified').Processor} Processor * @typedef {import('unified').PluggableList} PluggableList * @typedef {import('remark-rehype').Options} RemarkRehypeOptions * @typedef {import('./plugin/recma-document.js').RecmaDocumentOptions} RecmaDocumentOptions * @typedef {import('./plugin/recma-stringify.js').RecmaStringifyOptions} RecmaStringifyOptions * @typedef {import('./plugin/recma-jsx-rewrite.js').RecmaJsxRewriteOptions} RecmaJsxRewriteOptions * * @typedef BaseProcessorOptions * @property {boolean} [jsx=false] Whether to keep JSX * @property {'mdx'|'md'} [format='mdx'] Format of the files to be processed * @property {'program'|'function-body'} [outputFormat='program'] Whether to compile to a whole program or a function body. * @property {Array<string>} [mdExtensions] Extensions (with `.`) for markdown * @property {Array<string>} [mdxExtensions] Extensions (with `.`) for MDX * @property {PluggableList} [recmaPlugins] List of recma (esast, JavaScript) plugins * @property {PluggableList} [remarkPlugins] List of remark (mdast, markdown) plugins * @property {PluggableList} [rehypePlugins] List of rehype (hast, HTML) plugins * @property {RemarkRehypeOptions} [remarkRehypeOptions] Options to pass through to `remark-rehype`. * * @typedef {Omit<RecmaDocumentOptions & RecmaStringifyOptions & RecmaJsxRewriteOptions, 'outputFormat'>} PluginOptions * @typedef {BaseProcessorOptions & PluginOptions} ProcessorOptions */ import {unified} from 'unified' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import {recmaJsxBuild} from './plugin/recma-jsx-build.js' import {recmaDocument} from './plugin/recma-document.js' import {recmaJsxRewrite} from './plugin/recma-jsx-rewrite.js' import {recmaStringify} from './plugin/recma-stringify.js' import {rehypeRecma} from './plugin/rehype-recma.js' import {rehypeRemoveRaw} from './plugin/rehype-remove-raw.js' import {remarkMarkAndUnravel} from './plugin/remark-mark-and-unravel.js' import {remarkMdx} from './plugin/remark-mdx.js' import {nodeTypes} from './node-types.js' import {development as defaultDevelopment} from './condition.js' /** * Pipeline to: * * 1. Parse MDX (serialized markdown with embedded JSX, ESM, and expressions) * 2. Transform through remark (mdast), rehype (hast), and recma (esast) * 3. Serialize as JavaScript * * @param {ProcessorOptions} [options] * @return {Processor} */ export function createProcessor(options = {}) { const { development = defaultDevelopment, jsx, format, outputFormat, providerImportSource, recmaPlugins, rehypePlugins, remarkPlugins, remarkRehypeOptions = {}, SourceMapGenerator, ...rest } = options // @ts-expect-error runtime. if (format === 'detect') { throw new Error( "Incorrect `format: 'detect'`: `createProcessor` can support either `md` or `mdx`; it does not support detecting the format" ) } const pipeline = unified().use(remarkParse) if (format !== 'md') { pipeline.use(remarkMdx) } pipeline .use(remarkMarkAndUnravel) .use(remarkPlugins || []) .use(remarkRehype, { ...remarkRehypeOptions, allowDangerousHtml: true, /* c8 ignore next */ passThrough: [...(remarkRehypeOptions.passThrough || []), ...nodeTypes] }) .use(rehypePlugins || []) if (format === 'md') { pipeline.use(rehypeRemoveRaw) } pipeline .use(rehypeRecma) .use(recmaDocument, {...rest, outputFormat}) .use(recmaJsxRewrite, {development, providerImportSource, outputFormat}) if (!jsx) { pipeline.use(recmaJsxBuild, {outputFormat}) } pipeline.use(recmaStringify, {SourceMapGenerator}).use(recmaPlugins || []) return pipeline }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/evaluate.js
JavaScript
/** * @typedef {import('vfile').VFileCompatible} VFileCompatible * @typedef {import('./util/resolve-evaluate-options.js').EvaluateOptions} EvaluateOptions * @typedef {import('mdx/types').MDXModule} MDXModule */ import {compile, compileSync} from './compile.js' import {run, runSync} from './run.js' import {resolveEvaluateOptions} from './util/resolve-evaluate-options.js' /** * Evaluate MDX. * * @param {VFileCompatible} vfileCompatible MDX document to parse (`string`, `Buffer`, `vfile`, anything that can be given to `vfile`) * @param {EvaluateOptions} evaluateOptions * @return {Promise<MDXModule>} */ export async function evaluate(vfileCompatible, evaluateOptions) { const {compiletime, runtime} = resolveEvaluateOptions(evaluateOptions) // V8 on Erbium. /* c8 ignore next 2 */ return run(await compile(vfileCompatible, compiletime), runtime) } /** * Synchronously evaluate MDX. * * @param {VFileCompatible} vfileCompatible MDX document to parse (`string`, `Buffer`, `vfile`, anything that can be given to `vfile`) * @param {EvaluateOptions} evaluateOptions * @return {MDXModule} */ export function evaluateSync(vfileCompatible, evaluateOptions) { const {compiletime, runtime} = resolveEvaluateOptions(evaluateOptions) return runSync(compileSync(vfileCompatible, compiletime), runtime) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/integration/esbuild.js
JavaScript
/** * @typedef {import('esbuild').Plugin} Plugin * @typedef {import('esbuild').PluginBuild} PluginBuild * @typedef {import('esbuild').OnLoadArgs} OnLoadArgs * @typedef {import('esbuild').OnLoadResult} OnLoadResult * @typedef {import('esbuild').OnResolveArgs} OnResolveArgs * @typedef {import('esbuild').Message} Message * @typedef {import('vfile').VFileValue} VFileValue * @typedef {import('vfile-message').VFileMessage} VFileMessage * @typedef {import('unist').Point} Point * @typedef {import('../core.js').ProcessorOptions} ProcessorOptions * * @typedef {ProcessorOptions & {allowDangerousRemoteMdx?: boolean}} Options */ import assert from 'node:assert' import {promises as fs} from 'node:fs' import path from 'node:path' import process from 'node:process' import fetch from 'node-fetch' import {VFile} from 'vfile' import {createFormatAwareProcessors} from '../util/create-format-aware-processors.js' import {extnamesToRegex} from '../util/extnames-to-regex.js' const eol = /\r\n|\r|\n|\u2028|\u2029/g /** @type Map<string, string> */ const cache = new Map() const p = process /** * Compile MDX w/ esbuild. * * @param {Options} [options] * @return {Plugin} */ export function esbuild(options = {}) { const {allowDangerousRemoteMdx, ...rest} = options const name = 'esbuild-xdm' const remoteNamespace = name + '-remote' const {extnames, process} = createFormatAwareProcessors(rest) return {name, setup} /** * @param {PluginBuild} build */ function setup(build) { const filter = extnamesToRegex(extnames) /* eslint-disable-next-line security/detect-non-literal-regexp */ const filterHttp = new RegExp('^https?:\\/{2}.+' + filter.source) const http = /^https?:\/{2}/ const filterHttpOrRelative = /^(https?:\/{2}|.{1,2}\/).*/ if (allowDangerousRemoteMdx) { // Intercept import paths starting with "http:" and "https:" so // esbuild doesn't attempt to map them to a file system location. // Tag them with the "http-url" namespace to associate them with // this plugin. build.onResolve( {filter: filterHttp, namespace: 'file'}, resolveRemoteInLocal ) build.onResolve( {filter: filterHttpOrRelative, namespace: remoteNamespace}, resolveInRemote ) } build.onLoad({filter: /.*/, namespace: remoteNamespace}, onloadremote) build.onLoad({filter}, onload) /** @param {OnResolveArgs} args */ function resolveRemoteInLocal(args) { return {path: args.path, namespace: remoteNamespace} } // Intercept all import paths inside downloaded files and resolve them against // the original URL. All of these // files will be in the "http-url" namespace. Make sure to keep // the newly resolved URL in the "http-url" namespace so imports // inside it will also be resolved as URLs recursively. /** @param {OnResolveArgs} args */ function resolveInRemote(args) { return { path: String(new URL(args.path, args.importer)), namespace: remoteNamespace } } /** * @param {OnLoadArgs} data * @returns {Promise<OnLoadResult>} */ async function onloadremote(data) { const href = data.path console.log('%s: downloading `%s`', remoteNamespace, href) /** @type {string} */ let contents const cachedContents = cache.get(href) if (cachedContents) { contents = cachedContents } else { contents = await (await fetch(href)).text() cache.set(href, contents) } return filter.test(href) ? onload({ // Clean search and hash from URL. path: Object.assign(new URL(href), {search: '', hash: ''}).href, namespace: 'file', // @ts-expect-error `Buffer` type. pluginData: {contents, suffix: ''} }) : // V8 on Erbium. /* c8 ignore next 2 */ {contents, loader: 'js', resolveDir: p.cwd()} } /** * @param {Omit<OnLoadArgs, 'pluginData'> & {pluginData?: {contents?: string|Uint8Array}}} data * @returns {Promise<OnLoadResult>} */ async function onload(data) { /** @type {string} */ const doc = String( data.pluginData && data.pluginData.contents !== undefined ? data.pluginData.contents : await fs.readFile(data.path) ) let file = new VFile({value: doc, path: data.path}) /** @type {VFileValue|undefined} */ let value /** @type {Array<VFileMessage|Error>} */ let messages = [] /** @type {Array<Message>} */ const errors = [] /** @type {Array<Message>} */ const warnings = [] try { file = await process(file) value = file.value messages = file.messages } catch (error_) { const error = /** @type {VFileMessage|Error} */ (error_) if ('fatal' in error) error.fatal = true messages.push(error) } for (const message of messages) { const location = 'position' in message ? message.position : undefined const start = location ? location.start : undefined const end = location ? location.end : undefined let length = 0 let lineStart = 0 let line = 0 let column = 0 if ( start && start.line != null && start.column != null && start.offset != null ) { line = start.line column = start.column - 1 lineStart = start.offset - column length = 1 if ( end && end.line != null && end.column != null && end.offset != null ) { length = end.offset - start.offset } } eol.lastIndex = lineStart const match = eol.exec(doc) const lineEnd = match ? match.index : doc.length ;(!('fatal' in message) || message.fatal ? errors : warnings).push({ pluginName: name, text: 'reason' in message ? message.reason : /* Extra fallback to make sure weird values are definitely strings */ /* c8 ignore next */ message.stack || String(message), notes: [], location: { namespace: 'file', suggestion: '', file: data.path, line, column, length: Math.min(length, lineEnd), lineText: doc.slice(lineStart, lineEnd) }, detail: message }) } // Safety check: the file has a path, so there has to be a `dirname`. assert(file.dirname, 'expected `dirname` to be defined') // V8 on Erbium. /* c8 ignore next 10 */ return { contents: value, errors, warnings, resolveDir: http.test(file.path) ? p.cwd() : path.resolve(file.cwd, file.dirname) } } } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/integration/node.js
JavaScript
/** * @typedef {import('../compile.js').CompileOptions} CompileOptions * * @typedef LoaderOptions * @property {boolean} [fixRuntimeWithoutExportMap=true] * Several JSX runtimes, notably React and Emotion, don’t yet have a proper * export map set up. * Export maps are needed to map `xxx/jsx-runtime` to an actual file in ESM. * This option fixes React et al by turning those into `xxx/jsx-runtime.js`. * * @typedef {CompileOptions & LoaderOptions} Options */ import {promises as fs} from 'node:fs' import path from 'node:path' import {URL, fileURLToPath} from 'node:url' import {VFile} from 'vfile' import {createFormatAwareProcessors} from '../util/create-format-aware-processors.js' /** * Create smart processors to handle different formats. * * @param {Options} [options] */ export function createLoader(options = {}) { const {extnames, process} = createFormatAwareProcessors(options) let fixRuntimeWithoutExportMap = options.fixRuntimeWithoutExportMap if ( fixRuntimeWithoutExportMap === null || fixRuntimeWithoutExportMap === undefined ) { fixRuntimeWithoutExportMap = true } return {load, getFormat, transformSource} /* c8 ignore start */ // Node version 17. /** * @param {string} url * @param {unknown} context * @param {Function} defaultLoad */ async function load(url, context, defaultLoad) { if (!extnames.includes(path.extname(url))) { return defaultLoad(url, context, defaultLoad) } /* eslint-disable-next-line security/detect-non-literal-fs-filename */ const value = await fs.readFile(fileURLToPath(new URL(url))) const file = await process(new VFile({value, path: new URL(url)})) let source = String(file) if (fixRuntimeWithoutExportMap) { source = String(file).replace(/\/jsx-runtime(?=["'])/g, '$&.js') } // V8 on Erbium. /* c8 ignore next 2 */ return {format: 'module', source} } // Pre version 17. /** * @param {string} url * @param {unknown} context * @param {Function} defaultGetFormat * @deprecated * This is an obsolete legacy function that no longer works in Node 17. */ function getFormat(url, context, defaultGetFormat) { return extnames.includes(path.extname(url)) ? {format: 'module'} : defaultGetFormat(url, context, defaultGetFormat) } /** * @param {string} value * @param {{url: string, [x: string]: unknown}} context * @param {Function} defaultTransformSource * @deprecated * This is an obsolete legacy function that no longer works in Node 17. */ async function transformSource(value, context, defaultTransformSource) { if (!extnames.includes(path.extname(context.url))) { return defaultTransformSource(value, context, defaultTransformSource) } const file = await process(new VFile({value, path: new URL(context.url)})) let source = String(file) if (fixRuntimeWithoutExportMap) { source = String(file).replace(/\/jsx-runtime(?=["'])/g, '$&.js') } // V8 on Erbium. /* c8 ignore next 2 */ return {source} } /* c8 ignore end */ }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/integration/require.cjs
JavaScript
'use strict' const fs = require('fs') let deasync try { deasync = require('deasync') } catch { throw new Error( 'Could not load optional dependency `deasync`\nPlease manually install it' ) } const {runSync} = deasync(load)('../run.js') const {createFormatAwareProcessors} = deasync(load)( '../util/create-format-aware-processors.js' ) const {resolveEvaluateOptions} = deasync(load)( '../util/resolve-evaluate-options.js' ) module.exports = register function register(options) { const {compiletime, runtime} = resolveEvaluateOptions(options) const {extnames, processSync} = createFormatAwareProcessors(compiletime) let index = -1 while (++index < extnames.length) { // eslint-disable-next-line node/no-deprecated-api require.extensions[extnames[index]] = xdm } function xdm(module, path) { const file = processSync(fs.readFileSync(path)) const result = runSync(file, runtime) module.exports = result.default module.loaded = true } } function load(filePath, callback) { let called // Sometimes, the import hangs (see error message for reasons). // To fix that, a timeout can be used. const id = setTimeout(timeout, 1024) function timeout() { done( new Error( 'Could not import:\n' + "this error can occur when doing `require('xdm/register.cjs')` in an async function: please move the require to the top or remove it and use `node -r xdm/register.cjs …` instead\n" + 'this error can also occur if both `xdm/register.cjs` and `xdm/esm-loader.js` are used: please use one or the other' ) ) } import(filePath).then((module) => { done(null, module) }, done) function done(error, result) { if (called) return called = true clearTimeout(id) callback(error, result) } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/integration/rollup.js
JavaScript
/** * @typedef {import('@rollup/pluginutils').FilterPattern} FilterPattern * @typedef {import('rollup').Plugin} Plugin * @typedef {Omit<import('../compile.js').CompileOptions, 'SourceMapGenerator'>} CompileOptions * * @typedef RollupPluginOptions * @property {FilterPattern} [include] List of picomatch patterns to include * @property {FilterPattern} [exclude] List of picomatch patterns to exclude * * @typedef {CompileOptions & RollupPluginOptions} ProcessorAndRollupOptions */ import {SourceMapGenerator} from 'source-map' import {VFile} from 'vfile' import {createFilter} from '@rollup/pluginutils' import {createFormatAwareProcessors} from '../util/create-format-aware-processors.js' /** * Compile MDX w/ rollup. * * @param {ProcessorAndRollupOptions} [options] * @return {Plugin} */ export function rollup(options = {}) { const {include, exclude, ...rest} = options const {extnames, process} = createFormatAwareProcessors({ SourceMapGenerator, ...rest }) const filter = createFilter(include, exclude) return { name: 'xdm', async transform(value, path) { const file = new VFile({value, path}) if ( file.extname && filter(file.path) && extnames.includes(file.extname) ) { const compiled = await process(file) return {code: String(compiled.value), map: compiled.map} // V8 on Erbium. /* c8 ignore next 2 */ } } } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/integration/webpack.js
JavaScript
/** * @typedef {import('vfile').VFileCompatible} VFileCompatible * @typedef {import('vfile').VFile} VFile * @typedef {import('webpack').LoaderContext<unknown>} LoaderContext * @typedef {import('../compile.js').CompileOptions} CompileOptions * @typedef {Pick<CompileOptions, 'SourceMapGenerator'>} Defaults * @typedef {Omit<CompileOptions, 'SourceMapGenerator'>} Options * @typedef {(vfileCompatible: VFileCompatible) => Promise<VFile>} Process */ import {SourceMapGenerator} from 'source-map' import {createFormatAwareProcessors} from '../util/create-format-aware-processors.js' /** @type {WeakMap<CompileOptions, Process>} */ const cache = new WeakMap() /** * A Webpack (4+) loader for xdm. * See `webpack.cjs`, which wraps this, because Webpack loaders must currently * be CommonJS. * * @this {LoaderContext} * @param {string} value * @param {(error: Error|null|undefined, content?: string|Buffer, map?: Object) => void} callback */ export function loader(value, callback) { /** @type {Defaults} */ const defaults = this.sourceMap ? {SourceMapGenerator} : {} const options = /** @type {CompileOptions} */ (this.getOptions()) const config = {...defaults, ...options} let process = cache.get(config) if (!process) { process = createFormatAwareProcessors(config).process cache.set(config, process) } process({value, path: this.resourcePath}).then((file) => { callback(null, file.value, file.map) return file }, callback) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/node-types.js
JavaScript
// List of node types made by `mdast-util-mdx`, which have to be passed // through untouched from the mdast tree to the hast tree. export const nodeTypes = [ 'mdxFlowExpression', 'mdxJsxFlowElement', 'mdxJsxTextElement', 'mdxTextExpression', 'mdxjsEsm' ]
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/recma-document.js
JavaScript
/** * @typedef {import('estree-jsx').Directive} Directive * @typedef {import('estree-jsx').ExportDefaultDeclaration} ExportDefaultDeclaration * @typedef {import('estree-jsx').ExportSpecifier} ExportSpecifier * @typedef {import('estree-jsx').ExportNamedDeclaration} ExportNamedDeclaration * @typedef {import('estree-jsx').ExportAllDeclaration} ExportAllDeclaration * @typedef {import('estree-jsx').Expression} Expression * @typedef {import('estree-jsx').FunctionDeclaration} FunctionDeclaration * @typedef {import('estree-jsx').ImportDeclaration} ImportDeclaration * @typedef {import('estree-jsx').JSXElement} JSXElement * @typedef {import('estree-jsx').ModuleDeclaration} ModuleDeclaration * @typedef {import('estree-jsx').Node} Node * @typedef {import('estree-jsx').Program} Program * @typedef {import('estree-jsx').SimpleLiteral} SimpleLiteral * @typedef {import('estree-jsx').Statement} Statement * @typedef {import('estree-jsx').VariableDeclarator} VariableDeclarator * @typedef {import('estree-jsx').SpreadElement} SpreadElement * @typedef {import('estree-jsx').Property} Property * * @typedef RecmaDocumentOptions * @property {'program'|'function-body'} [outputFormat='program'] Whether to use either `import` and `export` statements to get the runtime (and optionally provider) and export the content, or get values from `arguments` and return things * @property {boolean} [useDynamicImport=false] Whether to keep `import` (and `export … from`) statements or compile them to dynamic `import()` instead * @property {string} [baseUrl] Resolve relative `import` (and `export … from`) relative to this URL * @property {string} [pragma='React.createElement'] Pragma for JSX (used in classic runtime) * @property {string} [pragmaFrag='React.Fragment'] Pragma for JSX fragments (used in classic runtime) * @property {string} [pragmaImportSource='react'] Where to import the identifier of `pragma` from (used in classic runtime) * @property {string} [jsxImportSource='react'] Place to import automatic JSX runtimes from (used in automatic runtime) * @property {'automatic'|'classic'} [jsxRuntime='automatic'] JSX runtime to use */ import {analyze} from 'periscopic' import {stringifyPosition} from 'unist-util-stringify-position' import {positionFromEstree} from 'unist-util-position-from-estree' import {create} from '../util/estree-util-create.js' import {specifiersToDeclarations} from '../util/estree-util-specifiers-to-declarations.js' import {declarationToExpression} from '../util/estree-util-declaration-to-expression.js' import {isDeclaration} from '../util/estree-util-is-declaration.js' /** * A plugin to wrap the estree in `MDXContent`. * * @type {import('unified').Plugin<[RecmaDocumentOptions?]|Array<void>, Program>} */ export function recmaDocument(options = {}) { const { baseUrl, useDynamicImport, outputFormat = 'program', pragma = 'React.createElement', pragmaFrag = 'React.Fragment', pragmaImportSource = 'react', jsxImportSource = 'react', jsxRuntime = 'automatic' } = options return (tree, file) => { /** @type {Array<string|[string, string]>} */ const exportedIdentifiers = [] /** @type {Array<Directive|Statement|ModuleDeclaration>} */ const replacement = [] /** @type {Array<string>} */ const pragmas = [] let exportAllCount = 0 /** @type {ExportDefaultDeclaration|ExportSpecifier|undefined} */ let layout /** @type {boolean|undefined} */ let content /** @type {Node} */ let child // Patch missing comments, which types say could occur. /* c8 ignore next */ if (!tree.comments) tree.comments = [] if (jsxRuntime) { pragmas.push('@jsxRuntime ' + jsxRuntime) } if (jsxRuntime === 'automatic' && jsxImportSource) { pragmas.push('@jsxImportSource ' + jsxImportSource) } if (jsxRuntime === 'classic' && pragma) { pragmas.push('@jsx ' + pragma) } if (jsxRuntime === 'classic' && pragmaFrag) { pragmas.push('@jsxFrag ' + pragmaFrag) } if (pragmas.length > 0) { tree.comments.unshift({type: 'Block', value: pragmas.join(' ')}) } if (jsxRuntime === 'classic' && pragmaImportSource) { if (!pragma) { throw new Error( 'Missing `pragma` in classic runtime with `pragmaImportSource`' ) } handleEsm({ type: 'ImportDeclaration', specifiers: [ { type: 'ImportDefaultSpecifier', local: {type: 'Identifier', name: pragma.split('.')[0]} } ], source: {type: 'Literal', value: pragmaImportSource} }) } // Find the `export default`, the JSX expression, and leave the rest // (import/exports) as they are. for (child of tree.body) { // ```js // export default props => <>{props.children}</> // ``` // // Treat it as an inline layout declaration. if (child.type === 'ExportDefaultDeclaration') { if (layout) { file.fail( 'Cannot specify multiple layouts (previous: ' + stringifyPosition(positionFromEstree(layout)) + ')', positionFromEstree(child), 'recma-document:duplicate-layout' ) } layout = child replacement.push({ type: 'VariableDeclaration', kind: 'const', declarations: [ { type: 'VariableDeclarator', id: {type: 'Identifier', name: 'MDXLayout'}, init: isDeclaration(child.declaration) ? declarationToExpression(child.declaration) : child.declaration } ] }) } // ```js // export {a, b as c} from 'd' // ``` else if (child.type === 'ExportNamedDeclaration' && child.source) { /** @type {SimpleLiteral} */ // @ts-expect-error `ExportNamedDeclaration.source` can only be a string literal. const source = child.source // Remove `default` or `as default`, but not `default as`, specifier. child.specifiers = child.specifiers.filter((specifier) => { if (specifier.exported.name === 'default') { if (layout) { file.fail( 'Cannot specify multiple layouts (previous: ' + stringifyPosition(positionFromEstree(layout)) + ')', positionFromEstree(child), 'recma-document:duplicate-layout' ) } layout = specifier // Make it just an import: `import MDXLayout from '…'`. handleEsm( create(specifier, { type: 'ImportDeclaration', specifiers: [ // Default as default / something else as default. specifier.local.name === 'default' ? { type: 'ImportDefaultSpecifier', local: {type: 'Identifier', name: 'MDXLayout'} } : create(specifier.local, { type: 'ImportSpecifier', imported: specifier.local, local: {type: 'Identifier', name: 'MDXLayout'} }) ], source: create(source, {type: 'Literal', value: source.value}) }) ) return false } return true }) // If there are other things imported, keep it. if (child.specifiers.length > 0) { handleExport(child) } } // ```js // export {a, b as c} // export * from 'a' // ``` else if ( child.type === 'ExportNamedDeclaration' || child.type === 'ExportAllDeclaration' ) { handleExport(child) } else if (child.type === 'ImportDeclaration') { handleEsm(child) } else if ( child.type === 'ExpressionStatement' && // @ts-expect-error types are wrong: `JSXElement`/`JSXFragment` are // `Expression`s. (child.expression.type === 'JSXFragment' || // @ts-expect-error " child.expression.type === 'JSXElement') ) { content = true replacement.push(createMdxContent(child.expression)) // The following catch-all branch is because plugins might’ve added // other things. // Normally, we only have import/export/jsx, but just add whatever’s // there. /* c8 ignore next 3 */ } else { replacement.push(child) } } // If there was no JSX content at all, add an empty function. if (!content) { replacement.push(createMdxContent()) } exportedIdentifiers.push(['MDXContent', 'default']) if (outputFormat === 'function-body') { replacement.push({ type: 'ReturnStatement', argument: { type: 'ObjectExpression', properties: [ ...Array.from({length: exportAllCount}).map( /** * @param {undefined} _ * @param {number} index * @returns {SpreadElement} */ (_, index) => ({ type: 'SpreadElement', argument: {type: 'Identifier', name: '_exportAll' + (index + 1)} }) ), ...exportedIdentifiers.map((d) => { /** @type {Property} */ const prop = { type: 'Property', kind: 'init', method: false, computed: false, shorthand: typeof d === 'string', key: { type: 'Identifier', name: typeof d === 'string' ? d : d[1] }, value: { type: 'Identifier', name: typeof d === 'string' ? d : d[0] } } return prop }) ] } }) } else { replacement.push({ type: 'ExportDefaultDeclaration', declaration: {type: 'Identifier', name: 'MDXContent'} }) } tree.body = replacement /** * @param {ExportNamedDeclaration|ExportAllDeclaration} node * @returns {void} */ function handleExport(node) { if (node.type === 'ExportNamedDeclaration') { // ```js // export function a() {} // export class A {} // export var a = 1 // ``` if (node.declaration) { exportedIdentifiers.push( ...analyze(node.declaration).scope.declarations.keys() ) } // ```js // export {a, b as c} // export {a, b as c} from 'd' // ``` for (child of node.specifiers) { exportedIdentifiers.push(child.exported.name) } } handleEsm(node) } /** * @param {ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration} node * @returns {void} */ function handleEsm(node) { // Rewrite the source of the `import` / `export … from`. // See: <https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier> if (baseUrl && node.source) { let value = String(node.source.value) try { // A full valid URL. value = String(new URL(value)) } catch { // Relative: `/example.js`, `./example.js`, and `../example.js`. if (/^\.{0,2}\//.test(value)) { value = String(new URL(value, baseUrl)) } // Otherwise, it’s a bare specifiers. // For example `some-package`, `@some-package`, and // `some-package/path`. // These are supported in Node and browsers plan to support them // with import maps (<https://github.com/WICG/import-maps>). } node.source = create(node.source, {type: 'Literal', value}) } /** @type {Statement|ModuleDeclaration|undefined} */ let replace /** @type {Expression} */ let init if (outputFormat === 'function-body') { if ( // Always have a source: node.type === 'ImportDeclaration' || node.type === 'ExportAllDeclaration' || // Source optional: (node.type === 'ExportNamedDeclaration' && node.source) ) { if (!useDynamicImport) { file.fail( 'Cannot use `import` or `export … from` in `evaluate` (outputting a function body) by default: please set `useDynamicImport: true` (and probably specify a `baseUrl`)', positionFromEstree(node), 'recma-document:invalid-esm-statement' ) } // Just for types. /* c8 ignore next 3 */ if (!node.source) { throw new Error('Expected `node.source` to be defined') } // ``` // import 'a' // //=> await import('a') // import a from 'b' // //=> const {default: a} = await import('b') // export {a, b as c} from 'd' // //=> const {a, c: b} = await import('d') // export * from 'a' // //=> const _exportAll0 = await import('a') // ``` init = { type: 'AwaitExpression', argument: create(node, { type: 'ImportExpression', source: node.source }) } if ( (node.type === 'ImportDeclaration' || node.type === 'ExportNamedDeclaration') && node.specifiers.length === 0 ) { replace = {type: 'ExpressionStatement', expression: init} } else { replace = { type: 'VariableDeclaration', kind: 'const', declarations: node.type === 'ExportAllDeclaration' ? [ { type: 'VariableDeclarator', id: { type: 'Identifier', name: '_exportAll' + ++exportAllCount }, init } ] : specifiersToDeclarations(node.specifiers, init) } } } else if (node.declaration) { replace = node.declaration } else { /** @type {Array<VariableDeclarator>} */ const declarators = node.specifiers .filter( (specifier) => specifier.local.name !== specifier.exported.name ) .map((specifier) => ({ type: 'VariableDeclarator', id: specifier.exported, init: specifier.local })) if (declarators.length > 0) { replace = { type: 'VariableDeclaration', kind: 'const', declarations: declarators } } } } else { replace = node } if (replace) { replacement.push(replace) } } } /** * @param {Expression} [content] * @returns {FunctionDeclaration} */ function createMdxContent(content) { /** @type {JSXElement} */ const element = { type: 'JSXElement', openingElement: { type: 'JSXOpeningElement', name: {type: 'JSXIdentifier', name: 'MDXLayout'}, attributes: [ { type: 'JSXSpreadAttribute', argument: {type: 'Identifier', name: 'props'} } ], selfClosing: false }, closingElement: { type: 'JSXClosingElement', name: {type: 'JSXIdentifier', name: 'MDXLayout'} }, children: [ { type: 'JSXElement', openingElement: { type: 'JSXOpeningElement', name: {type: 'JSXIdentifier', name: '_createMdxContent'}, attributes: [], selfClosing: true }, closingElement: null, children: [] } ] } // @ts-expect-error: JSXElements are expressions. const consequent = /** @type {Expression} */ (element) let argument = content || {type: 'Literal', value: null} if ( argument && // @ts-expect-error: fine. argument.type === 'JSXFragment' && // @ts-expect-error: fine. argument.children.length === 1 && // @ts-expect-error: fine. argument.children[0].type === 'JSXElement' ) { // @ts-expect-error: fine. argument = argument.children[0] } return { type: 'FunctionDeclaration', id: {type: 'Identifier', name: 'MDXContent'}, params: [ { type: 'AssignmentPattern', left: {type: 'Identifier', name: 'props'}, right: {type: 'ObjectExpression', properties: []} } ], body: { type: 'BlockStatement', body: [ { type: 'ReturnStatement', argument: { type: 'ConditionalExpression', test: {type: 'Identifier', name: 'MDXLayout'}, consequent, alternate: { type: 'CallExpression', callee: {type: 'Identifier', name: '_createMdxContent'}, arguments: [], optional: false } } }, { type: 'FunctionDeclaration', id: {type: 'Identifier', name: '_createMdxContent'}, params: [], body: { type: 'BlockStatement', body: [{type: 'ReturnStatement', argument}] } } ] } } } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/recma-jsx-build.js
JavaScript
/** * @typedef {import('estree-jsx').Program} Program * * @typedef RecmaJsxBuildOptions * @property {'program'|'function-body'} [outputFormat='program'] Whether to keep the import of the automatic runtime or get it from `arguments[0]` instead */ import {buildJsx} from 'estree-util-build-jsx' import {specifiersToDeclarations} from '../util/estree-util-specifiers-to-declarations.js' import {toIdOrMemberExpression} from '../util/estree-util-to-id-or-member-expression.js' /** * A plugin to build JSX into function calls. * `estree-util-build-jsx` does all the work for us! * * @type {import('unified').Plugin<[RecmaJsxBuildOptions?]|Array<void>, Program>} */ export function recmaJsxBuild(options = {}) { const {outputFormat} = options return (tree) => { buildJsx(tree) // When compiling to a function body, replace the import that was just // generated, and get `jsx`, `jsxs`, and `Fragment` from `arguments[0]` // instead. if ( outputFormat === 'function-body' && tree.body[0] && tree.body[0].type === 'ImportDeclaration' && typeof tree.body[0].source.value === 'string' && /\/jsx-runtime$/.test(tree.body[0].source.value) ) { tree.body[0] = { type: 'VariableDeclaration', kind: 'const', declarations: specifiersToDeclarations( tree.body[0].specifiers, toIdOrMemberExpression(['arguments', 0]) ) } } } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/recma-jsx-rewrite.js
JavaScript
/** * @typedef {import('estree-jsx').Node} Node * @typedef {import('estree-jsx').Expression} Expression * @typedef {import('estree-jsx').Function} ESFunction * @typedef {import('estree-jsx').ImportSpecifier} ImportSpecifier * @typedef {import('estree-jsx').JSXElement} JSXElement * @typedef {import('estree-jsx').JSXIdentifier} JSXIdentifier * @typedef {import('estree-jsx').JSXNamespacedName} JSXNamespacedName * @typedef {import('estree-jsx').ModuleDeclaration} ModuleDeclaration * @typedef {import('estree-jsx').Program} Program * @typedef {import('estree-jsx').Property} Property * @typedef {import('estree-jsx').Statement} Statement * @typedef {import('estree-jsx').VariableDeclarator} VariableDeclarator * @typedef {import('estree-jsx').ObjectPattern} ObjectPattern * @typedef {import('estree-jsx').Identifier} Identifier * * @typedef {import('estree-walker').SyncHandler} WalkHandler * * @typedef {import('periscopic').Scope & {node: Node}} Scope * * @typedef RecmaJsxRewriteOptions * @property {'program'|'function-body'} [outputFormat='program'] Whether to use an import statement or `arguments[0]` to get the provider * @property {boolean} [development=false] Whether to add extra information to error messages in generated code (can also be passed in Node.js by setting `NODE_ENV=development`) * @property {string} [providerImportSource] Place to import a provider from * * @typedef StackEntry * @property {Array<string>} objects * @property {Array<string>} components * @property {Array<string>} tags * @property {Record<string, {node: JSXElement, component: boolean}>} references * @property {ESFunction} node */ import {stringifyPosition} from 'unist-util-stringify-position' import {positionFromEstree} from 'unist-util-position-from-estree' import {name as isIdentifierName} from 'estree-util-is-identifier-name' import {walk} from 'estree-walker' import {analyze} from 'periscopic' import {specifiersToDeclarations} from '../util/estree-util-specifiers-to-declarations.js' import { toIdOrMemberExpression, toJsxIdOrMemberExpression } from '../util/estree-util-to-id-or-member-expression.js' import {toBinaryAddition} from '../util/estree-util-to-binary-addition.js' const own = {}.hasOwnProperty /** * A plugin that rewrites JSX in functions to accept components as * `props.components` (when the function is called `_createMdxContent`), or from * a provider (if there is one). * It also makes sure that any undefined components are defined: either from * received components or as a function that throws an error. * * @type {import('unified').Plugin<[RecmaJsxRewriteOptions?]|Array<void>, Program>} */ export function recmaJsxRewrite(options = {}) { const {development, providerImportSource, outputFormat} = options return (tree, file) => { // Find everything that’s defined in the top-level scope. const scopeInfo = analyze(tree) /** @type {Array<StackEntry>} */ const fnStack = [] /** @type {boolean|undefined} */ let importProvider /** @type {boolean|undefined} */ let createErrorHelper /** @type {Scope|null} */ let currentScope walk(tree, { enter(_node) { const node = /** @type {Node} */ (_node) if ( node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' ) { fnStack.push({ objects: [], components: [], tags: [], references: {}, node }) } let fnScope = fnStack[0] if ( !fnScope || (!isNamedFunction(fnScope.node, 'MDXContent') && !providerImportSource) ) { return } if ( fnStack[1] && isNamedFunction(fnStack[1].node, '_createMdxContent') ) { fnScope = fnStack[1] } const newScope = /** @type {Scope|undefined} */ ( // @ts-expect-error: periscopic doesn’t support JSX. scopeInfo.map.get(node) ) if (newScope) { newScope.node = node currentScope = newScope } if (currentScope && node.type === 'JSXElement') { let name = node.openingElement.name // `<x.y>`, `<Foo.Bar>`, `<x.y.z>`. if (name.type === 'JSXMemberExpression') { /** @type {Array<string>} */ const ids = [] // Find the left-most identifier. while (name.type === 'JSXMemberExpression') { ids.unshift(name.property.name) name = name.object } ids.unshift(name.name) const fullId = ids.join('.') const id = name.name if (!own.call(fnScope.references, fullId)) { fnScope.references[fullId] = {node, component: true} } if (!fnScope.objects.includes(id) && !inScope(currentScope, id)) { fnScope.objects.push(id) } } // `<xml:thing>`. else if (name.type === 'JSXNamespacedName') { // Ignore namespaces. } // If the name is a valid ES identifier, and it doesn’t start with a // lowercase letter, it’s a component. // For example, `$foo`, `_bar`, `Baz` are all component names. // But `foo` and `b-ar` are tag names. else if (isIdentifierName(name.name) && !/^[a-z]/.test(name.name)) { const id = name.name if (!inScope(currentScope, id)) { // No need to add an error for an undefined layout — we use an // `if` later. if (id !== 'MDXLayout' && !own.call(fnScope.references, id)) { fnScope.references[id] = {node, component: true} } if (!fnScope.components.includes(id)) { fnScope.components.push(id) } } } // @ts-expect-error Allow fields passed through from mdast through hast to // esast. else if (node.data && node.data._xdmExplicitJsx) { // Do not turn explicit JSX into components from `_components`. // As in, a given `h1` component is used for `# heading` (next case), // but not for `<h1>heading</h1>`. } else { const id = name.name if (!fnScope.tags.includes(id)) { fnScope.tags.push(id) } node.openingElement.name = toJsxIdOrMemberExpression([ '_components', id ]) if (node.closingElement) { node.closingElement.name = toJsxIdOrMemberExpression([ '_components', id ]) } } } }, leave(node) { /** @type {Array<Property>} */ const defaults = [] /** @type {Array<string>} */ const actual = [] /** @type {Array<Expression>} */ const parameters = [] /** @type {Array<VariableDeclarator>} */ const declarations = [] if (currentScope && currentScope.node === node) { // @ts-expect-error: `node`s were patched when entering. currentScope = currentScope.parent } if ( node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' ) { const fn = /** @type {ESFunction} */ (node) const scope = fnStack[fnStack.length - 1] /** @type {string} */ let name for (name of scope.tags) { defaults.push({ type: 'Property', kind: 'init', key: isIdentifierName(name) ? {type: 'Identifier', name} : {type: 'Literal', value: name}, value: {type: 'Literal', value: name}, method: false, shorthand: false, computed: false }) } actual.push(...scope.components) for (name of scope.objects) { // In some cases, a component is used directly (`<X>`) but it’s also // used as an object (`<X.Y>`). if (!actual.includes(name)) { actual.push(name) } } /** @type {string} */ let key // Add partials (so for `x.y.z` it’d generate `x` and `x.y` too). for (key in scope.references) { if (own.call(scope.references, key)) { const parts = key.split('.') let index = 0 while (++index < parts.length) { const partial = parts.slice(0, index).join('.') if (!own.call(scope.references, partial)) { scope.references[partial] = { node: scope.references[key].node, component: false } } } } } if (defaults.length > 0 || actual.length > 0) { if (providerImportSource) { importProvider = true parameters.push({ type: 'CallExpression', callee: {type: 'Identifier', name: '_provideComponents'}, arguments: [], optional: false }) } // Accept `components` as a prop if this is the `MDXContent` or // `_createMdxContent` function. if ( isNamedFunction(scope.node, 'MDXContent') || isNamedFunction(scope.node, '_createMdxContent') ) { parameters.push(toIdOrMemberExpression(['props', 'components'])) } if (defaults.length > 0 || parameters.length > 1) { parameters.unshift({ type: 'ObjectExpression', properties: defaults }) } // If we’re getting components from several sources, merge them. /** @type {Expression} */ let componentsInit = parameters.length > 1 ? { type: 'CallExpression', callee: toIdOrMemberExpression(['Object', 'assign']), arguments: parameters, optional: false } : parameters[0].type === 'MemberExpression' ? // If we’re only getting components from `props.components`, // make sure it’s defined. { type: 'LogicalExpression', operator: '||', left: parameters[0], right: {type: 'ObjectExpression', properties: []} } : parameters[0] /** @type {ObjectPattern|undefined} */ let componentsPattern // Add components to scope. // For `['MyComponent', 'MDXLayout']` this generates: // ```js // const {MyComponent, wrapper: MDXLayout} = _components // ``` // Note that MDXLayout is special as it’s taken from // `_components.wrapper`. if (actual.length > 0) { componentsPattern = { type: 'ObjectPattern', properties: actual.map((name) => ({ type: 'Property', kind: 'init', key: { type: 'Identifier', name: name === 'MDXLayout' ? 'wrapper' : name }, value: {type: 'Identifier', name}, method: false, shorthand: name !== 'MDXLayout', computed: false })) } } if (scope.tags.length > 0) { declarations.push({ type: 'VariableDeclarator', id: {type: 'Identifier', name: '_components'}, init: componentsInit }) componentsInit = {type: 'Identifier', name: '_components'} } if (componentsPattern) { declarations.push({ type: 'VariableDeclarator', id: componentsPattern, init: componentsInit }) } // Arrow functions with an implied return: if (fn.body.type !== 'BlockStatement') { fn.body = { type: 'BlockStatement', body: [{type: 'ReturnStatement', argument: fn.body}] } } /** @type {Array<Statement>} */ const statements = [ { type: 'VariableDeclaration', kind: 'let', declarations } ] const references = Object.keys(scope.references).sort() let index = -1 while (++index < references.length) { const id = references[index] const info = scope.references[id] const place = stringifyPosition(positionFromEstree(info.node)) /** @type {Array<Expression>} */ const parameters = [ {type: 'Literal', value: id}, {type: 'Literal', value: info.component} ] createErrorHelper = true if (development && place !== '1:1-1:1') { parameters.push({type: 'Literal', value: place}) } statements.push({ type: 'IfStatement', test: { type: 'UnaryExpression', operator: '!', prefix: true, argument: toIdOrMemberExpression(id.split('.')) }, consequent: { type: 'ExpressionStatement', expression: { type: 'CallExpression', callee: {type: 'Identifier', name: '_missingMdxReference'}, arguments: parameters, optional: false } }, alternate: null }) } fn.body.body.unshift(...statements) } fnStack.pop() } } }) // If a provider is used (and can be used), import it. if (importProvider && providerImportSource) { tree.body.unshift( createImportProvider(providerImportSource, outputFormat) ) } // If potentially missing components are used. if (createErrorHelper) { /** @type {Array<Expression>} */ const message = [ {type: 'Literal', value: 'Expected '}, { type: 'ConditionalExpression', test: {type: 'Identifier', name: 'component'}, consequent: {type: 'Literal', value: 'component'}, alternate: {type: 'Literal', value: 'object'} }, {type: 'Literal', value: ' `'}, {type: 'Identifier', name: 'id'}, { type: 'Literal', value: '` to be defined: you likely forgot to import, pass, or provide it.' } ] /** @type {Array<Identifier>} */ const parameters = [ {type: 'Identifier', name: 'id'}, {type: 'Identifier', name: 'component'} ] if (development) { message.push({ type: 'ConditionalExpression', test: {type: 'Identifier', name: 'place'}, consequent: toBinaryAddition([ {type: 'Literal', value: '\nIt’s referenced in your code at `'}, {type: 'Identifier', name: 'place'}, { type: 'Literal', value: (file.path ? '` in `' + file.path : '') + '`' } ]), alternate: {type: 'Literal', value: ''} }) parameters.push({type: 'Identifier', name: 'place'}) } tree.body.push({ type: 'FunctionDeclaration', id: {type: 'Identifier', name: '_missingMdxReference'}, generator: false, async: false, params: parameters, body: { type: 'BlockStatement', body: [ { type: 'ThrowStatement', argument: { type: 'NewExpression', callee: {type: 'Identifier', name: 'Error'}, arguments: [toBinaryAddition(message)] } } ] } }) } } } /** * @param {string} providerImportSource * @param {RecmaJsxRewriteOptions['outputFormat']} outputFormat * @returns {Statement|ModuleDeclaration} */ function createImportProvider(providerImportSource, outputFormat) { /** @type {Array<ImportSpecifier>} */ const specifiers = [ { type: 'ImportSpecifier', imported: {type: 'Identifier', name: 'useMDXComponents'}, local: {type: 'Identifier', name: '_provideComponents'} } ] return outputFormat === 'function-body' ? { type: 'VariableDeclaration', kind: 'const', declarations: specifiersToDeclarations( specifiers, toIdOrMemberExpression(['arguments', 0]) ) } : { type: 'ImportDeclaration', specifiers, source: {type: 'Literal', value: providerImportSource} } } /** * @param {ESFunction} node * @param {string} name * @returns {boolean} */ function isNamedFunction(node, name) { return Boolean(node && 'id' in node && node.id && node.id.name === name) } /** * @param {Scope} scope * @param {string} id */ function inScope(scope, id) { /** @type {Scope|null} */ let currentScope = scope while (currentScope) { if (currentScope.declarations.has(id)) { return true } // @ts-expect-error: `node`s have been added when entering. currentScope = currentScope.parent } return false }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/recma-stringify.js
JavaScript
/** * @typedef {import('estree-jsx').Node} Node * @typedef {import('estree-jsx').Program} Program * @typedef {import('estree-jsx').JSXAttribute} JSXAttribute * @typedef {import('estree-jsx').JSXClosingElement} JSXClosingElement * @typedef {import('estree-jsx').JSXClosingFragment} JSXClosingFragment * @typedef {import('estree-jsx').JSXElement} JSXElement * @typedef {import('estree-jsx').JSXEmptyExpression} JSXEmptyExpression * @typedef {import('estree-jsx').JSXExpressionContainer} JSXExpressionContainer * @typedef {import('estree-jsx').JSXFragment} JSXFragment * @typedef {import('estree-jsx').JSXIdentifier} JSXIdentifier * @typedef {import('estree-jsx').JSXMemberExpression} JSXMemberExpression * @typedef {import('estree-jsx').JSXNamespacedName} JSXNamespacedName * @typedef {import('estree-jsx').JSXOpeningElement} JSXOpeningElement * @typedef {import('estree-jsx').JSXOpeningFragment} JSXOpeningFragment * @typedef {import('estree-jsx').JSXSpreadAttribute} JSXSpreadAttribute * @typedef {import('estree-jsx').JSXText} JSXText * @typedef {import('vfile').VFile} VFile * @typedef {typeof import('source-map').SourceMapGenerator} SourceMapGenerator * * @typedef {Omit<import('astring').State, 'write'> & {write: ((code: string, node?: Node) => void)}} State * * @typedef {{[K in Node['type']]: (node: Node, state: State) => void}} Generator * * @typedef RecmaStringifyOptions * @property {SourceMapGenerator} [SourceMapGenerator] Generate a source map by passing a `SourceMapGenerator` from `source-map` in */ // @ts-expect-error baseGenerator is not yet exported by astring typings import {baseGenerator, generate} from 'astring' /** * A plugin that adds an esast compiler: a small wrapper around `astring` to add * support for serializing JSX. * * @type {import('unified').Plugin<[RecmaStringifyOptions?]|Array<void>, Program, string>} */ export function recmaStringify(options = {}) { const {SourceMapGenerator} = options Object.assign(this, {Compiler: compiler}) /** @type {import('unified').CompilerFunction<Program, string>} */ function compiler(tree, file) { /** @type {InstanceType<SourceMapGenerator>|undefined} */ let sourceMap if (SourceMapGenerator) { sourceMap = new SourceMapGenerator({file: file.path || 'unknown.mdx'}) } const result = generate(tree, { generator: Object.assign({}, baseGenerator, { JSXAttribute, JSXClosingElement, JSXClosingFragment, JSXElement, JSXEmptyExpression, JSXExpressionContainer, JSXFragment, JSXIdentifier, JSXMemberExpression, JSXNamespacedName, JSXOpeningElement, JSXOpeningFragment, JSXSpreadAttribute, JSXText }), comments: true, sourceMap }) if (sourceMap) { file.map = sourceMap.toJSON() } return result } } /** * `attr` * `attr="something"` * `attr={1}` * * @this {Generator} * @param {JSXAttribute} node * @param {State} state * @returns {void} */ function JSXAttribute(node, state) { this[node.name.type](node.name, state) if (node.value !== undefined && node.value !== null) { state.write('=') // Encode double quotes in attribute values. if (node.value.type === 'Literal') { state.write( '"' + encodeJsx(String(node.value.value)).replace(/"/g, '&quot;') + '"', node ) } else { this[node.value.type](node.value, state) } } } /** * `</div>` * * @this {Generator} * @param {JSXClosingElement} node * @param {State} state * @returns {void} */ function JSXClosingElement(node, state) { state.write('</') this[node.name.type](node.name, state) state.write('>') } /** * `</>` * * @this {Generator} * @param {JSXClosingFragment} node * @param {State} state * @returns {void} */ function JSXClosingFragment(node, state) { state.write('</>', node) } /** * `<div />` * `<div></div>` * * @this {Generator} * @param {JSXElement} node * @param {State} state * @returns {void} */ function JSXElement(node, state) { let index = -1 this[node.openingElement.type](node.openingElement, state) if (node.children) { while (++index < node.children.length) { const child = node.children[index] // Supported in types but not by Acorn. /* c8 ignore next 3 */ if (child.type === 'JSXSpreadChild') { throw new Error('JSX spread children are not supported') } this[child.type](child, state) } } if (node.closingElement) { this[node.closingElement.type](node.closingElement, state) } } /** * `{}` (always in a `JSXExpressionContainer`, which does the curlies) * * @this {Generator} * @returns {void} */ function JSXEmptyExpression() {} /** * `{expression}` * * @this {Generator} * @param {JSXExpressionContainer} node * @param {State} state * @returns {void} */ function JSXExpressionContainer(node, state) { state.write('{') this[node.expression.type](node.expression, state) state.write('}') } /** * `<></>` * * @this {Generator} * @param {JSXFragment} node * @param {State} state * @returns {void} */ function JSXFragment(node, state) { let index = -1 this[node.openingFragment.type](node.openingFragment, state) if (node.children) { while (++index < node.children.length) { const child = node.children[index] // Supported in types but not by Acorn. /* c8 ignore next 3 */ if (child.type === 'JSXSpreadChild') { throw new Error('JSX spread children are not supported') } this[child.type](child, state) } } this[node.closingFragment.type](node.closingFragment, state) } /** * `div` * * @this {Generator} * @param {JSXIdentifier} node * @param {State} state * @returns {void} */ function JSXIdentifier(node, state) { state.write(node.name, node) } /** * `member.expression` * * @this {Generator} * @param {JSXMemberExpression} node * @param {State} state * @returns {void} */ function JSXMemberExpression(node, state) { this[node.object.type](node.object, state) state.write('.') this[node.property.type](node.property, state) } /** * `ns:name` * * @this {Generator} * @param {JSXNamespacedName} node * @param {State} state * @returns {void} */ function JSXNamespacedName(node, state) { this[node.namespace.type](node.namespace, state) state.write(':') this[node.name.type](node.name, state) } /** * `<div>` * * @this {Generator} * @param {JSXOpeningElement} node * @param {State} state * @returns {void} */ function JSXOpeningElement(node, state) { let index = -1 state.write('<') this[node.name.type](node.name, state) if (node.attributes) { while (++index < node.attributes.length) { state.write(' ') this[node.attributes[index].type](node.attributes[index], state) } } state.write(node.selfClosing ? ' />' : '>') } /** * `<>` * * @this {Generator} * @param {JSXOpeningFragment} node * @param {State} state * @returns {void} */ function JSXOpeningFragment(node, state) { state.write('<>', node) } /** * `{...argument}` * * @this {Generator} * @param {JSXSpreadAttribute} node * @param {State} state * @returns {void} */ function JSXSpreadAttribute(node, state) { state.write('{') this.SpreadElement(node, state) state.write('}') } /** * `!` * * @this {Generator} * @param {JSXText} node * @param {State} state * @returns {void} */ function JSXText(node, state) { state.write( encodeJsx(node.value).replace(/<|{/g, ($0) => $0 === '<' ? '&lt;' : '&#123;' ), node ) } /** * Make sure that character references don’t pop up. * For example, the text `&copy;` should stay that way, and not turn into `©`. * We could encode all `&` (easy but verbose) or look for actual valid * references (complex but cleanest output). * Looking for the 2nd character gives us a middle ground. * The `#` is for (decimal and hexadecimal) numeric references, the letters * are for the named references. * * @param {string} value * @returns {string} */ function encodeJsx(value) { return value.replace(/&(?=[#a-z])/gi, '&amp;') }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/rehype-recma.js
JavaScript
/** * @typedef {import('estree-jsx').Program} Program * @typedef {import('hast').Root} Root */ import {toEstree} from 'hast-util-to-estree' /** * A plugin to transform an HTML (hast) tree to a JS (estree). * `hast-util-to-estree` does all the work for us! * * @type {import('unified').Plugin<Array<void>, Root, Program>} */ export function rehypeRecma() { return (tree) => toEstree(tree) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/rehype-remove-raw.js
JavaScript
/** * @typedef {import('hast').Root} Root */ import {visit} from 'unist-util-visit' /** * A tiny plugin that removes raw HTML. * This is needed if the format is `md` and `rehype-raw` was not used to parse * dangerous HTML into nodes. * * @type {import('unified').Plugin<Array<void>, Root>} */ export function rehypeRemoveRaw() { return (tree) => { visit(tree, 'raw', (_, index, parent) => { if (parent && typeof index === 'number') { parent.children.splice(index, 1) return index } }) } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/remark-mark-and-unravel.js
JavaScript
/** * @typedef {import('mdast').Root} Root * @typedef {import('mdast').Content} Content * @typedef {Root|Content} Node * @typedef {Extract<Node, import('unist').Parent>} Parent * * @typedef {import('./remark-mdx.js')} DoNotTouchAsThisImportIncludesMdxInTree */ import {visit} from 'unist-util-visit' /** * A tiny plugin that unravels `<p><h1>x</h1></p>` but also * `<p><Component /></p>` (so it has no knowledge of “HTML”). * It also marks JSX as being explicitly JSX, so when a user passes a `h1` * component, it is used for `# heading` but not for `<h1>heading</h1>`. * * @type {import('unified').Plugin<Array<void>, Root>} */ export function remarkMarkAndUnravel() { return (tree) => { visit(tree, (node, index, parent_) => { const parent = /** @type {Parent} */ (parent_) let offset = -1 let all = true /** @type {boolean|undefined} */ let oneOrMore if (parent && typeof index === 'number' && node.type === 'paragraph') { const children = node.children while (++offset < children.length) { const child = children[offset] if ( child.type === 'mdxJsxTextElement' || child.type === 'mdxTextExpression' ) { oneOrMore = true } else if ( child.type === 'text' && /^[\t\r\n ]+$/.test(String(child.value)) ) { // Empty. } else { all = false break } } if (all && oneOrMore) { offset = -1 while (++offset < children.length) { const child = children[offset] if (child.type === 'mdxJsxTextElement') { // @ts-expect-error: content model is fine. child.type = 'mdxJsxFlowElement' } if (child.type === 'mdxTextExpression') { // @ts-expect-error: content model is fine. child.type = 'mdxFlowExpression' } } parent.children.splice(index, 1, ...children) return index } } if ( node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement' ) { const data = node.data || (node.data = {}) data._xdmExplicitJsx = true } }) } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/plugin/remark-mdx.js
JavaScript
/** * @typedef {import('mdast').Root} Root * @typedef {import('micromark-extension-mdxjs').Options} MicromarkOptions * @typedef {import('mdast-util-mdx').ToMarkdownOptions} ToMarkdownOptions * @typedef {MicromarkOptions & ToMarkdownOptions} Options * * @typedef {import('mdast-util-mdx')} DoNotTouchAsThisImportIncludesMdxInTree */ import {mdxjs} from 'micromark-extension-mdxjs' import {mdxFromMarkdown, mdxToMarkdown} from 'mdast-util-mdx' /** * Add the micromark and mdast extensions for MDX.js (JS aware MDX). * * @type {import('unified').Plugin<[Options?]|Array<void>, Root>} */ export function remarkMdx(options = {}) { const data = this.data() add('micromarkExtensions', mdxjs(options)) add('fromMarkdownExtensions', mdxFromMarkdown()) add('toMarkdownExtensions', mdxToMarkdown(options)) /** * @param {string} field * @param {unknown} value */ function add(field, value) { const list = /** @type {Array<unknown>} */ ( // Other extensions /* c8 ignore next 2 */ data[field] ? data[field] : (data[field] = []) ) list.push(value) } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/run.js
JavaScript
/** * @typedef {import('vfile').VFile} VFile */ /** @type {new (code: string, ...args: Array<unknown>) => Function} **/ const AsyncFunction = Object.getPrototypeOf(run).constructor /** * Asynchronously run code. * * @param {{toString(): string}} file JS document to run * @param {unknown} options * @return {Promise<*>} */ export async function run(file, options) { // V8 on Erbium. /* c8 ignore next 2 */ return new AsyncFunction(String(file))(options) } /** * Synchronously run code. * * @param {{toString(): string}} file JS document to run * @param {unknown} options * @return {*} */ export function runSync(file, options) { return new Function(String(file))(options) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/create-format-aware-processors.js
JavaScript
/** * @typedef {import('vfile').VFileCompatible} VFileCompatible * @typedef {import('vfile').VFile} VFile * @typedef {import('unified').Processor} Processor * @typedef {import('../compile.js').CompileOptions} CompileOptions */ import {createProcessor} from '../core.js' import {md, mdx} from './extnames.js' import {resolveFileAndOptions} from './resolve-file-and-options.js' /** * Create smart processors to handle different formats. * * @param {CompileOptions} [compileOptions] */ export function createFormatAwareProcessors(compileOptions = {}) { const mdExtensions = compileOptions.mdExtensions || md const mdxExtensions = compileOptions.mdxExtensions || mdx /** @type {Processor} */ let cachedMarkdown /** @type {Processor} */ let cachedMdx return { extnames: compileOptions.format === 'md' ? mdExtensions : compileOptions.format === 'mdx' ? mdxExtensions : mdExtensions.concat(mdxExtensions), process, processSync } /** * Smart processor. * * @param {VFileCompatible} vfileCompatible MDX or markdown document * @return {Promise<VFile>} */ function process(vfileCompatible) { const {file, processor} = split(vfileCompatible) return processor.process(file) } /** * Sync smart processor. * * @param {VFileCompatible} vfileCompatible MDX or markdown document * @return {VFile} */ // C8 does not cover `.cjs` files (this is only used for the require hook, // which has to be CJS). /* c8 ignore next 4 */ function processSync(vfileCompatible) { const {file, processor} = split(vfileCompatible) return processor.processSync(file) } /** * Make a full vfile from what’s given, and figure out which processor * should be used for it. * This caches processors (one for markdown and one for MDX) so that they do * not have to be reconstructed for each file. * * @param {VFileCompatible} vfileCompatible MDX or markdown document * @return {{file: VFile, processor: Processor}} */ function split(vfileCompatible) { const {file, options} = resolveFileAndOptions( vfileCompatible, compileOptions ) const processor = options.format === 'md' ? cachedMarkdown || (cachedMarkdown = createProcessor(options)) : cachedMdx || (cachedMdx = createProcessor(options)) return {file, processor} } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/estree-util-create.js
JavaScript
/** * @typedef {import('estree-jsx').Node} Node */ /** * @template {Node} N * @param {Node} template * @param {N} node * @returns {N} */ export function create(template, node) { /** @type {Array<keyof template>} */ // @ts-expect-error: `start`, `end`, `comments` are custom Acorn fields. const fields = ['start', 'end', 'loc', 'range', 'comments'] let index = -1 while (++index < fields.length) { const field = fields[index] if (field in template) { // @ts-expect-error: assume they’re settable. node[field] = template[field] } } return node }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/estree-util-declaration-to-expression.js
JavaScript
/** * @typedef {import('estree-jsx').Declaration} Declaration * @typedef {import('estree-jsx').Expression} Expression */ /** * Turn a declaration into an expression. * Doesn’t work for variable declarations, but that’s fine for our use case * because currently we’re using this utility for export default declarations, * which can’t contain variable declarations. * * @param {Declaration} declaration * @returns {Expression} */ export function declarationToExpression(declaration) { if (declaration.type === 'FunctionDeclaration') { return {...declaration, type: 'FunctionExpression'} } if (declaration.type === 'ClassDeclaration') { return {...declaration, type: 'ClassExpression'} /* c8 ignore next 4 */ } // Probably `VariableDeclaration`. throw new Error('Cannot turn `' + declaration.type + '` into an expression') }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/estree-util-is-declaration.js
JavaScript
/** * @typedef {import('estree-jsx').Declaration} Declaration */ /** * @param {unknown} node * @returns {node is Declaration} */ export function isDeclaration(node) { /** @type {string} */ // @ts-expect-error Hush typescript, looks like `type` is available. const type = node && typeof node === 'object' && node.type return Boolean( type === 'FunctionDeclaration' || type === 'ClassDeclaration' || type === 'VariableDeclaration' ) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/estree-util-specifiers-to-declarations.js
JavaScript
/** * @typedef {import('estree-jsx').Identifier} Identifier * @typedef {import('estree-jsx').ImportSpecifier} ImportSpecifier * @typedef {import('estree-jsx').ImportDefaultSpecifier} ImportDefaultSpecifier * @typedef {import('estree-jsx').ImportNamespaceSpecifier} ImportNamespaceSpecifier * @typedef {import('estree-jsx').ExportSpecifier} ExportSpecifier * @typedef {import('estree-jsx').ObjectPattern} ObjectPattern * @typedef {import('estree-jsx').VariableDeclarator} VariableDeclarator * @typedef {import('estree-jsx').Expression} Expression */ import {create} from './estree-util-create.js' /** * @param {Array<ImportSpecifier|ImportDefaultSpecifier|ImportNamespaceSpecifier|ExportSpecifier>} specifiers * @param {Expression} init * @returns {Array<VariableDeclarator>} */ export function specifiersToDeclarations(specifiers, init) { let index = -1 /** @type {Array<VariableDeclarator>} */ const declarations = [] /** @type {Array<ImportSpecifier|ImportDefaultSpecifier|ExportSpecifier>} */ const otherSpecifiers = [] // Can only be one according to JS syntax. /** @type {ImportNamespaceSpecifier|undefined} */ let importNamespaceSpecifier while (++index < specifiers.length) { const specifier = specifiers[index] if (specifier.type === 'ImportNamespaceSpecifier') { importNamespaceSpecifier = specifier } else { otherSpecifiers.push(specifier) } } if (importNamespaceSpecifier) { declarations.push( create(importNamespaceSpecifier, { type: 'VariableDeclarator', id: importNamespaceSpecifier.local, init }) ) } declarations.push({ type: 'VariableDeclarator', id: { type: 'ObjectPattern', properties: otherSpecifiers.map((specifier) => { /** @type {Identifier} */ let key = specifier.type === 'ImportSpecifier' ? specifier.imported : specifier.type === 'ExportSpecifier' ? specifier.exported : {type: 'Identifier', name: 'default'} let value = specifier.local // Switch them around if we’re exporting. if (specifier.type === 'ExportSpecifier') { value = key key = specifier.local } return create(specifier, { type: 'Property', kind: 'init', shorthand: key.name === value.name, method: false, computed: false, key, value }) }) }, init: importNamespaceSpecifier ? {type: 'Identifier', name: importNamespaceSpecifier.local.name} : init }) return declarations }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/estree-util-to-binary-addition.js
JavaScript
/** * @typedef {import('estree-jsx').Expression} Expression */ /** * @param {Array<Expression>} expressions */ export function toBinaryAddition(expressions) { let index = -1 /** @type {Expression|undefined} */ let left while (++index < expressions.length) { const right = expressions[index] left = left ? {type: 'BinaryExpression', left, operator: '+', right} : right } // Just for types. /* c8 ignore next */ if (!left) throw new Error('Expected non-empty `expressions` to be passed') return left }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/estree-util-to-id-or-member-expression.js
JavaScript
/** * @typedef {import('estree-jsx').Identifier} Identifier * @typedef {import('estree-jsx').Literal} Literal * @typedef {import('estree-jsx').JSXIdentifier} JSXIdentifier * @typedef {import('estree-jsx').MemberExpression} MemberExpression * @typedef {import('estree-jsx').JSXMemberExpression} JSXMemberExpression */ import { start as esStart, cont as esCont, name as isIdentifierName } from 'estree-util-is-identifier-name' export const toIdOrMemberExpression = toIdOrMemberExpressionFactory( 'Identifier', 'MemberExpression', isIdentifierName ) export const toJsxIdOrMemberExpression = // @ts-expect-error: fine /** @type {(ids: Array<string|number>) => JSXIdentifier|JSXMemberExpression)} */ ( toIdOrMemberExpressionFactory( 'JSXIdentifier', 'JSXMemberExpression', isJsxIdentifierName ) ) /** * @param {string} idType * @param {string} memberType * @param {(value: string) => boolean} isIdentifier */ function toIdOrMemberExpressionFactory(idType, memberType, isIdentifier) { return toIdOrMemberExpression /** * @param {Array<string|number>} ids * @returns {Identifier|MemberExpression} */ function toIdOrMemberExpression(ids) { let index = -1 /** @type {Identifier|Literal|MemberExpression|undefined} */ let object while (++index < ids.length) { const name = ids[index] const valid = typeof name === 'string' && isIdentifier(name) // A value of `asd.123` could be turned into `asd['123']` in the JS form, // but JSX does not have a form for it, so throw. /* c8 ignore next 3 */ if (idType === 'JSXIdentifier' && !valid) { throw new Error('Cannot turn `' + name + '` into a JSX identifier') } /** @type {Identifier|Literal} */ // @ts-expect-error: JSX is fine. const id = valid ? {type: idType, name} : {type: 'Literal', value: name} // @ts-expect-error: JSX is fine. object = object ? { type: memberType, object, property: id, computed: id.type === 'Literal', optional: false } : id } // Just for types. /* c8 ignore next 3 */ if (!object) throw new Error('Expected non-empty `ids` to be passed') if (object.type === 'Literal') throw new Error('Expected identifier as left-most value') return object } } /** * Checks if the given string is a valid JSX identifier name. * @param {string} name */ function isJsxIdentifierName(name) { let index = -1 while (++index < name.length) { // We currently receive valid input, but this catches bugs and is needed // when externalized. /* c8 ignore next */ if (!(index ? jsxCont : esStart)(name.charCodeAt(index))) return false } // `false` if `name` is empty. return index > 0 } /** * Checks if the given character code can continue a JSX identifier. * @param {number} code */ function jsxCont(code) { return code === 45 /* `-` */ || esCont(code) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/extnames-to-regex.js
JavaScript
/** * Utility to turn a list of extnames (*with* dots) into an expression. * * @param {Array<string>} extnames List of extnames * @returns {RegExp} Regex matching them */ export function extnamesToRegex(extnames) { // eslint-disable-next-line security/detect-non-literal-regexp return new RegExp( '\\.(' + extnames.map((d) => d.slice(1)).join('|') + ')([?#]|$)' ) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/extnames.js
JavaScript
// @ts-expect-error: untyped. import markdownExtensions from 'markdown-extensions' export const mdx = ['.mdx'] /** @type {Array<string>} */ export const md = markdownExtensions.map((/** @type {string} */ d) => '.' + d)
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/resolve-evaluate-options.js
JavaScript
/** * @typedef {import('../core.js').ProcessorOptions} ProcessorOptions * * @typedef RuntimeOptions * @property {*} Fragment Symbol to use for fragments * @property {*} jsx Function to generate an element with static children * @property {*} jsxs Function to generate an element with dynamic children * * @typedef ProviderOptions * @property {*} [useMDXComponents] Function to get `MDXComponents` from context * * @typedef {RuntimeOptions & ProviderOptions} RunnerOptions * * @typedef {Omit<ProcessorOptions, 'jsx' | 'jsxImportSource' | 'jsxRuntime' | 'pragma' | 'pragmaFrag' | 'pragmaImportSource' | 'providerImportSource' | 'outputFormat'> } EvaluateProcessorOptions * * @typedef {EvaluateProcessorOptions & RunnerOptions} EvaluateOptions */ /** * Split compiletime options from runtime options. * * @param {EvaluateOptions} options * @returns {{compiletime: ProcessorOptions, runtime: RunnerOptions}} */ export function resolveEvaluateOptions(options) { const {Fragment, jsx, jsxs, useMDXComponents, ...rest} = options || {} if (!options || !('Fragment' in options)) throw new Error('Expected `Fragment` given to `evaluate`') if (!jsx) throw new Error('Expected `jsx` given to `evaluate`') if (!jsxs) throw new Error('Expected `jsxs` given to `evaluate`') return { compiletime: { ...rest, outputFormat: 'function-body', providerImportSource: useMDXComponents ? '#' : undefined }, runtime: {Fragment, jsx, jsxs, useMDXComponents} } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
lib/util/resolve-file-and-options.js
JavaScript
/** * @typedef {import('vfile').VFileCompatible} VFileCompatible * @typedef {import('../core.js').ProcessorOptions} ProcessorOptions * @typedef {import('../compile.js').CompileOptions} CompileOptions */ import {VFile} from 'vfile' import {md} from './extnames.js' /** * Create a file and options from a given `vfileCompatible` and options that * might contain `format: 'detect'`. * * @param {VFileCompatible} vfileCompatible * @param {CompileOptions} [options] * @returns {{file: VFile, options: ProcessorOptions}} */ export function resolveFileAndOptions(vfileCompatible, options) { const file = looksLikeAVFile(vfileCompatible) ? vfileCompatible : new VFile(vfileCompatible) const {format, ...rest} = options || {} return { file, options: { format: format === 'md' || format === 'mdx' ? format : file.extname && (rest.mdExtensions || md).includes(file.extname) ? 'md' : 'mdx', ...rest } } } /** * @param {VFileCompatible} [value] * @returns {value is VFile} */ function looksLikeAVFile(value) { return Boolean( value && typeof value === 'object' && 'message' in value && 'messages' in value ) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
register.cjs
JavaScript
'use strict' const runtime = require('react/jsx-runtime') const register = require('./lib/integration/require.cjs') register({...runtime})
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
registry.d.ts
TypeScript
/* eslint-disable @typescript-eslint/naming-convention */ declare module '*.mdx' { import {MDXProps} from 'mdx/types' /** * MDX Content. * * @see https://v2.mdxjs.com/mdx/ */ export default function MDXContent(props: MDXProps): JSX.Element } declare module '*.md' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' } declare module '*.markdown' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' } declare module '*.mdown' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' } declare module '*.mkdn' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' } declare module '*.mkd' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' } declare module '*.mdwn' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' } declare module '*.mkdown' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' } declare module '*.ron' { /** * Markdown content. * * @see https://spec.commonmark.org */ export {default} from '*.mdx' }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
rollup.js
JavaScript
export {rollup as default} from './lib/integration/rollup.js'
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
script/benchmark.js
JavaScript
import {promises as fs} from 'node:fs' import {transformSync as babel} from '@babel/core' import marky from 'marky' import gfm from 'remark-gfm' import {sync as mdx1} from 'mdx1' import {sync as mdx2} from 'mdx2' import {compileSync as xdm} from '../index.js' main() async function main() { /** @type {string} */ let doc try { doc = String(await fs.readFile('giant.mdx')) } catch { console.warn( 'Cannot read `giant.mdx`: please place a large file in the root of `xdm`' ) return } run('@mdx-js/mdx 1', () => { babel(mdx1(doc), { cloneInputAst: false, compact: true, configFile: false, plugins: ['@babel/plugin-transform-react-jsx'] }) }) run('@mdx-js/mdx 2', () => { babel(mdx2(doc), { cloneInputAst: false, compact: true, configFile: false, plugins: ['@babel/plugin-transform-react-jsx'] }) }) run('xdm', () => xdm(doc, {remarkPlugins: [gfm]})) } function run(label, fn) { marky.mark(label) fn() const entry = marky.stop(label) console.log('%s: %ims', entry.name, entry.duration) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/babel.js
JavaScript
/** * @typedef {import('@babel/parser').ParserOptions} ParserOptions * @typedef {import('estree-jsx').Program} Program * @typedef {import('mdx/types').MDXContent} MDXContent */ import {promises as fs} from 'node:fs' import path from 'node:path' import test from 'tape' import parser from '@babel/parser' import {transformAsync as babel} from '@babel/core' // @ts-expect-error: untyped. import toBabel from 'estree-to-babel' import React from 'react' import {renderToStaticMarkup} from 'react-dom/server' import {compileSync} from '../index.js' test('xdm (babel)', async (t) => { const base = path.resolve(path.join('test', 'context')) const result = await babel( 'export const Message = () => <>World!</>\n\n# Hello, <Message />', {filename: 'example.mdx', plugins: [babelPluginSyntaxMdx]} ) const js = (result || {code: undefined}).code || '' await fs.writeFile(path.join(base, 'babel.js'), js) const Content = /** @type {MDXContent} */ ( /* @ts-expect-error file is dynamically generated */ (await import('./context/babel.js')).default // type-coverage:ignore-line ) t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>Hello, World!</h1>', 'should compile' ) await fs.unlink(path.join(base, 'babel.js')) function babelPluginSyntaxMdx() { return { /** * @param {string} value * @param {ParserOptions} options */ parserOverride(value, options) { if ( // @ts-expect-error: types accept one of them. (options.sourceFileName || options.sourceFilename) && // @ts-expect-error: types accept one of them. path.extname(options.sourceFileName || options.sourceFilename) === '.mdx' ) { return compileSync( {value, path: options.sourceFilename}, {recmaPlugins: [recmaBabel]} ).result } return parser.parse(value, options) } } } /** @type {import('unified').Plugin<Array<void>, Program, string>} */ function recmaBabel() { Object.assign(this, {Compiler: toBabel}) } t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/context/components.js
JavaScript
import React from 'react' /** * @param {Record<string, unknown>} props */ export function Pill(props) { return React.createElement('span', {...props, style: {color: 'red'}}) } /** * @param {Record<string, unknown>} props */ export function Layout(props) { return React.createElement('div', {...props, style: {color: 'red'}}) } export default Layout
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/context/data.js
JavaScript
export const number = 3.14 export const object = {a: 1, b: 2} export const array = [1, 2] export default 2 * number
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/core.js
JavaScript
/** * @typedef {import('hast').Root} Root * @typedef {import('../lib/compile.js').VFileCompatible} VFileCompatible * @typedef {import('mdx/types').MDXContent} MDXContent * @typedef {import('mdx/types').MDXModule} MDXModule * @typedef {import('mdx/types').MDXComponents} Components */ import path from 'node:path' import {promises as fs} from 'node:fs' import {MDXProvider} from '@mdx-js/react' import {nanoid} from 'nanoid' import {h} from 'preact' import {render} from 'preact-render-to-string' import React from 'react' import {renderToStaticMarkup} from 'react-dom/server' import rehypeKatex from 'rehype-katex' import rehypeRaw from 'rehype-raw' import remarkFrontmatter from 'remark-frontmatter' import remarkGfm from 'remark-gfm' import remarkMath from 'remark-math' import test from 'tape' import {components as themeUiComponents, ThemeProvider} from 'theme-ui' import {base as themeUiBaseTheme} from '@theme-ui/preset-base' import {compile, compileSync, createProcessor, nodeTypes} from '../index.js' test('xdm', async (t) => { t.equal( renderToStaticMarkup( React.createElement(await run(await compile('# hi!'))) ), '<h1>hi!</h1>', 'should compile' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('# hi!')))), '<h1>hi!</h1>', 'should compile (sync)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('')))), '', 'should compile an empty document' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('x', { remarkPlugins: [() => () => ({type: 'root', children: []})] }) ) ) ), '', 'should compile an empty document (remark)' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('y', { rehypePlugins: [() => () => ({type: 'root', children: []})] }) ) ) ), '', 'should compile an empty document (rehype)' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('y', { rehypePlugins: [() => () => ({type: 'doctype', name: 'html'})] }) ) ) ), '', 'should compile a document (rehype, non-representable)' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('y', { rehypePlugins: [ () => () => ({type: 'element', tagName: 'x', children: []}) ] }) ) ) ), '<x></x>', 'should compile a non-element document (rehype, single element)' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('y', { rehypePlugins: [ () => () => ({type: 'element', tagName: 'a-b', children: []}) ] }) ) ) ), '<a-b></a-b>', 'should compile custom elements' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('!', {jsxRuntime: 'automatic'})) ) ), '<p>!</p>', 'should support the automatic runtime (`@jsxRuntime`)' ) t.equal( render( h( // @ts-expect-error: React and Preact interferring. await run(compileSync('?', {jsxImportSource: 'preact'})), {}, [] ) ), '<p>?</p>', 'should support an import source (`@jsxImportSource`)' ) t.equal( render( h( // @ts-expect-error: Preact types do not accept `JSX.Element`. await run( compileSync('<>%</>', { jsxRuntime: 'classic', pragma: 'preact.createElement', pragmaFrag: 'preact.Fragment', pragmaImportSource: 'preact/compat' }) ), {} ) ), '%', 'should support `pragma`, `pragmaFrag` for `preact/compat`' ) t.equal( render( h( // @ts-expect-error: Preact types do not accept `JSX.Element`. await run(compileSync('<>1</>', {jsxImportSource: 'preact'})), {} ) ), '1', 'should support `jsxImportSource` for `preact`' ) t.equal( renderToStaticMarkup( React.createElement( await run( String( compileSync('<>+</>', {jsxImportSource: '@emotion/react'}) ).replace( /\/jsx-runtime(?=["'])/g, '$&/dist/emotion-react-jsx-runtime.cjs.prod.js' ) ) ) ), '+', 'should support `jsxImportSource` for `emotion`' ) t.throws( () => { compileSync('import React from "react"\n\n.', { jsxRuntime: 'classic', pragmaImportSource: '@emotion/react', pragma: '' }) }, /Missing `pragma` in classic runtime with `pragmaImportSource`/, 'should *not* support `jsxClassicImportSource` w/o `pragma`' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<X />')), { components: { /** @param {Record<string, unknown>} props */ // @ts-expect-error: React and Preact interfering. X(props) { return React.createElement('span', props, '!') } } }) ), '<span>!</span>', 'should support passing in `components` to `MDXContent`' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<x.y />')), { components: { x: { /** @param {object} props */ // @ts-expect-error: React and Preact interfering. y(props) { return React.createElement('span', props, '?') } } } }) ), '<span>?</span>', 'should support passing in `components` (for members) to `MDXContent`' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<X /> and <X.Y />')), { components: { // @ts-expect-error: React and Preact interfering. X: Object.assign( /** @param {Record<string, unknown>} props */ (props) => React.createElement('span', props, '!'), { /** @param {Record<string, unknown>} props */ Y(props) { return React.createElement('span', props, '?') } } ) } }) ), '<p><span>!</span> and <span>?</span></p>', 'should support passing in `components` directly and as an object w/ members' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('*a*')), { components: { // @ts-expect-error: React and Preact interfering. em(props) { return React.createElement('i', props) } } }) ), '<p><i>a</i></p>', 'should support overwriting components by passing them to `MDXContent`' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('export var X = () => <em>a</em>\n\n*a*, <X>b</X>') ), { components: { // @ts-expect-error: React and Preact interfering. em(props) { return React.createElement('i', props) } } } ) ), '<p><i>a</i>, <em>a</em></p>', 'should *not* support overwriting components in exports' ) try { renderToStaticMarkup( React.createElement( await run(compileSync('export var X = () => <Y />\n\n<X />')) ) ) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.match( exception.message, /Y is not defined/, 'should throw on missing components in exported components' ) } t.equal( renderToStaticMarkup( React.createElement( MDXProvider, { components: { // @ts-expect-error: React and Preact interferring. Y() { return React.createElement('span', {}, '!') } } }, React.createElement( await run( compileSync('export var X = () => <Y />\n\n<X />', { providerImportSource: '@mdx-js/react' }) ) ) ) ), '<span>!</span>', 'should support provided components in exported components' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync( 'export function Foo({Box = "div"}) { return <Box>a</Box>; }\n\n<Foo />' ) ) ) ), '<div>a</div>', 'should support custom components in exported components' ) t.equal( renderToStaticMarkup( React.createElement( MDXProvider, { components: { y: { // @ts-expect-error `mdx-js/react` types do not support nested components. z() { return React.createElement('span', {}, '!') } } } }, React.createElement( await run( compileSync('export var X = () => <y.z />\n\n<X />', { providerImportSource: '@mdx-js/react' }) ) ) ) ), '<span>!</span>', 'should support provided component objects in exported components' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('a')), { components: { /** * @param {Record<string, unknown>} props */ // @ts-expect-error: React and Preact interfering. wrapper(props) { const {components, ...rest} = props return React.createElement('div', rest) } } }) ), '<div><p>a</p></div>', 'should support setting the layout by passing it (as `wrapper`) to `MDXContent`' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync( `import { MDXProvider } from '@mdx-js/react' export default function Layout({children}) { return <MDXProvider components={{h1: 'h2'}}>{children}</MDXProvider> } # hi`, {providerImportSource: '@mdx-js/react'} ) ) ) ), '<h2>hi</h2>', 'should support providing components in a layout' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync( 'import React from "react"\nexport default class extends React.Component { render() { return <>{this.props.children}</> } }\n\na' ) ) ) ), '<p>a</p>', 'should support setting the layout through a class component' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync( 'export default function Layout({components, ...props}) { return <section {...props} /> }\n\na' ) ), { components: { /** * @param {Record<string, unknown>} props */ // @ts-expect-error: React and Preact interfering. wrapper(props) { const {components, ...rest} = props return React.createElement('article', rest) } } } ) ), '<section><p>a</p></section>', 'should *not* support overwriting the layout by passing one (as `wrapper`) to `MDXContent`' ) t.throws( () => { compileSync( 'export default function a() {}\n\nexport default function b() {}\n\n.' ) }, /Cannot specify multiple layouts \(previous: 1:1-1:31\)/, 'should *not* support multiple layouts (1)' ) t.throws( () => { compileSync( 'export default function a() {}\n\nexport {Layout as default} from "./components.js"\n\n.' ) }, /Cannot specify multiple layouts \(previous: 1:1-1:31\)/, 'should *not* support multiple layouts (2)' ) try { renderToStaticMarkup( React.createElement(await run(compileSync('export default a'))) ) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.equal( exception.message, 'a is not defined', 'should support an identifier as an export default' ) } try { renderToStaticMarkup(React.createElement(await run(compileSync('<X />')))) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.match( exception.message, /Expected component `X` to be defined: you likely forgot to import, pass, or provide it./, 'should throw if a required component is not passed' ) } try { renderToStaticMarkup(React.createElement(await run(compileSync('<a.b />')))) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.match( exception.message, /Expected object `a` to be defined: you likely forgot to import, pass, or provide it/, 'should throw if a required member is not passed' ) } try { renderToStaticMarkup( React.createElement(await run(compileSync('<X />', {development: true}))) ) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.match( exception.message, /It’s referenced in your code at `1:1-1:6/, 'should pass more info to errors w/ `development: true`' ) } try { renderToStaticMarkup( React.createElement( await run( compileSync( {value: 'asd <a.b />', path: 'folder/example.mdx'}, {development: true} ) ) ) ) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.match( exception.message, /It’s referenced in your code at `1:5-1:12` in `folder\/example.mdx`/, 'should show what file contains the error w/ `development: true`, and `path`' ) } t.equal( renderToStaticMarkup( React.createElement( MDXProvider, { components: { /** * @param {Record<string, unknown>} props */ // @ts-expect-error: React and Preact interferring. em(props) { return React.createElement('i', props) } } }, React.createElement( await run(compileSync('*z*', {providerImportSource: '@mdx-js/react'})) ) ) ), '<p><i>z</i></p>', 'should support setting components through context with a `providerImportSource`' ) try { renderToStaticMarkup( React.createElement( await run(compileSync('<X />', {providerImportSource: '@mdx-js/react'})) ) ) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.match( exception.message, /Expected component `X` to be defined: you likely forgot to import, pass, or provide it/, 'should throw if a required component is not passed or given to `MDXProvider`' ) } t.equal( renderToStaticMarkup( React.createElement(await run(createProcessor().processSync('x'))) ), '<p>x</p>', 'should support `createProcessor`' ) t.equal( renderToStaticMarkup( React.createElement( await run(createProcessor({format: 'md'}).processSync('\tx')) ) ), '<pre><code>x\n</code></pre>', 'should support `format: md`' ) t.equal( renderToStaticMarkup( React.createElement( await run(createProcessor({format: 'mdx'}).processSync('\tx')) ) ), '<p>x</p>', 'should support `format: mdx`' ) try { // @ts-expect-error runtime does not accept `detect`. createProcessor({format: 'detect'}) t.fail() } catch (/** @type {unknown} */ error) { const exception = /** @type {Error} */ (error) t.equal( exception.message, "Incorrect `format: 'detect'`: `createProcessor` can support either `md` or `mdx`; it does not support detecting the format", 'should not support `format: detect`' ) } t.equal( renderToStaticMarkup( React.createElement(await run(await compile({value: '\tx'}))) ), '<p>x</p>', 'should detect as `mdx` by default' ) t.equal( renderToStaticMarkup( React.createElement( await run(await compile({value: '\tx', path: 'y.md'})) ) ), '<pre><code>x\n</code></pre>', 'should detect `.md` as `md`' ) t.equal( renderToStaticMarkup( React.createElement( await run(await compile({value: '\tx', path: 'y.mdx'})) ) ), '<p>x</p>', 'should detect `.mdx` as `mdx`' ) t.equal( renderToStaticMarkup( React.createElement( await run(await compile({value: '\tx', path: 'y.md'}, {format: 'mdx'})) ) ), '<p>x</p>', 'should not “detect” `.md` w/ `format: mdx`' ) t.equal( renderToStaticMarkup( React.createElement( await run(await compile({value: '\tx', path: 'y.mdx'}, {format: 'md'})) ) ), '<pre><code>x\n</code></pre>', 'should not “detect” `.mdx` w/ `format: md`' ) t.equal( renderToStaticMarkup( React.createElement( await run(await compile({value: '<q>r</q>', path: 's.md'})) ) ), '<p>r</p>', 'should not support HTML in markdown by default' ) t.equal( renderToStaticMarkup( React.createElement( await run( await compile( {value: '<q>r</q>', path: 's.md'}, {rehypePlugins: [rehypeRaw]} ) ) ) ), '<p><q>r</q></p>', 'should support HTML in markdown w/ `rehype-raw`' ) t.match( String( await compile('a', { format: 'md', remarkPlugins: [ () => (/** @type {Root} */ tree) => { tree.children.unshift({ type: 'mdxjsEsm', value: '', data: { estree: { type: 'Program', comments: [], sourceType: 'module', body: [ { type: 'VariableDeclaration', kind: 'var', declarations: [ { type: 'VariableDeclarator', id: {type: 'Identifier', name: 'a'}, init: {type: 'Literal', value: 1} } ] } ] } } }) } ], rehypePlugins: [[rehypeRaw, {passThrough: nodeTypes}]] }) ), /var a = 1/, 'should support injected MDX nodes w/ `rehype-raw`' ) t.end() }) test('jsx', async (t) => { t.equal( String(compileSync('*a*', {jsx: true})), [ '/*@jsxRuntime automatic @jsxImportSource react*/', 'function MDXContent(props = {}) {', ' let {wrapper: MDXLayout} = props.components || ({});', ' return MDXLayout ? <MDXLayout {...props}><_createMdxContent /></MDXLayout> : _createMdxContent();', ' function _createMdxContent() {', ' let _components = Object.assign({', ' p: "p",', ' em: "em"', ' }, props.components);', ' return <_components.p><_components.em>{"a"}</_components.em></_components.p>;', ' }', '}', 'export default MDXContent;', '' ].join('\n'), 'should serialize JSX w/ `jsx: true`' ) t.equal( String(compileSync('<a {...b} c d="1" e={1} />', {jsx: true})), [ '/*@jsxRuntime automatic @jsxImportSource react*/', 'function MDXContent(props = {}) {', ' let {wrapper: MDXLayout} = props.components || ({});', ' return MDXLayout ? <MDXLayout {...props}><_createMdxContent /></MDXLayout> : _createMdxContent();', ' function _createMdxContent() {', ' return <a {...b} c d="1" e={1} />;', ' }', '}', 'export default MDXContent;', '' ].join('\n'), 'should serialize props' ) t.equal( String(compileSync('<><a:b /><c.d/></>', {jsx: true})), [ '/*@jsxRuntime automatic @jsxImportSource react*/', 'function MDXContent(props = {}) {', ' let {wrapper: MDXLayout} = props.components || ({});', ' return MDXLayout ? <MDXLayout {...props}><_createMdxContent /></MDXLayout> : _createMdxContent();', ' function _createMdxContent() {', ' let {c} = props.components || ({});', ' if (!c) _missingMdxReference("c", false);', ' if (!c.d) _missingMdxReference("c.d", true);', ' return <><><a:b /><c.d /></></>;', ' }', '}', 'export default MDXContent;', 'function _missingMdxReference(id, component) {', ' throw new Error("Expected " + (component ? "component" : "object") + " `" + id + "` to be defined: you likely forgot to import, pass, or provide it.");', '}', '' ].join('\n'), 'should serialize fragments, namespaces, members' ) t.equal( String(compileSync('<>a {/* 1 */} b</>', {jsx: true})), [ '/*@jsxRuntime automatic @jsxImportSource react*/', '/*1*/', 'function MDXContent(props = {}) {', ' let {wrapper: MDXLayout} = props.components || ({});', ' return MDXLayout ? <MDXLayout {...props}><_createMdxContent /></MDXLayout> : _createMdxContent();', ' function _createMdxContent() {', ' return <><>{"a "}{}{" b"}</></>;', ' }', '}', 'export default MDXContent;', '' ].join('\n'), 'should serialize fragments, expressions' ) t.equal( String(compileSync('{<a-b></a-b>}', {jsx: true})), [ '/*@jsxRuntime automatic @jsxImportSource react*/', 'function MDXContent(props = {}) {', ' let {wrapper: MDXLayout} = props.components || ({});', ' return MDXLayout ? <MDXLayout {...props}><_createMdxContent /></MDXLayout> : _createMdxContent();', ' function _createMdxContent() {', ' let _components = Object.assign({', ' "a-b": "a-b"', ' }, props.components);', ' return <>{<_components.a-b></_components.a-b>}</>;', ' }', '}', 'export default MDXContent;', '' ].join('\n'), 'should serialize custom elements inside expressions' ) t.equal( String(compileSync('Hello {props.name}', {jsx: true})), [ '/*@jsxRuntime automatic @jsxImportSource react*/', 'function MDXContent(props = {}) {', ' let {wrapper: MDXLayout} = props.components || ({});', ' return MDXLayout ? <MDXLayout {...props}><_createMdxContent /></MDXLayout> : _createMdxContent();', ' function _createMdxContent() {', ' let _components = Object.assign({', ' p: "p"', ' }, props.components);', ' return <_components.p>{"Hello "}{props.name}</_components.p>;', ' }', '}', 'export default MDXContent;', '' ].join('\n'), 'should allow using props' ) t.match( String(compileSync("{<w x='y \" z' />}", {jsx: true})), /x="y &quot; z"/, 'should serialize double quotes in attribute values' ) t.match( String(compileSync('{<>a &amp; b &#123; c &lt; d</>}', {jsx: true})), /a & b &#123; c &lt; d/, 'should serialize `<` and `{` in JSX text' ) t.end() }) test('markdown (CM)', async (t) => { t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('[a](b)')))), '<p><a href="b">a</a></p>', 'should support links (resource) (`[]()` -> `a`)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('[a]: b\n[a]'))) ), '<p><a href="b">a</a></p>', 'should support links (reference) (`[][]` -> `a`)' ) t.throws( () => { compileSync('<http://a>') }, /note: to create a link in MDX, use `\[text]\(url\)/, 'should *not* support links (autolink) (`<http://a>` -> error)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('> a')))), '<blockquote>\n<p>a</p>\n</blockquote>', 'should support block quotes (`>` -> `blockquote`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('\\*a*')))), '<p>*a*</p>', 'should support characters (escape) (`\\` -> ``)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('&lt;')))), '<p>&lt;</p>', 'should support character (reference) (`&lt;` -> `<`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('```\na')))), '<pre><code>a\n</code></pre>', 'should support code (fenced) (` ``` ` -> `pre code`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync(' a')))), '<p>a</p>', 'should *not* support code (indented) (`\\ta` -> `p`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('`a`')))), '<p><code>a</code></p>', 'should support code (text) (`` `a` `` -> `code`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('*a*')))), '<p><em>a</em></p>', 'should support emphasis (`*` -> `em`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('a\\\nb')))), '<p>a<br/>\nb</p>', 'should support hard break (escape) (`\\\\\\n` -> `<br>`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('a \nb')))), '<p>a<br/>\nb</p>', 'should support hard break (whitespace) (`\\\\\\n` -> `<br>`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('#')))), '<h1></h1>', 'should support headings (atx) (`#` -> `<h1>`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('a\n=')))), '<h1>a</h1>', 'should support headings (setext) (`=` -> `<h1>`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('1.')))), '<ol>\n<li></li>\n</ol>', 'should support list (ordered) (`1.` -> `<ol><li>`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('*')))), '<ul>\n<li></li>\n</ul>', 'should support list (unordered) (`*` -> `<ul><li>`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('**a**')))), '<p><strong>a</strong></p>', 'should support strong (`**` -> `strong`)' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('***')))), '<hr/>', 'should support thematic break (`***` -> `<hr>`)' ) t.end() }) test('markdown (GFM, with `remark-gfm`)', async (t) => { t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('http://a', {remarkPlugins: [remarkGfm]})) ) ), '<p><a href="http://a">http://a</a></p>', 'should support links (autolink literal) (`http://a` -> `a`)' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('[^1]\n[^1]: a', {remarkPlugins: [remarkGfm]})) ) ), '<p><sup><a href="#user-content-fn-1" id="user-content-fnref-1" data-footnote-ref="true" aria-describedby="footnote-label">1</a></sup></p>\n<section data-footnotes="true" class="footnotes"><h2 id="footnote-label" class="sr-only">Footnotes</h2>\n<ol>\n<li id="user-content-fn-1">\n<p>a <a href="#user-content-fnref-1" data-footnote-backref="true" class="data-footnote-backref" aria-label="Back to content">↩</a></p>\n</li>\n</ol>\n</section>', 'should support footnotes (`[^1]` -> `<sup><a…`)' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('| a |\n| - |', {remarkPlugins: [remarkGfm]})) ) ), '<table><thead><tr><th>a</th></tr></thead></table>', 'should support tables (`| a |` -> `<table>...`)' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('* [x] a\n* [ ] b', {remarkPlugins: [remarkGfm]})) ) ), '<ul class="contains-task-list">\n<li class="task-list-item"><input type="checkbox" disabled="" checked=""/> a</li>\n<li class="task-list-item"><input type="checkbox" disabled=""/> b</li>\n</ul>', 'should support tasklists (`* [x]` -> `input`)' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('~a~', {remarkPlugins: [remarkGfm]})) ) ), '<p><del>a</del></p>', 'should support strikethrough (`~` -> `del`)' ) t.end() }) test('markdown (frontmatter, `remark-frontmatter`)', async (t) => { t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('---\na: b\n---\nc', {remarkPlugins: [remarkFrontmatter]}) ) ) ), '<p>c</p>', 'should support frontmatter (YAML)' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('+++\na: b\n+++\nc', { remarkPlugins: [[remarkFrontmatter, 'toml']] }) ) ) ), '<p>c</p>', 'should support frontmatter (TOML)' ) t.end() }) test('markdown (math, `remark-math`, `rehype-katex`)', async (t) => { t.match( renderToStaticMarkup( React.createElement( await run( compileSync('$C_L$', { remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex] }) ) ) ), /<math/, 'should support math (LaTeX)' ) t.end() }) test('remark-rehype options', async (t) => { t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('Text[^1]\n\n[^1]: Note.', { remarkPlugins: [remarkGfm], remarkRehypeOptions: { footnoteLabel: 'Notes', footnoteBackLabel: 'Back' } }) ) ) ), `<p>Text<sup><a href="#user-content-fn-1" id="user-content-fnref-1" data-footnote-ref="true" aria-describedby="footnote-label">1</a></sup></p> <section data-footnotes="true" class="footnotes"><h2 id="footnote-label" class="sr-only">Notes</h2> <ol> <li id="user-content-fn-1"> <p>Note. <a href="#user-content-fnref-1" data-footnote-backref="true" class="data-footnote-backref" aria-label="Back">↩</a></p> </li> </ol> </section>`, 'should pass options to remark-rehype' ) t.end() }) test('MDX (JSX)', async (t) => { t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('a <s>b</s>'))) ), '<p>a <s>b</s></p>', 'should support JSX (text)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<div>\n b\n</div>'))) ), '<div><p>b</p></div>', 'should support JSX (flow)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<h1>b</h1>'))) ), '<h1>b</h1>', 'should unravel JSX (text) as an only child' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<a>b</a><b>c</b>'))) ), '<a>b</a>\n<b>c</b>', 'should unravel JSX (text) as only children' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<a>b</a>\t<b>c</b>'))) ), '<a>b</a>\n\t\n<b>c</b>', 'should unravel JSX (text) and whitespace as only children' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('{1}')))), '1', 'should unravel expression (text) as an only child' ) t.equal( renderToStaticMarkup(React.createElement(await run(compileSync('{1}{2}')))), '1\n2', 'should unravel expression (text) as only children' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('{1}\n{2}'))) ), '1\n2', 'should unravel expression (text) and whitespace as only children' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('a <>b</>'))) ), '<p>a b</p>', 'should support JSX (text, fragment)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<>\n b\n</>'))) ), '<p>b</p>', 'should support JSX (flow, fragment)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('a <x:y>b</x:y>'))) ), '<p>a <x:y>b</x:y></p>', 'should support JSX (namespace)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('export const a = 1\n\na {a}'))) ), '<p>a 1</p>', 'should support expressions in MDX (text)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('{\n 1 + 1\n}'))) ), '2', 'should support expressions in MDX (flow)' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('{/*!*/}'))) ), '', 'should support empty expressions in MDX' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<x a="1" b:c="1" hidden />'))) ), '<x a="1" b:c="1" hidden=""></x>', 'should support JSX attribute names' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('<x y="1" z=\'w\' style={{color: "red"}} />')) ) ), '<x y="1" z="w" style="color:red"></x>', 'should support JSX attribute values' ) t.equal( renderToStaticMarkup( React.createElement(await run(compileSync('<x {...{a: 1}} />'))) ), '<x a="1"></x>', 'should support JSX spread attributes' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('{<i>the sum of one and one is: {1 + 1}</i>}')) ) ), '<i>the sum of one and one is: 2</i>', 'should support JSX in expressions' ) t.end() }) test('MDX (ESM)', async (t) => { t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('import {Pill} from "./components.js"\n\n<Pill>!</Pill>') ) ) ), '<span style="color:red">!</span>', 'should support importing components w/ ESM' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('import {number} from "./data.js"\n\n{number}')) ) ), '3.14', 'should support importing data w/ ESM' ) t.equal( (await runWhole(compileSync('export const number = Math.PI'))).number, Math.PI, 'should support exporting w/ ESM' ) t.ok( 'a' in (await runWhole(compileSync('export var a'))), 'should support exporting an identifier w/o a value' ) t.equal( ( await runWhole( compileSync('import {object} from "./data.js"\nexport var {a} = object') ) ).a, 1, 'should support exporting an object pattern' ) t.deepEqual( ( await runWhole( compileSync( 'import {object} from "./data.js"\nexport var {a, ...rest} = object' ) ) ).rest, {b: 2}, 'should support exporting a rest element in an object pattern' ) t.deepEqual( ( await runWhole( compileSync( 'import {object} from "./data.js"\nexport var {c = 3} = object' ) ) ).c, 3, 'should support exporting an assignment pattern in an object pattern' ) t.equal( ( await runWhole( compileSync('import {array} from "./data.js"\nexport var [a] = array') ) ).a, 1, 'should support exporting an array pattern' ) t.equal( ( await runWhole( compileSync('export const number = Math.PI\nexport {number as pi}') ) ).pi, Math.PI, 'should support `export as` w/ ESM' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync( 'export default function Layout(props) { return <div {...props} /> }\n\na' ) ) ) ), '<div><p>a</p></div>', 'should support default export to define a layout' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('export {Layout as default} from "./components.js"\n\na') ) ) ), '<div style="color:red"><p>a</p></div>', 'should support default export from a source' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('export {default} from "./components.js"\n\na')) ) ), '<div style="color:red"><p>a</p></div>', 'should support rexporting something as a default export from a source' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('export {default} from "./components.js"\n\na')) ) ), '<div style="color:red"><p>a</p></div>', 'should support rexporting the default export from a source' ) t.equal( renderToStaticMarkup( React.createElement( await run(compileSync('export {default} from "./components.js"\n\na')) ) ), '<div style="color:red"><p>a</p></div>', 'should support rexporting the default export from a source' ) t.equal( renderToStaticMarkup( React.createElement( await run( compileSync('export {default, Pill} from "./components.js"\n\na') ) ) ), '<div style="color:red"><p>a</p></div>', 'should support rexporting the default export, and other things, from a source' ) t.end() }) test('theme-ui', async (t) => { t.match( renderToStaticMarkup( React.createElement( ThemeProvider, {theme: themeUiBaseTheme}, React.createElement(await run(String(compileSync('# h1'))), { components: themeUiComponents }) ) ), /<style data-emotion="css 16uteme">.css-16uteme{color:var\(--theme-ui-colors-text\);font-family:inherit;line-height:1.125;font-weight:700;font-size:32px;}<\/style><h1 class="css-16uteme">h1<\/h1>/, 'should work' ) t.end() }) /** * * @param {VFileCompatible} input * @return {Promise<MDXContent>} */ async function run(input) { return (await runWhole(input)).default } /** * * @param {VFileCompatible} input * @return {Promise<MDXModule>} */ async function runWhole(input) { const name = 'fixture-' + nanoid().toLowerCase() + '.js' const fp = path.join('test', 'context', name) await fs.writeFile(fp, String(input)) try { /** @type {MDXModule} */ return await import('./context/' + name) } finally { // This is not a bug: the `finally` runs after the whole `try` block, but // before the `return`. await fs.unlink(fp) } }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/esbuild.js
JavaScript
/** * @typedef {import('esbuild').BuildFailure} BuildFailure * @typedef {import('esbuild').Message} Message * @typedef {import('unist').Parent} Parent * @typedef {import('vfile').VFile} VFile * @typedef {import('mdx/types').MDXContent} MDXContent */ import {promises as fs} from 'node:fs' import path from 'node:path' import process from 'node:process' import test from 'tape' import esbuild from 'esbuild' import React from 'react' import {renderToStaticMarkup} from 'react-dom/server' import esbuildXdm from '../esbuild.js' test('xdm (esbuild)', async (t) => { const base = path.resolve(path.join('test', 'context')) // MDX. await fs.writeFile( path.join(base, 'esbuild.mdx'), 'export const Message = () => <>World!</>\n\n# Hello, <Message />' ) await esbuild.build({ bundle: true, define: {'process.env.NODE_ENV': '"development"'}, entryPoints: [path.join(base, 'esbuild.mdx')], outfile: path.join(base, 'esbuild.js'), format: 'esm', plugins: [esbuildXdm()] }) /** @type {MDXContent} */ let Content = /* @ts-expect-error file is dynamically generated */ (await import('./context/esbuild.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>Hello, World!</h1>', 'should compile' ) await fs.unlink(path.join(base, 'esbuild.mdx')) await fs.unlink(path.join(base, 'esbuild.js')) // Resolve directory. await fs.writeFile( path.join(base, 'esbuild-resolve.mdx'), 'import Content from "./folder/file.mdx"\n\n<Content/>' ) await fs.mkdir(path.join(base, 'folder')) await fs.writeFile( path.join(base, 'folder', 'file.mdx'), 'import {data} from "./file.js"\n\n{data}' ) await fs.writeFile( path.join(base, 'folder', 'file.js'), 'export const data = 0.1' ) await esbuild.build({ bundle: true, define: {'process.env.NODE_ENV': '"development"'}, entryPoints: [path.join(base, 'esbuild-resolve.mdx')], outfile: path.join(base, 'esbuild-resolve.js'), format: 'esm', plugins: [esbuildXdm()] }) /** @type {MDXContent} */ Content = /* @ts-expect-error file is dynamically generated */ (await import('./context/esbuild-resolve.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '0.1', 'should compile' ) await fs.unlink(path.join(base, 'esbuild-resolve.mdx')) await fs.unlink(path.join(base, 'esbuild-resolve.js')) await fs.rmdir(path.join(base, 'folder'), {recursive: true}) // Markdown. await fs.writeFile(path.join(base, 'esbuild.md'), '\ta') await esbuild.build({ bundle: true, define: {'process.env.NODE_ENV': '"development"'}, entryPoints: [path.join(base, 'esbuild.md')], outfile: path.join(base, 'esbuild-md.js'), format: 'esm', plugins: [esbuildXdm()] }) Content = /* @ts-expect-error file is dynamically generated */ (await import('./context/esbuild-md.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '<pre><code>a\n</code></pre>', 'should compile `.md`' ) await fs.unlink(path.join(base, 'esbuild.md')) await fs.unlink(path.join(base, 'esbuild-md.js')) // `.md` as MDX extension. await fs.writeFile(path.join(base, 'esbuild.md'), '\ta') await esbuild.build({ bundle: true, define: {'process.env.NODE_ENV': '"development"'}, entryPoints: [path.join(base, 'esbuild.md')], outfile: path.join(base, 'esbuild-md-as-mdx.js'), format: 'esm', plugins: [esbuildXdm({mdExtensions: [], mdxExtensions: ['.md']})] }) Content = /* @ts-expect-error file is dynamically generated */ (await import('./context/esbuild-md-as-mdx.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '<p>a</p>', 'should compile `.md` as MDX w/ configuration' ) await fs.unlink(path.join(base, 'esbuild.md')) await fs.unlink(path.join(base, 'esbuild-md-as-mdx.js')) // File not in `extnames`: await fs.writeFile(path.join(base, 'esbuild.md'), 'a') await fs.writeFile(path.join(base, 'esbuild.mdx'), 'a') console.log('\nnote: the following error is expected!\n') try { await esbuild.build({ entryPoints: [path.join(base, 'esbuild.md')], outfile: path.join(base, 'esbuild-md-as-mdx.js'), plugins: [esbuildXdm({format: 'mdx'})] }) t.fail() } catch (error) { t.match( String(error), /No loader is configured for "\.md" files/, 'should not handle `.md` files w/ `format: mdx`' ) } console.log('\nnote: the following error is expected!\n') try { await esbuild.build({ entryPoints: [path.join(base, 'esbuild.mdx')], outfile: path.join(base, 'esbuild-md-as-mdx.js'), plugins: [esbuildXdm({format: 'md'})] }) t.fail() } catch (error) { t.match( String(error), /No loader is configured for "\.mdx" files/, 'should not handle `.mdx` files w/ `format: md`' ) } await fs.unlink(path.join(base, 'esbuild.md')) await fs.unlink(path.join(base, 'esbuild.mdx')) console.log('\nnote: the following errors and warnings are expected!\n') await fs.writeFile( path.join(base, 'esbuild-broken.mdx'), 'asd <https://example.com>?' ) try { await esbuild.build({ entryPoints: [path.join(base, 'esbuild-broken.mdx')], outfile: path.join(base, 'esbuild.js'), plugins: [esbuildXdm()] }) t.fail('esbuild should throw') } catch (error) { const exception = /** @type {BuildFailure} */ (error) const message = exception.errors[0] delete message.detail t.deepEqual( message, { location: { column: 11, file: 'test/context/esbuild-broken.mdx', length: 1, line: 1, lineText: 'asd <https://example.com>?', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: 'Unexpected character `/` (U+002F) before local name, expected a character that can start a name, such as a letter, `$`, or `_` (note: to create a link in MDX, use `[text](url)`)' }, 'should pass errors' ) } await fs.unlink(path.join(base, 'esbuild-broken.mdx')) await fs.writeFile( path.join(base, 'esbuild-warnings.mdx'), 'export const Message = () => <>World!</>\n\n# Hello, <Message />' ) try { await esbuild.build({ entryPoints: [path.join(base, 'esbuild-warnings.mdx')], outfile: path.join(base, 'esbuild-warnings.js'), format: 'esm', plugins: [ esbuildXdm({ rehypePlugins: [ function () { return transform /** * * @param {Parent} tree * @param {VFile} file */ function transform(tree, file) { file.message('1') file.message('2', tree.children[1]) // EOL between both, no position. file.message('3', tree) file.message('4', tree.children[0]) // Export // @ts-expect-error: fine. file.message('5', tree.children[2].children[0]) // Text in heading // @ts-expect-error: fine. file.message('6', tree.children[2].children[1]) // Expression in heading // @ts-expect-error: fine. file.message('7', tree.children[2].position.end).fatal = true // End of heading } } ] }) ] }) t.fail('esbuild should throw') } catch (error) { /** @type {BuildFailure} */ const result = JSON.parse(JSON.stringify(error)) for (const message of [...result.errors, ...result.warnings]) { delete message.detail } t.deepEqual( result, { errors: [ { location: { column: 20, file: 'test/context/esbuild-warnings.mdx', length: 1, line: 3, lineText: '# Hello, <Message />', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: '7' } ], warnings: [ { location: { column: 0, file: 'test/context/esbuild-warnings.mdx', length: 0, line: 0, lineText: 'export const Message = () => <>World!</>', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: '1' }, { location: { column: 0, file: 'test/context/esbuild-warnings.mdx', length: 0, line: 0, lineText: 'export const Message = () => <>World!</>', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: '2' }, { location: { column: 0, file: 'test/context/esbuild-warnings.mdx', length: 40, line: 1, lineText: 'export const Message = () => <>World!</>', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: '3' }, { location: { column: 0, file: 'test/context/esbuild-warnings.mdx', length: 40, line: 1, lineText: 'export const Message = () => <>World!</>', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: '4' }, { location: { column: 2, file: 'test/context/esbuild-warnings.mdx', length: 7, line: 3, lineText: '# Hello, <Message />', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: '5' }, { location: { column: 9, file: 'test/context/esbuild-warnings.mdx', length: 11, line: 3, lineText: '# Hello, <Message />', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: '6' } ] }, 'should pass warnings' ) } await fs.unlink(path.join(base, 'esbuild-warnings.mdx')) console.log('\nnote: the preceding errors and warnings are expected!\n') await fs.writeFile(path.join(base, 'esbuild-plugin-crash.mdx'), '# hi') try { await esbuild.build({ entryPoints: [path.join(base, 'esbuild-plugin-crash.mdx')], outfile: path.join(base, 'esbuild-plugin-crash.js'), format: 'esm', plugins: [ esbuildXdm({ rehypePlugins: [ function () { return () => { throw new Error('Something went wrong') } } ] }) ] }) t.fail('esbuild should throw') } catch (error) { /** @type {BuildFailure} */ const result = JSON.parse(JSON.stringify(error)) for (const message of [...result.errors, ...result.warnings]) { delete message.detail message.text = message.text.split('\n')[0] } t.deepEqual( result, { errors: [ { location: { column: 0, file: 'test/context/esbuild-plugin-crash.mdx', length: 0, line: 0, lineText: '# hi', namespace: 'file', suggestion: '' }, notes: [], pluginName: 'esbuild-xdm', text: 'Error: Something went wrong' } ], warnings: [] }, 'should pass errors' ) } await fs.unlink(path.join(base, 'esbuild-plugin-crash.mdx')) console.log('\nnote: the preceding errors and warnings are expected!\n') /** @type {(contents: string) => import('esbuild').Plugin} */ const inlinePlugin = (contents) => ({ name: 'inline plugin', setup(build) { build.onResolve({filter: /index\.mdx/}, () => ({ path: path.join(process.cwd(), 'index.mdx'), pluginData: {contents} })) } }) await esbuild.build({ entryPoints: [path.join(process.cwd(), 'index.mdx')], plugins: [inlinePlugin(`# Test`), esbuildXdm()], define: {'process.env.NODE_ENV': '"development"'}, format: 'esm', bundle: true, outfile: path.join(base, 'esbuild-compile-from-memory.js') }) Content = /** @ts-expect-error file is dynamically generated */ (await import('./context/esbuild-compile-from-memory.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>Test</h1>', 'should compile from `pluginData.content`' ) await fs.unlink(path.join(base, 'esbuild-compile-from-memory.js')) await esbuild.build({ entryPoints: [path.join(process.cwd(), 'index.mdx')], plugins: [inlinePlugin(``), esbuildXdm()], define: {'process.env.NODE_ENV': '"development"'}, format: 'esm', bundle: true, outfile: path.join(base, 'esbuild-compile-from-memory-empty.js') }) Content = /** @ts-expect-error file is dynamically generated */ (await import('./context/esbuild-compile-from-memory-empty.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '', 'should compile from `pluginData.content` when an empty string is passed' ) await fs.unlink(path.join(base, 'esbuild-compile-from-memory-empty.js')) // Remote markdown. await fs.writeFile( path.join(base, 'esbuild-with-remote-md.mdx'), 'import Content from "https://raw.githubusercontent.com/wooorm/xdm/main/test/files/md-file.md"\n\n<Content />' ) await esbuild.build({ bundle: true, define: {'process.env.NODE_ENV': '"development"'}, entryPoints: [path.join(base, 'esbuild-with-remote-md.mdx')], outfile: path.join(base, 'esbuild-with-remote-md.js'), format: 'esm', plugins: [esbuildXdm({allowDangerousRemoteMdx: true})] }) Content = /* @ts-expect-error file is dynamically generated */ (await import('./context/esbuild-with-remote-md.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '<p>Some content.</p>', 'should compile remote markdown files w/ `allowDangerousRemoteMdx`' ) await fs.unlink(path.join(base, 'esbuild-with-remote-md.mdx')) await fs.unlink(path.join(base, 'esbuild-with-remote-md.js')) // Remote MDX importing more markdown. await fs.writeFile( path.join(base, 'esbuild-with-remote-mdx.mdx'), 'import Content from "https://raw.githubusercontent.com/wooorm/xdm/main/test/files/mdx-file-importing-markdown.mdx"\n\n<Content />' ) await esbuild.build({ bundle: true, define: {'process.env.NODE_ENV': '"development"'}, entryPoints: [path.join(base, 'esbuild-with-remote-mdx.mdx')], outfile: path.join(base, 'esbuild-with-remote-mdx.js'), format: 'esm', plugins: [esbuildXdm({allowDangerousRemoteMdx: true})] }) Content = /* @ts-expect-error file is dynamically generated */ (await import('./context/esbuild-with-remote-mdx.js')).default // type-coverage:ignore-line t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>heading</h1>\n<p>A <span style="color:red">little pill</span>.</p>\n<p>Some content.</p>', 'should compile remote MD, MDX, and JS files w/ `allowDangerousRemoteMdx`' ) await fs.unlink(path.join(base, 'esbuild-with-remote-mdx.mdx')) await fs.unlink(path.join(base, 'esbuild-with-remote-mdx.js')) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/esm-loader.js
JavaScript
/** * @typedef {import('mdx/types').MDXContent} MDXContent */ import path from 'node:path' import {promises as fs} from 'node:fs' import test from 'tape' import React from 'react' import {renderToStaticMarkup} from 'react-dom/server' test('xdm (ESM loader)', async (t) => { const base = path.resolve(path.join('test', 'context')) await fs.writeFile( path.join(base, 'esm-loader.mdx'), 'export const Message = () => <>World!</>\n\n# Hello, <Message />' ) /** @type {MDXContent} */ let Content try { Content = (await import('./context/esm-loader.mdx')).default // type-coverage:ignore-line } catch (error) { const exception = /** @type {NodeJS.ErrnoException} */ (error) if (exception.code === 'ERR_UNKNOWN_FILE_EXTENSION') { await fs.unlink(path.join(base, 'esm-loader.mdx')) throw new Error( 'Please run Node with `--experimental-loader=./test/react-18-esm-loader.js` to test the ESM loader' ) } throw error } t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>Hello, World!</h1>', 'should compile' ) await fs.unlink(path.join(base, 'esm-loader.mdx')) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/evaluate.js
JavaScript
import * as provider from '@mdx-js/react' import React from 'react' import * as runtime from 'react/jsx-runtime' import {renderToStaticMarkup} from 'react-dom/server' import test from 'tape' import {evaluate, evaluateSync, compile} from '../index.js' test('xdm (evaluate)', async (t) => { t.throws( () => { // @ts-expect-error evaluateSync('a') }, /Expected `Fragment` given to `evaluate`/, 'should throw on missing `Fragment`' ) t.throws( () => { // @ts-expect-error evaluateSync('a', {Fragment: runtime.Fragment}) }, /Expected `jsx` given to `evaluate`/, 'should throw on missing `jsx`' ) t.throws( () => { // @ts-expect-error evaluateSync('a', {Fragment: runtime.Fragment, jsx: runtime.jsx}) }, /Expected `jsxs` given to `evaluate`/, 'should throw on missing `jsxs`' ) t.equal( renderToStaticMarkup( // @ts-expect-error runtime.js does not have a typing React.createElement((await evaluate('# hi!', runtime)).default) ), '<h1>hi!</h1>', 'should evaluate' ) t.equal( renderToStaticMarkup( // @ts-expect-error runtime.js does not have a typing React.createElement(evaluateSync('# hi!', runtime).default) ), '<h1>hi!</h1>', 'should evaluate (sync)' ) t.equal( renderToStaticMarkup( React.createElement( ( await evaluate( 'import {number} from "./context/data.js"\n\n{number}', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).default ) ), '3.14', 'should support an `import` of a relative url w/ `useDynamicImport`' ) t.equal( renderToStaticMarkup( React.createElement( ( await evaluate( 'import {number} from "' + new URL('context/data.js', import.meta.url) + '"\n\n{number}', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).default ) ), '3.14', 'should support an `import` of a full url w/ `useDynamicImport`' ) t.match( String( await compile('import "a"', { outputFormat: 'function-body', useDynamicImport: true, ...runtime }) ), /\nawait import\("a"\);?\n/, 'should support an `import` w/o specifiers w/ `useDynamicImport`' ) t.match( String( await compile('import {} from "a"', { outputFormat: 'function-body', useDynamicImport: true, ...runtime }) ), /\nawait import\("a"\);?\n/, 'should support an `import` w/ 0 specifiers w/ `useDynamicImport`' ) t.match( renderToStaticMarkup( React.createElement( ( await evaluate( 'import * as x from "./context/components.js"\n\n<x.Pill>Hi!</x.Pill>', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).default ) ), /<span style="color:red">Hi!<\/span>/, 'should support a namespace import w/ `useDynamicImport`' ) t.match( renderToStaticMarkup( React.createElement( ( await evaluate( 'import x from "theme-ui"\n\n<x.Text>Hi!</x.Text>', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).default ) ), /<span class="css-\w+">Hi!<\/span>/, 'should support an import default of a bare specifier w/ `useDynamicImport`' ) t.match( renderToStaticMarkup( React.createElement( ( await evaluate( 'import * as x from "theme-ui"\n\n<x.Text>Hi!</x.Text>', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).default ) ), /<span class="css-\w+">Hi!<\/span>/, 'should support a namespace import and a bare specifier w/ `useDynamicImport`' ) // @ts-expect-error runtime.js does not have a typing let mod = await evaluate('export const a = 1\n\n{a}', runtime) t.equal( renderToStaticMarkup(React.createElement(mod.default)), '1', 'should support an `export` (1)' ) t.equal(mod.a, 1, 'should support an `export` (2)') // @ts-expect-error runtime.js does not have a typing mod = await evaluate('export function a() { return 1 }\n\n{a()}', runtime) t.equal( renderToStaticMarkup(React.createElement(mod.default)), '1', 'should support an `export function` (1)' ) if (typeof mod.a !== 'function') throw new TypeError('missing function') t.equal(mod.a(), 1, 'should support an `export function` (2)') mod = await evaluate( 'export class A { constructor() { this.b = 1 } }\n\n{new A().b}', // @ts-expect-error runtime.js does not have a typing runtime ) t.equal( renderToStaticMarkup(React.createElement(mod.default)), '1', 'should support an `export class` (1)' ) // @ts-expect-error TODO figure out how to narrow class type in JSDoc typescript t.equal(new mod.A().b, 1, 'should support an `export class` (2)') // @ts-expect-error runtime.js does not have a typing mod = await evaluate('export const a = 1\nexport {a as b}\n\n{a}', runtime) t.equal( renderToStaticMarkup(React.createElement(mod.default)), '1', 'should support an `export as` (1)' ) t.equal(mod.a, 1, 'should support an `export as` (2)') t.equal(mod.b, 1, 'should support an `export as` (3)') t.equal( renderToStaticMarkup( React.createElement( ( await evaluate( 'export default function Layout({components, ...props}) { return <section {...props} /> }\n\na', // @ts-expect-error runtime.js does not have a typing runtime ) ).default ) ), '<section><p>a</p></section>', 'should support an `export default`' ) t.throws( () => { // @ts-expect-error runtime.js does not have a typing evaluateSync('export {a} from "b"', runtime) }, /Cannot use `import` or `export … from` in `evaluate` \(outputting a function body\) by default/, 'should throw on an export from' ) t.equal( ( await evaluate( 'export {number} from "./context/data.js"', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).number, 3.14, 'should support an `export from` w/ `useDynamicImport`' ) t.equal( ( await evaluate( 'import {number} from "./context/data.js"\nexport {number}', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).number, 3.14, 'should support an `export` w/ `useDynamicImport`' ) t.equal( ( await evaluate( 'export {number as data} from "./context/data.js"', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).data, 3.14, 'should support an `export as from` w/ `useDynamicImport`' ) t.equal( ( await evaluate( 'export {default as data} from "./context/data.js"', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} ) ).data, 6.28, 'should support an `export default as from` w/ `useDynamicImport`' ) t.deepEqual( { ...(await evaluate( 'export * from "./context/data.js"', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} )), default: undefined }, {array: [1, 2], default: undefined, number: 3.14, object: {a: 1, b: 2}}, 'should support an `export all from` w/ `useDynamicImport`' ) // I’m not sure if this makes sense, but it is how Node works. t.deepEqual( { ...(await evaluate( 'export {default as number} from "./context/data.js"\nexport * from "./context/data.js"', // @ts-expect-error runtime.js does not have a typing {baseUrl: import.meta.url, useDynamicImport: true, ...runtime} )), default: undefined }, {array: [1, 2], default: undefined, number: 6.28, object: {a: 1, b: 2}}, 'should support an `export all from`, but prefer explicit exports, w/ `useDynamicImport`' ) t.throws( () => { // @ts-expect-error runtime.js does not have a typing evaluateSync('export * from "a"', runtime) }, /Cannot use `import` or `export … from` in `evaluate` \(outputting a function body\) by default/, 'should throw on an export all from' ) t.throws( () => { // @ts-expect-error runtime.js does not have a typing evaluateSync('import {a} from "b"', runtime) }, /Cannot use `import` or `export … from` in `evaluate` \(outputting a function body\) by default/, 'should throw on an import' ) t.throws( () => { // @ts-expect-error runtime.js does not have a typing evaluateSync('import a from "b"', runtime) }, /Cannot use `import` or `export … from` in `evaluate` \(outputting a function body\) by default/, 'should throw on an import default' ) t.equal( renderToStaticMarkup( // @ts-expect-error runtime.js does not have a typing React.createElement((await evaluate('<X/>', runtime)).default, { components: { // @ts-expect-error: React and Preact interfering. X() { return React.createElement('span', {}, '!') } } }) ), '<span>!</span>', 'should support a given components' ) t.equal( renderToStaticMarkup( React.createElement( provider.MDXProvider, { components: { // @ts-expect-error: React and Preact interferring. X() { return React.createElement('span', {}, '!') } } }, React.createElement( // @ts-expect-error runtime.js does not have a typing (await evaluate('<X/>', {...runtime, ...provider})).default ) ) ), '<span>!</span>', 'should support a provider w/ `useMDXComponents`' ) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/index.js
JavaScript
import './babel.js' import './core.js' import './esbuild.js' import './esm-loader.js' import './evaluate.js' import './rollup.js' import './source-map.js' import './vue.js' // Can’t test webpack on Node 17 for now: // <https://github.com/webpack/webpack/issues/14532> // import './webpack.js'
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/react-18-esm-loader.js
JavaScript
import {createLoader} from '../esm-loader.js' // Load is for Node 17+, the rest for 12, 14, 16. const {load, getFormat, transformSource} = createLoader({ fixRuntimeWithoutExportMap: false }) export {load, getFormat, transformSource}
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/register.cjs
JavaScript
/** * @typedef {import('mdx/types').MDXContent} MDXContent */ 'use strict' const path = require('path') const fs = require('fs').promises const test = require('tape') const React = require('react') const {renderToStaticMarkup} = require('react-dom/server') require('../register.cjs') test('xdm (register)', async (t) => { const base = path.resolve(path.join('test', 'context')) await fs.writeFile( path.join(base, 'register.mdx'), 'export const Message = () => <>World!</>\n\n# Hello, <Message />' ) // OMG, it works! const Content = /** @type {MDXContent} */ ( /* @ts-expect-error file is dynamically generated */ require('./context/register.mdx') // type-coverage:ignore-line ) t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>Hello, World!</h1>', 'should compile' ) await fs.unlink(path.join(base, 'register.mdx')) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/rollup.js
JavaScript
/** * @typedef {import('mdx/types').MDXContent} MDXContent */ import path from 'node:path' import {promises as fs} from 'node:fs' import test from 'tape' import {rollup} from 'rollup' import React from 'react' import {renderToStaticMarkup} from 'react-dom/server' import rollupXdm from '../rollup.js' test('xdm (rollup)', async (t) => { const base = path.resolve(path.join('test', 'context')) await fs.writeFile( path.join(base, 'rollup.mdx'), 'export const Message = () => <>World!</>\n\n# Hello, <Message />' ) const bundle = await rollup({ input: path.join(base, 'rollup.mdx'), external: ['react/jsx-runtime'], plugins: [rollupXdm()] }) await fs.writeFile( path.join(base, 'rollup.js'), ( await bundle.generate({format: 'es'}) ).output[0].code ) const Content = /** @type {MDXContent} */ ( /* @ts-expect-error file is dynamically generated */ (await import('./context/rollup.js')).default // type-coverage:ignore-line ) t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>Hello, World!</h1>', 'should compile' ) await fs.unlink(path.join(base, 'rollup.mdx')) await fs.unlink(path.join(base, 'rollup.js')) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/source-map.js
JavaScript
/** * @typedef {import('mdx/types').MDXContent} MDXContent */ import {promises as fs} from 'node:fs' import path from 'node:path' import {Buffer} from 'node:buffer' import React from 'react' import {renderToStaticMarkup} from 'react-dom/server' import {SourceMapGenerator} from 'source-map' import test from 'tape' import {compile} from '../index.js' // Note: Node has an experimental `--enable-source-maps` flag, but most of V8 // doesn’t seem to support it. // So instead use a userland module. import 'source-map-support/register.js' test('xdm (source maps)', async (t) => { const base = path.resolve(path.join('test', 'context')) const file = await compile( ['export function Component() {', ' a()', '}', '', '<Component />'].join( '\n' ), {SourceMapGenerator} ) file.value += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + Buffer.from(JSON.stringify(file.map)).toString('base64') + '\n' await fs.writeFile(path.join(base, 'sourcemap.js'), String(file)) const Content = /** @type {MDXContent} */ ( /* @ts-expect-error file is dynamically generated */ (await import('./context/sourcemap.js')).default // type-coverage:ignore-line ) try { renderToStaticMarkup(React.createElement(Content)) t.fail() } catch (error) { const exception = /** @type {Error} */ (error) const match = /at Component \(file:([^)]+)\)/.exec(String(exception.stack)) const place = path.posix.join(...base.split(path.sep), 'unknown.mdx') + ':2:3' t.equal( match && match[1].slice(-place.length), place, 'should support source maps' ) } await fs.unlink(path.join(base, 'sourcemap.js')) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/vue.js
JavaScript
/** * @typedef {import('vue').SetupContext} SetupContext * @typedef {import('mdx/types').MDXContent} MDXContent */ import path from 'node:path' import {promises as fs} from 'node:fs' import test from 'tape' import {transformAsync as babel} from '@babel/core' import * as vue from 'vue' import {renderToString} from '@vue/server-renderer' import {compile} from '../index.js' test('xdm (vue)', async (t) => { const base = path.resolve(path.join('test', 'context')) const jsx = String( await compile( 'export const C = () => <>c</>\n\n*a*, **b**, <C />, and <D />', {jsx: true} ) ) const fileResult = await babel(jsx, {plugins: ['@vue/babel-plugin-jsx']}) let js = (fileResult || {code: null}).code || '' // Vue used to be ESM, but it recently published a minor/patch w/o that. js = js.replace( /import {[^}]+} from "vue";/, 'import * as vue from "vue"; const {isVNode: _isVNode, createVNode: _createVNode, createTextVNode: _createTextVNode, Fragment: _Fragment} = vue' ) await fs.writeFile(path.join(base, 'vue.js'), js) const Content = /** @type {MDXContent} */ ( /* @ts-expect-error file is dynamically generated */ (await import('./context/vue.js')).default // type-coverage:ignore-line ) const result = await renderToString( vue.createSSRApp({ // App components. components: {Content}, template: '<Content :components="mdxComponents" />', data() { return { mdxComponents: { em: /** * @param {unknown} _ * @param {SetupContext} context * */ (_, context) => vue.h('i', context.attrs, context.slots), D: () => '<3' } } } }) ) t.equal( // Remove SSR comments used to hydrate (I guess). result.replace(/<!--[[\]]-->/g, ''), '<p><i>a</i>, <strong>b</strong>, c, and &lt;3</p>', 'should compile' ) await fs.unlink(path.join(base, 'vue.js')) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
test/webpack.js
JavaScript
/** * @typedef {import('mdx/types').MDXContent} MDXContent */ import {promisify} from 'node:util' import path from 'node:path' import {promises as fs} from 'node:fs' import test from 'tape' import webpack from 'webpack' import React from 'react' import {renderToStaticMarkup} from 'react-dom/server' test('xdm (webpack)', async (t) => { const base = path.resolve(path.join('test', 'context')) await fs.writeFile( path.join(base, 'webpack.mdx'), 'export const Message = () => <>World!</>\n\n# Hello, <Message />' ) await promisify(webpack)({ // @ts-expect-error context does not exist on the webpack options type context: base, entry: './webpack.mdx', mode: 'none', module: {rules: [{test: /\.mdx$/, use: [path.resolve('webpack.cjs')]}]}, output: {path: base, filename: 'webpack.cjs', libraryTarget: 'commonjs'} }) // One for ESM loading CJS, one for webpack. const Content = /** @type {MDXContent} */ ( /* @ts-expect-error file is dynamically generated */ (await import('./context/webpack.cjs')).default.default // type-coverage:ignore-line ) t.equal( renderToStaticMarkup(React.createElement(Content)), '<h1>Hello, World!</h1>', 'should compile' ) await fs.unlink(path.join(base, 'webpack.mdx')) await fs.unlink(path.join(base, 'webpack.cjs')) t.end() })
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
webpack.cjs
JavaScript
'use strict' /** * Webpack loader * * @remarks * To do: once webpack supports ESM loaders, remove this wrapper. * * @param {string} code */ module.exports = function (code) { const callback = this.async() // Note that `import()` caches, so this should be fast enough. import('./lib/integration/webpack.js').then((module) => module.loader.call(this, code, callback) ) }
wooorm/xdm
597
Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
wooorm
Titus
schema.graphql
GraphQL
type Account @entity { id: ID! address: String } type Nominator @entity { id: ID! stash: String currentValidators: [ValidatorJSON] submittedIn: BigInt bond: BigInt } type NominatorJSON @jsonField { stash: String bond: BigInt } type Validator @entity{ id: ID! stash: String selfStake: BigInt activeStake: BigInt inactiveStake: BigInt totalStake: BigInt # A list of nominators whose stake is actively on the given validator activeNominators: [NominatorJSON] # A list of nominators whose stake is not actively on the given validator inactiveNominators: [NominatorJSON] # A list of all nomiantors, both active and inactive allNominators: [NominatorJSON] nominations: [ValidatorNomination] @derivedFrom(field: "validator") } type ValidatorJSON @jsonField { stash: String } type ValidatorNomination @entity { id: ID! extrinsicId: String blockNumber: BigInt totalValidatorsNominated: BigInt bond: BigInt nominator: Nominator validator: Validator nomination: Nomination } type Nomination @entity { id: ID! nominator: Nominator blockNumber: BigInt validatorNominations: [ValidatorNomination!] @derivedFrom(field: "nomination") }
wpank/subql
2
TypeScript
wpank
Will
src/index.ts
TypeScript
//Exports all handler functions export * from './mappings/Nominate' import "@polkadot/api-augment"
wpank/subql
2
TypeScript
wpank
Will
src/mappings/Nominate.ts
TypeScript
import { SubstrateExtrinsic } from '@subql/types'; import {Nomination, Nominator, Validator, ValidatorNomination} from "../types"; const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); const { hexToU8a, isHex } = require('@polkadot/util'); // Process a staking.nominate transaction export async function handleNominate(extrinsic: SubstrateExtrinsic): Promise<void> { // Get the extrinsic hash and block number const extrinsicHash = extrinsic.block.block.header.hash.toString(); const blockNumber = extrinsic.block.block.header.number.toNumber() // A staking.nominate transaction is initiated from a controller account // get the controller and the nomination targets //@ts-ignore const { signer, method: {args}} = extrinsic.extrinsic.toHuman(); const { targets } = args; const controller = signer['Id'] ? signer['Id'] : signer const nominatorTargets = targets.map((target)=>{ const address = target['Id'] ? target['Id'] : target if (isValidAddressPolkadotAddress(address)) return address }) // On Chain Queries // get the stash from the controller, the bonded amount, and the current era const ledgerQuery = (await api.query.staking.ledger(controller)).toJSON() const nominatorStash = ledgerQuery['stash'] const nominatorBond = BigInt(ledgerQuery['total']) const currentEra = (await api.query.staking.currentEra()).toString(); // Update the nominators bond and current nominations and create a `Nomination` record await updateNominator(nominatorStash, nominatorTargets, currentEra, nominatorBond) await createNomination(extrinsicHash, nominatorStash, blockNumber) const nominations = await Promise.all(targets.map(async (target) => { const validatorStash = target["Id"] ? target['Id'] : target await updateValidator(validatorStash, currentEra, nominatorStash, nominatorBond) const validatorNominationId = `${nominatorStash}-${validatorStash}-${blockNumber}` await createValidatorNomination(validatorNominationId, blockNumber, nominatorStash, validatorStash, extrinsicHash, nominatorBond) })); } // Update the nominator entry // - If the nominator doesn't already exist, create a record for them // - Check the diff of whether the nominator removed any previous validators from their nomination // - update the current validator targets, the era the tx was submitted in, and the bond const updateNominator = async(nominatorStash, nominatorTargets, submittedIn, bond) => { await ensureNominator(nominatorStash) const nominator = await Nominator.get(nominatorStash) await updateRemovedValidators(nominator, nominatorTargets) nominator.currentValidators = nominatorTargets nominator.submittedIn = submittedIn nominator.bond = bond await nominator.save() } // Called before updating the current validators of a nominator // This takes the diff of the old validators and new validators // if the validator was removed from the nomination, removes the nominator // from the list of `allNominators` for the validator const updateRemovedValidators = async(nominator, nominatorTargets) => { // Get the current set of validators prior to the nominator tx taking place const prevValidators = nominator.currentValidators // If they had previous validators they were nominating and there was some that were removed, // remove them from the list of `allNominators`, `activeNominators`, and `inactiveNominators` if (prevValidators){ // Find which validators may have been removed from their nominators const removedValidators = prevValidators.filter(x => !nominatorTargets.includes(x)) // const removedValidators = prevValidators.filter(prevVal => !nominatorTargets.some(nomTarget => nomTarget.stash === prevVal.stash)) for (const val of removedValidators) { await ensureValidator(val) const validator = await Validator.get(val) const allNominators = validator.allNominators const activeNominators = validator.activeNominators const inactiveNominators = validator.inactiveNominators if (allNominators){ const index = allNominators.map(nominator => {return nominator.stash}).indexOf(nominator.stash) if (index > -1){ // Remove nominator from list of `allNomiantors` allNominators.splice(index, 1); validator.allNominators = allNominators // Update Total Stake Amounts let totalStake = BigInt(0) for (const nom of allNominators){ // const nominator = await Nominator.get(nom.stash.toString()) if (nom && BigInt(nom.bond) > 0){ totalStake += BigInt(nom.bond) } } validator.totalStake = totalStake } } if (activeNominators){ const index = activeNominators.map(nominator => {return nominator.stash}).indexOf(nominator.stash) if (index > -1){ activeNominators.splice(index, 1); validator.activeNominators = activeNominators } } if (inactiveNominators){ const index = inactiveNominators.map(nominator => {return nominator.stash}).indexOf(nominator.stash) if (index > -1){ // Remove nominator from list of `inactiveValidators` inactiveNominators.splice(index, 1); validator.inactiveNominators = inactiveNominators // Update inactive stake amounts let inactiveStake = BigInt(0) for (const nom of inactiveNominators){ // const nominator = await Nominator.get(nom.stash.toString()) if (nom && BigInt(nom.bond) > 0){ inactiveStake += BigInt(nom.bond) } } validator.inactiveStake = inactiveStake } } await validator.save(); } } } // Update a Validator's list of active and inactive Nominators, as well as totals for active/inactive stake amounts const updateValidator = async(validatorStash, currentEra, nominatorStash, nominatorBond) => { // Get Era Exposure let erasStakers // Prior to runtime 1050, `staking.Stakers` was the storage item if (api.query.staking.stakers){ erasStakers = (await api.query.staking.stakers(validatorStash)); } if (api.query.staking.erasStakers){ erasStakers = (await api.query.staking.erasStakers(currentEra, validatorStash)); } // @ts-ignore const {total, own, others} = erasStakers const activeNominators = others.map((nominator)=> { return {stash: nominator.who.toString(), bond: nominator.value.toString()} }) let validator = await Validator.get(validatorStash); let allNominators if (!validator) { validator = new Validator(validatorStash); validator.stash = validatorStash; allNominators = [{stash: nominatorStash, bond: nominatorBond.toString()}] } else { // The validator was included in a nominators nomination // add the nominator to the list of all nominators if it isn't already there allNominators = validator.allNominators const index = validator.allNominators.map(nominator => {return nominator.stash}).indexOf(nominatorStash) if (index == -1){ allNominators.push({stash: nominatorStash, bond: nominatorBond.toString()}) } } // Inactive nominators are the diff between all nominators and active nominators const inactiveNominators = allNominators.filter(nominator => !activeNominators.some(activeNominator => activeNominator.stash === nominator.stash)) validator.inactiveNominators = inactiveNominators // Total stake is the sum of stake from all nominators, active and inactive let totalStake = BigInt(0) for (const nom of allNominators){ // const nominator = await Nominator.get(nom.stash.toString()) if (nom && BigInt(nom.bond) > 0){ totalStake += BigInt(nom.bond) } } let inactiveStake = BigInt(0) for (const nom of inactiveNominators){ // const nominator = await Nominator.get(nom.stash.toString()) if (nom && BigInt(nom.bond) > 0){ inactiveStake += BigInt(nom.bond) } } validator.totalStake = totalStake validator.activeStake = total validator.selfStake = own validator.inactiveStake = inactiveStake validator.allNominators = allNominators validator.activeNominators = activeNominators await validator.save() } // Create a Nomination record const createNomination = async(extrinsicHash, nominatorStash, blockNumber) => { let nomination = new Nomination(extrinsicHash) // @ts-ignore nomination.nominatorId = nominatorStash.toString(); nomination.blockNumber = blockNumber; await nomination.save() } // Create a `ValidatorNomination` Record const createValidatorNomination = async(id, blockNumber, nominatorStash, validatorStash, extrinsicHash, bond) => { let validatorNomination = await ValidatorNomination.get(id) if (!validatorNomination) { validatorNomination = new ValidatorNomination(id); validatorNomination.blockNumber = blockNumber //@ts-ignore validatorNomination.nominatorId = nominatorStash //@ts-ignore validatorNomination.validatorId = validatorStash //@ts-ignore validatorNomination.nominationId = extrinsicHash validatorNomination.bond = bond await validatorNomination.save() } } // Ensure that a `Validator` record exists, if it doesn't, create it const ensureValidator = async(stash: string): Promise<void> =>{ const validator = await Validator.get(stash) if (!validator){ await new Validator(stash).save(); } } // Ensure that a `Nominator` record exists, if it doesn't, create it const ensureNominator = async(stash: string): Promise<void> => { const nominator = await Nominator.get(stash) if (!nominator){ await new Nominator(stash).save(); } } const isValidAddressPolkadotAddress = (address) => { try { encodeAddress( isHex(address) ? hexToU8a(address) : decodeAddress(address) ); return address.length > 40 } catch (error) { return false; } };
wpank/subql
2
TypeScript
wpank
Will
controllers/activities/create.js
JavaScript
'use strict' const Boom = require('@hapi/boom') const Joi = require('@hapi/joi') module.exports = { description: 'Create a new activity', tags: ['api', 'activity'], handler: async function (request, h) { const userId = request.auth.credentials.id if (request.payload.activity_id) { const alias = await this.db.activities.findOne({ user_id: userId, id: request.payload.activity_id, activity_id: null }) if (!alias) { throw Boom.notFound( `Alias activity ${request.payload.activity_id} does not exist}` ) } } const attrs = { ...request.payload, user_id: userId } const result = await this.db.activities.insert(attrs) return h.response(result).code(201) }, validate: { payload: Joi.object().keys({ name: Joi.string().required(), activity_id: Joi.string().guid(), sets: Joi.any().strip(), comment: Joi.any().strip(), aliases: Joi.any().strip(), suggestions: Joi.any().strip() }) }, response: { modify: true, schema: Joi.object({ user_id: Joi.any().strip() }).unknown() } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/activities/get.js
JavaScript
'use strict' const Boom = require('@hapi/boom') const Joi = require('@hapi/joi') module.exports = { description: 'Get activity by id', tags: ['api', 'activity'], handler: async function (request) { const activity = await this.db.activities.with_alias({ id: request.params.id, user_id: request.auth.credentials.id }) if (!activity) { throw Boom.notFound() } return activity }, validate: { params: Joi.object().keys({ id: Joi.string().guid() }) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/activities/history.js
JavaScript
'use strict' const Boom = require('@hapi/boom') const Joi = require('@hapi/joi') module.exports = { description: 'Get workout history for an activity by id', tags: ['api', 'activity'], handler: async function (request) { const params = { ...request.params, user_id: request.auth.credentials.id } const activity = await this.db.activities.findOne(params) if (!activity) { throw Boom.notFound() } let id = activity.id if (activity.activity_id) { id = activity.activity_id } const historyCount = await this.db.activities.history_count({ id, user_id: request.auth.credentials.id }) /* eslint require-atomic-updates: 0 */ request.totalCount = historyCount.count let { page } = request.query if (page === 0) { page = this.utils.lastPage(historyCount.count, request.query.limit) } if (historyCount.count === 0) { return [] } const query = { ...request.query, page, id, user_id: request.auth.credentials.id } query.page = (query.page - 1) * query.limit const activities = await this.db.activities.history(query) return activities }, validate: { params: Joi.object().keys({ id: Joi.string().guid() }), query: Joi.object().keys({ limit: Joi.number() .default(10) .min(1) .max(100), page: Joi.number() .default(0) .min(0) }) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/activities/list.js
JavaScript
'use strict' const Joi = require('@hapi/joi') module.exports = { description: 'Get activities for logged in user', tags: ['api', 'activity'], handler: async function (request) { const params = { ...request.query, id: request.auth.credentials.id } params.page = (params.page - 1) * params.limit const activityCount = await this.db.activities.for_user_count(params) request.totalCount = activityCount.count const activities = await this.db.activities.for_user(params) return activities }, validate: { query: Joi.object().keys({ limit: Joi.number() .default(10) .min(1) .max(100), page: Joi.number() .default(1) .positive() }) }, response: { modify: true, schema: Joi.array().items( Joi.object({ user_id: Joi.any().strip(), aliases: Joi.array() .items( Joi.object({ user_id: Joi.any().strip() }).unknown() ) .allow(null) }).unknown() ) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/activities/promote.js
JavaScript
'use strict' const Boom = require('@hapi/boom') module.exports = { description: 'Promote an activity to main activity', tags: ['api', 'activity'], handler: async function (request) { const activity = await this.db.activities.findOne({ id: request.params.id, user_id: request.auth.credentials.id }) if (!activity) { throw Boom.notFound() } await this.db.tx(async (tx) => { // Set any current aliases to us await tx.activities.update( { activity_id: activity.activity_id }, { activity_id: activity.id } ) await Promise.all([ // Set our activity_id to null tx.activities.updateOne({ id: activity.id }, { activity_id: null }), // Set old parent's activity_id to us tx.activities.updateOne( { id: activity.activity_id }, { activity_id: activity.id } ) ]) }) const activities = await this.db.activities.with_aliases({ id: request.params.id, user_id: request.auth.credentials.id }) return activities } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/activities/suggest.js
JavaScript
'use strict' const Joi = require('@hapi/joi') module.exports = { description: 'Search activities by name', tags: ['api', 'activity'], handler: async function (request) { const userId = request.auth.credentials.id const activity = await this.db.activities.search_alias({ user_id: userId, name: request.params.name }) if (activity) { return activity } const name = request.params.name.replace(/\s+/g, ' | ').toLowerCase() const suggestions = await this.db.activities.search({ name, user_id: request.auth.credentials.id }) return { suggestions } }, validate: { params: Joi.object().keys({ name: Joi.string().replace(/[^\w' ]/gi, '') }) }, response: { modify: true, schema: Joi.object({ user_id: Joi.any().strip() }).unknown() } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/admin/users/list.js
JavaScript
'use strict' module.exports = { description: 'Get all users', tags: ['admin'], handler: async function () { const result = await this.db.users.summary() return result }, auth: { scope: 'admin' } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/heartbeat.js
JavaScript
'use strict' const Boom = require('@hapi/boom') module.exports = { description: 'Heartbeat', handler: async function (request, h) { const count = await this.db.users.count() // $lab:coverage:off$ if (count.count > -1) { return h.response('ok').type('text/plain') } throw Boom.internal('Heartbeat error') // $lab:coverage:on$ }, auth: false }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/invites/validate.js
JavaScript
'use strict' const Config = require('getconfig') const Boom = require('@hapi/boom') const Joi = require('@hapi/joi') module.exports = { description: 'Check invite validity', tags: ['api', 'user'], handler: async function (request) { const params = { ...request.params, claimed_by: null } const invite = await this.db.invites.findOne(params, ['token']) if (!invite) { throw Boom.notFound() } return invite }, validate: { params: Joi.object().keys({ token: Joi.string().guid() }) }, auth: false, plugins: { 'hapi-rate-limit': Config.inviteValidateRateLimit } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/confirm.js
JavaScript
'use strict' const Boom = require('@hapi/boom') const Joi = require('@hapi/joi') module.exports = { description: 'Confirm email', tags: ['api', 'user'], handler: async function (request) { const validation = await this.db.validations.confirm({ user_id: request.auth.credentials.id, token: request.payload.token }) if (!validation) { throw Boom.notFound('Invalid Token') } await this.db.tx(async (tx) => { await Promise.all([ tx.validations.destroy({ user_id: validation.user_id }), tx.users.updateOne( { id: request.auth.credentials.id }, { validated: true } ) ]) }) const user = await this.db.users.active(request.auth.credentials.email) return user }, validate: { payload: Joi.object().keys({ token: Joi.string() .guid() .required() }) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/delete.js
JavaScript
'use strict' const Joi = require('@hapi/joi') module.exports = { description: 'Delete user', notes: 'The query parameter "confirm" is meant to aid clients in confirming with the end user that they really want to do this', tags: ['user'], handler: async function (request, h) { await this.db.users.destroy({ id: request.auth.credentials.id }) return h.response().code(204) }, validate: { query: Joi.object().keys({ confirm: Joi.boolean() .valid(true) .required() }) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/invites.js
JavaScript
'use strict' const Joi = require('@hapi/joi') module.exports = { description: 'Invites for currently logged in user', tags: ['api', 'user'], handler: function (request) { if (!request.auth.credentials.validated) { return [] } const result = this.db.invites.find({ user_id: request.auth.credentials.id, claimed_by: null }) return result }, response: { modify: true, schema: Joi.array().items( Joi.object({ claimed_by: Joi.any().strip(), user_id: Joi.any().strip() }).unknown() ) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/login.js
JavaScript
'use strict' const Bcrypt = require('bcrypt') const Boom = require('@hapi/boom') const Config = require('getconfig') const Joi = require('@hapi/joi') const JWT = require('jsonwebtoken') module.exports = { description: 'Authenticates a user and returns a JWT', tags: ['api', 'user'], handler: async function (request, h) { request.server.log(['users', 'auth'], `Login: ${request.payload.email}`) const user = await this.db.users.active(request.payload.email) if (!user) { throw Boom.unauthorized() } const { hash } = await this.db.users.findOne({ id: user.id }, ['hash']) const valid = await Bcrypt.compare(request.payload.password, hash) if (!valid) { throw Boom.unauthorized() } user.timestamp = new Date() return h .response({ token: JWT.sign({ ...user }, Config.auth.secret, Config.auth.options) }) .code(201) }, validate: { payload: Joi.object().keys({ email: Joi.string().required(), password: Joi.string() .min(8) .required() }) }, auth: false }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/logout.js
JavaScript
'use strict' module.exports = { description: 'Log the current user out and invalidate all of their tokens', tags: ['api', 'user'], handler: async function (request, h) { await this.db.users.updateOne( { id: request.auth.credentials.id }, { logout: new Date() } ) return h.response().code(204) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/recover.js
JavaScript
'use strict' const Joi = require('@hapi/joi') const AWS = require('../../lib/aws') const Config = require('getconfig') module.exports = { description: 'Request password recovery', tags: ['api', 'user'], handler: async function (request, h) { const existingRecovery = await this.db.recoveries.fresh(request.payload) if (existingRecovery) { return h.response(null).code(202) } const user = await this.db.users.findOne({ email: request.payload.email, validated: true }) if (!user) { return h.response(null).code(202) } const recovery = await this.db.tx(async (tx) => { await tx.recoveries.destroy({ email: request.payload.email }) return tx.recoveries.insert(request.payload) }) const email = { Destination: { ToAddresses: [recovery.email] }, Message: { Body: { Text: { Data: `Here is the link you requested to recover your lift.zone password: ${Config.clientUri}/recover?token=${recovery.token}\n\nIf you did not request this, simply don't click this link.\n\nThis link expires in 3 hours.` }, Html: { Data: `<a href="${Config.clientUri}/recover?token=${recovery.token}">Here</a> is the link you requested to recover your lift.zone password.<br /><br />If you did not request this, simply don't click this link.<br /><br />This link expires in 3 hours.` } }, Subject: { Data: 'Lift zone password recovery' } }, Source: Config.email.from, ReplyToAddresses: [Config.email.from] } // $lab:coverage:off$ if (process.env.NODE_ENV) { try { AWS.sendEmail(email) } catch (err) { request.log(['error', 'user', 'recovery'], err.stack || err) } } // $lab:coverage:on$ request.log(['debug'], recovery.token) // We used to return instantly but since changing to async/await that broke // but it works if we reply at the end and I can't be bothered to // figure out why return h.response(null).code(202) }, validate: { payload: Joi.object().keys({ email: Joi.string() .email() .required() }) }, auth: false }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/reset.js
JavaScript
'use strict' const Bcrypt = require('bcrypt') const Boom = require('@hapi/boom') const Config = require('getconfig') const Joi = require('@hapi/joi') const JWT = require('jsonwebtoken') module.exports = { description: 'Reset password using recovery token', notes: 'Logs out any existing sessions', tags: ['user'], handler: async function (request, h) { const recovery = await this.db.recoveries.findOne({ token: request.payload.token }) if (!recovery) { throw Boom.notFound('Invalid token') } const hash = await Bcrypt.hash(request.payload.password, Config.saltRounds) await this.db.tx(async (tx) => { await Promise.all([ tx.recoveries.destroy({ token: recovery.token }), tx.users.updateOne( { email: recovery.email }, { hash, logout: new Date() } ) ]) }) const user = await this.db.users.active(recovery.email) user.timestamp = new Date() return h .response({ token: JWT.sign({ ...user }, Config.auth.secret, Config.auth.options) }) .code(201) }, validate: { payload: Joi.object().keys({ token: Joi.string() .guid() .required(), password: Joi.string() .min(8, 'utf-8') .required(), passwordConfirm: Joi.any() .valid(Joi.ref('password')) .strip() }) }, auth: false }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/self.js
JavaScript
'use strict' module.exports = { description: 'Currently logged in user', tags: ['api', 'user'], handler: function (request) { const user = request.auth.credentials return user } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/signup.js
JavaScript
'use strict' const Bcrypt = require('bcrypt') const Boom = require('@hapi/boom') const Config = require('getconfig') const JWT = require('jsonwebtoken') const Joi = require('@hapi/joi') module.exports = { description: 'Sign up', tags: ['api', 'user'], handler: async function (request, h) { const invite = await this.db.invites.findOne({ token: request.payload.invite, claimed_by: null }) if (!invite) { throw Boom.notFound('Invalid invite') } const hash = await Bcrypt.hash(request.payload.password, Config.saltRounds) await this.db.tx(async (tx) => { const user = await tx.users.insert({ name: request.payload.name, email: request.payload.email, hash }) for (let i = 0; i < Config.invites.count; ++i) { await tx.invites.insert({ user_id: user.id }) } await tx.invites.update( { token: request.payload.invite }, { claimed_by: user.id } ) }) const user = await this.db.users.active(request.payload.email) user.timestamp = new Date() return h .response({ token: JWT.sign({ ...user }, Config.auth.secret, Config.auth.options) }) .code(201) }, validate: { payload: Joi.object().keys({ invite: Joi.string() .guid() .required(), name: Joi.string().required(), email: Joi.string() .email() .required(), password: Joi.string() .min(8, 'utf-8') .required(), passwordConfirm: Joi.any() .valid(Joi.ref('password')) .strip() }) }, auth: false }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/update.js
JavaScript
'use strict' const Bcrypt = require('bcrypt') const Boom = require('@hapi/boom') const Config = require('getconfig') const Joi = require('@hapi/joi') module.exports = { description: 'Update user info', tags: ['api', 'user'], handler: async function (request) { const credentials = request.auth.credentials const { hash } = await this.db.users.findOne({ id: credentials.id }, [ 'hash' ]) const valid = await Bcrypt.compare(request.payload.currentPassword, hash) if (!valid) { throw Boom.badRequest('Current password does not match') } const attrs = { ...request.payload } if (attrs.email) { attrs.validated = false } if (attrs.newPassword) { attrs.hash = await Bcrypt.hash(attrs.newPassword, Config.saltRounds) } delete attrs.currentPassword delete attrs.newPassword const updatedUser = await this.db.users.updateOne( { id: request.auth.credentials.id }, attrs ) const result = await this.db.users.active(updatedUser.email) return result }, validate: { payload: Joi.object() .keys({ name: Joi.string(), email: Joi.string().email(), currentPassword: Joi.string() .min(8, 'utf-8') .required(), newPassword: Joi.string().min(8, 'utf-8'), confirmPassword: Joi.any() .valid(Joi.ref('newPassword')) .strip(), preferences: Joi.object({ weightUnit: Joi.string().valid('lb', 'kg'), dateFormat: Joi.string(), smartmode: Joi.boolean(), visible: Joi.boolean() }) }) .with('newPassword', 'currentPassword') }, response: { modify: true, schema: Joi.object({ hash: Joi.any().strip() }).unknown() } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/users/validate.js
JavaScript
'use strict' const AWS = require('../../lib/aws') const Config = require('getconfig') module.exports = { description: 'Request email validation', tags: ['api', 'user'], handler: async function (request, h) { const existingValidation = await this.db.validations.fresh({ user_id: request.auth.credentials.id }) if (existingValidation) { return h.response(null).code(202) } const validation = await this.db.validations.insert({ user_id: request.auth.credentials.id }) const email = { Destination: { ToAddresses: [request.auth.credentials.email] }, Message: { Body: { Text: { Data: `Here is the link to validate your lift.zone account: ${Config.clientUri}/validate?token=${validation.token}\n\nOnce validate you will be able to send invites and recover your password should you lose it.\n\nThis link expires in 15 minutes.` }, Html: { Data: `<a href="${Config.clientUri}/validate?token=${validation.token}">Here</a> is the link you requested to recover your lift.zone password.<br /><br />Once validate you will be able to send invites and recover your password should you lose it.<br /><br />This link expires in 15 minutes.` } }, Subject: { Data: 'Lift zone account validation' } }, Source: Config.email.from, ReplyToAddresses: [Config.email.from] } // $lab:coverage:off$ if (process.env.NODE_ENV) { try { AWS.sendEmail(email) } catch (err) { request.log(['error', 'user', 'validate'], err.stack || err) } } // $lab:coverage:on$ request.log(['debug'], validation.token) return h.response(null).code(202) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/workouts/all.js
JavaScript
'use strict' module.exports = { description: 'Get a summary of all of a user\'s workouts', tags: ['api', 'workout'], handler: async function (request) { const result = await this.db.workouts.summary({ user_id: request.auth.credentials.id }) return result } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/workouts/create.js
JavaScript
'use strict' const Boom = require('@hapi/boom') const Utils = require('../../lib/utils') module.exports = { description: 'Create a new workout', tags: ['api', 'workout'], handler: async function (request, h) { const existing = await this.db.workouts.findOne({ date: request.payload.date, user_id: request.auth.credentials.id }) if (existing) { throw Boom.conflict( `There is already a workout for ${request.payload.date}` ) } const attrs = { ...request.payload, user_id: request.auth.credentials.id } const workout = await this.db.workouts.insert(attrs) return h.response(workout).code(201) }, validate: { payload: Utils.workoutValidator } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/workouts/delete.js
JavaScript
'use strict' const Boom = require('@hapi/boom') const Joi = require('@hapi/joi') module.exports = { description: 'Delete a workout', tags: ['api', 'workout'], handler: async function (request, h) { const existing = await this.db.workouts.findOne({ id: request.params.id, user_id: request.auth.credentials.id }) if (!existing) { throw Boom.notFound() } await this.db.workouts.destroy({ id: existing.id }) return h.response().code(204) }, validate: { params: Joi.object().keys({ id: Joi.string().guid() }) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/workouts/get.js
JavaScript
'use strict' const Joi = require('@hapi/joi') const Boom = require('@hapi/boom') module.exports = { description: 'Get a workout by id', tags: ['api', 'workout'], handler: async function (request) { const attrs = { ...request.params, user_id: request.auth.credentials.id } const workout = await this.db.workouts.findOne(attrs) if (!workout) { throw Boom.notFound() } return workout }, validate: { params: Joi.object().keys({ id: Joi.string().guid() }) } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/workouts/public.js
JavaScript
'use strict' const Joi = require('@hapi/joi') const Boom = require('@hapi/boom') module.exports = { description: 'Get a public workout by id', tags: ['api', 'workout'], handler: async function (request) { const workout = await this.db.workouts.public(request.params) if (!workout) { throw Boom.notFound() } return workout }, validate: { params: Joi.object().keys({ id: Joi.string().guid() }) }, auth: false, response: { modify: true, schema: Joi.object({ user_id: Joi.any().strip() }).unknown() } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
controllers/workouts/update.js
JavaScript
'use strict' const Boom = require('@hapi/boom') const Joi = require('@hapi/joi') const Utils = require('../../lib/utils') module.exports = { description: 'Update a new workout', tags: ['api', 'workout'], handler: async function (request) { const existingId = await this.db.workouts.findOne({ id: request.params.id }) if (!existingId) { throw Boom.notFound() } const existingDate = await this.db.workouts.findOne({ date: request.payload.date, user_id: request.auth.credentials.id }) if (existingDate && existingDate.id !== request.params.id) { throw Boom.conflict( `There is already a workout for ${request.payload.date}` ) } const attrs = { ...request.payload } const workout = await this.db.workouts.updateOne( { id: request.params.id }, attrs ) return workout }, validate: { params: Joi.object().keys({ id: Joi.string().guid() }), payload: Utils.workoutValidator } }
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/for_user.sql
SQL
SELECT activities.*, CASE WHEN count(aliases) = 0 THEN '[]'::json ELSE json_agg(aliases) END AS aliases FROM activities LEFT JOIN activities AS aliases on activities.id = aliases.activity_id WHERE activities.user_id = ${id} AND activities.activity_id is null GROUP BY activities.id ORDER BY activities.name LIMIT ${limit} OFFSET ${page}
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/for_user_count.sql
SQL
--- returns: one --- SELECT count(activities.id)::integer as count FROM activities WHERE activities.user_id = ${id} AND activities.activity_id is null
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/history.sql
SQL
SELECT workouts.name as workout_name, to_char(workouts.date, 'YYYY-MM-DD') as workout_date, workout_activities.comment, workout_activities.sets FROM workouts, jsonb_to_recordset(workouts.activities) AS workout_activities(id uuid, comment text, sets jsonb) WHERE workouts.user_id = ${user_id} AND ( workout_activities.id = ${id} OR workout_activities.id in ( SELECT id FROM activities WHERE activity_id = ${id} ) ) ORDER BY workouts.date LIMIT ${limit} OFFSET ${page}
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/history_count.sql
SQL
--- returns: one --- SELECT count(workouts.id)::integer as count FROM workouts, jsonb_to_recordset(workouts.activities) AS workout_activities(id uuid, comment text, sets jsonb) WHERE workouts.user_id = ${user_id} AND ( workout_activities.id = ${id} OR workout_activities.id in ( SELECT id FROM activities WHERE activity_id = ${id} ) )
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/search.sql
SQL
SELECT id, CASE WHEN activity_id IS NULL THEN id ELSE activity_id END as activity_id, name, 1 - ts_rank(to_tsvector('english', name), to_tsquery(${name})) as rank FROM activities WHERE user_id = ${user_id} AND to_tsvector('english', name) @@ to_tsquery(${name}) ORDER BY rank DESC LIMIT 5
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/search_alias.sql
SQL
--- returns: one || none --- SELECT activities.id, activities.activity_id, activities.name, aliases.name AS alias FROM activities LEFT JOIN activities AS aliases on activities.activity_id = aliases.id WHERE activities.user_id = ${user_id} AND activities.name = ${name}
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/with_alias.sql
SQL
--- returns: one || none --- SELECT activities.id, activities.activity_id, activities.name, aliases.name AS alias FROM activities LEFT JOIN activities AS aliases on activities.activity_id = aliases.id WHERE activities.user_id = ${user_id} AND activities.id = ${id}
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/activities/with_aliases.sql
SQL
--- returns: one || none --- SELECT activities.*, CASE WHEN count(aliases) = 0 THEN '[]'::json ELSE json_agg(aliases) END AS aliases FROM activities LEFT JOIN activities AS aliases on activities.id = aliases.activity_id WHERE activities.user_id = ${user_id} AND activities.id = ${id} GROUP BY activities.id
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/recoveries/fresh.sql
SQL
--- returns: one || none --- SELECT * FROM recoveries WHERE email = ${email} AND created_at > now() - interval '3 hours'
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/users/active.sql
SQL
--- returns: one || none --- SELECT users.id, users.name, users.email, users.logout, users.validated, users.scope, users.preferences FROM users WHERE users.active = TRUE AND lower(users.email)=lower($1);
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/users/count.sql
SQL
--- returns: one --- SELECT count(0)::integer as count from users;
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/users/summary.sql
SQL
SELECT users.id, users.name, users.email, users.active, users.validated, (SELECT count(workouts.id)::integer from workouts where workouts.user_id = users.id) as workouts, (SELECT count(activities.id)::integer from activities where activities.user_id = users.id) as activities, (SELECT count(invites.token)::integer from invites where invites.user_id = users.id and invites.claimed_by is null) as invites, (SELECT max(workouts.created_at) from workouts where workouts.user_id = users.id) as last_workout FROM users
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/validations/confirm.sql
SQL
--- returns: one || none --- SELECT * FROM validations WHERE user_id = ${user_id} AND token = ${token} AND created_at > now() - interval '1 day'
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/validations/fresh.sql
SQL
--- returns: one || none --- SELECT * FROM validations WHERE user_id = ${user_id} AND created_at > now() - interval '15 minutes'
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/workouts/public.sql
SQL
--- returns: one || none --- SELECT workouts.*, users.name as user_name FROM workouts JOIN users ON users.id = workouts.user_id WHERE workouts.id = ${id} AND ( ( users.preferences->>'visible' = 'true' AND workouts.visible IS NULL ) OR workouts.visible = true )
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar
db/workouts/summary.sql
SQL
SELECT workouts.id, name, to_char(workouts.date, 'YYYY-MM-DD') as date, jsonb_array_length(workouts.activities) as activities FROM workouts WHERE user_id = ${user_id} GROUP BY workouts.id
wraithgar/api.lift.zone
1
API for lift.zone
JavaScript
wraithgar
Gar