diff --git a/docs/guide/plugins.md b/docs/guide/plugins.md index 92cb65b..cb9b5b4 100644 --- a/docs/guide/plugins.md +++ b/docs/guide/plugins.md @@ -64,6 +64,13 @@ export function pluginCustom(md: MarkdownExit) { Release read the `MarkdownExit` class [properties](/reference/api/Class.MarkdownExit.html#properties) type definition for more details about the available plugin APIs. +### Supporting the Core Entry + +Apps may import from [`markdown-exit/core`](/guide/quick-start.html#core-entry) to leave out linkify-it. To keep your plugin compatible: + +- Use `import type` for types. If your plugin needs runtime values such as `Token`, import them from `markdown-exit/core`, which shares the same classes as `markdown-exit`. Importing `markdown-exit` at runtime adds linkify-it to the bundle of every app that uses your plugin. +- `md.linkify` is `undefined` in the core entry until the app assigns a linkify-it instance. If your plugin accesses `md.linkify`, guard against that or document that the plugin requires linkify-it. + ### Async Render Rules A nice feature of **markdown-exit** is its built-in support for [async rendering](/guide/rendering.html#async-rendering), allowing you to implement async render rules in your plugin. diff --git a/docs/guide/quick-start.md b/docs/guide/quick-start.md index 0695870..fceee5b 100644 --- a/docs/guide/quick-start.md +++ b/docs/guide/quick-start.md @@ -118,3 +118,28 @@ const md = MarkdownExit() // OR with the `new` keyword const md = new MarkdownExit() ``` + +## Core Entry + +`markdown-exit/core` exposes the same API as `markdown-exit`, but leaves out [linkify-it](https://github.com/markdown-it/linkify-it), the library behind the [`linkify`](/reference/api/Interface.MarkdownExitOptions.html#linkify) option. If you never enable `linkify`, import from `markdown-exit/core` to get a smaller bundle: + +```ts +import { createMarkdownExit } from 'markdown-exit/core' + +const md = createMarkdownExit() +md.render('https://example.com') //

https://example.com

+``` + +In the core entry, `md.linkify` is `undefined`. To enable `linkify`, install `linkify-it` and assign an instance yourself: + +```ts +import { LinkifyIt } from 'linkify-it' +import { createMarkdownExit } from 'markdown-exit/core' + +const md = createMarkdownExit({ linkify: true }) +md.linkify = new LinkifyIt() +``` + +> [!WARNING] +> - Plugins that access `md.linkify` (e.g. `md.linkify.set(...)`) throw in the core entry unless you assign a linkify-it instance before calling `md.use()`. +> - If any module in your app imports `markdown-exit` instead of `markdown-exit/core`, linkify-it is bundled anyway, and instances created from `markdown-exit/core` get a linkify-it instance too. diff --git a/packages/markdown-exit/package.json b/packages/markdown-exit/package.json index b955c36..e4f4f96 100644 --- a/packages/markdown-exit/package.json +++ b/packages/markdown-exit/package.json @@ -22,6 +22,7 @@ ], "exports": { ".": "./dist/index.js", + "./core": "./dist/core.js", "./package.json": "./package.json" }, "main": "./dist/index.js", diff --git a/packages/markdown-exit/src/index.core.ts b/packages/markdown-exit/src/index.core.ts new file mode 100644 index 0000000..8cef5ae --- /dev/null +++ b/packages/markdown-exit/src/index.core.ts @@ -0,0 +1,17 @@ +import type { createMarkdownExit } from './core' +import { callable } from './common/utils' +import { MarkdownExit } from './core' + +export * from './core' +export * from './parser' +export * from './renderer' +export * from './token' + +// type and default const variable name must be the same +// for correct d.ts generation +type MarkdownExitConstructor = InstanceType + +// eslint-disable-next-line ts/no-redeclare +const MarkdownExitConstructor = callable(MarkdownExit) as unknown as (typeof createMarkdownExit & typeof MarkdownExit) + +export default MarkdownExitConstructor diff --git a/packages/markdown-exit/src/index.ts b/packages/markdown-exit/src/index.ts index 8cef5ae..d5abee2 100644 --- a/packages/markdown-exit/src/index.ts +++ b/packages/markdown-exit/src/index.ts @@ -1,17 +1,7 @@ -import type { createMarkdownExit } from './core' -import { callable } from './common/utils' -import { MarkdownExit } from './core' +import { LinkifyIt } from 'linkify-it' +import { setLinkifyFactory } from './parser/linkify-it' -export * from './core' -export * from './parser' -export * from './renderer' -export * from './token' +setLinkifyFactory(() => new LinkifyIt()) -// type and default const variable name must be the same -// for correct d.ts generation -type MarkdownExitConstructor = InstanceType - -// eslint-disable-next-line ts/no-redeclare -const MarkdownExitConstructor = callable(MarkdownExit) as unknown as (typeof createMarkdownExit & typeof MarkdownExit) - -export default MarkdownExitConstructor +export * from './index.core' +export { default } from './index.core' diff --git a/packages/markdown-exit/src/parser/core/rules/linkify.ts b/packages/markdown-exit/src/parser/core/rules/linkify.ts index d8c1e4f..14d082c 100644 --- a/packages/markdown-exit/src/parser/core/rules/linkify.ts +++ b/packages/markdown-exit/src/parser/core/rules/linkify.ts @@ -4,6 +4,7 @@ // import type StateCore from '../state_core' +import { requireLinkify } from '../../linkify-it' function isLinkOpen(str: string) { return /^\s]/i.test(str) @@ -17,7 +18,7 @@ export default function linkify(state: StateCore) { return const blockTokens = state.tokens - const linkify = state.md.linkify + const linkify = requireLinkify(state.md.linkify) for (let j = 0, l = blockTokens.length; j < l; j++) { if (blockTokens[j].type !== 'inline' || diff --git a/packages/markdown-exit/src/parser/inline/rules/linkify.ts b/packages/markdown-exit/src/parser/inline/rules/linkify.ts index 8ec5bb6..3160c21 100644 --- a/packages/markdown-exit/src/parser/inline/rules/linkify.ts +++ b/packages/markdown-exit/src/parser/inline/rules/linkify.ts @@ -1,6 +1,7 @@ // Process links like https://example.org/ import type StateInline from '../state_inline' +import { requireLinkify } from '../../linkify-it' // RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i @@ -29,7 +30,7 @@ export default function linkify(state: StateInline, silent: boolean) { const proto = match[1] - const link = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length)) + const link = requireLinkify(state.md.linkify).matchAtStart(state.src.slice(pos - proto.length)) if (!link) return false diff --git a/packages/markdown-exit/src/parser/linkify-it.ts b/packages/markdown-exit/src/parser/linkify-it.ts new file mode 100644 index 0000000..8c52bbe --- /dev/null +++ b/packages/markdown-exit/src/parser/linkify-it.ts @@ -0,0 +1,18 @@ +import type { LinkifyIt } from 'linkify-it' + +let createLinkify: (() => LinkifyIt) | undefined + +export function setLinkifyFactory(factory: () => LinkifyIt): void { + createLinkify = factory +} + +// `markdown-exit/core` registers no factory, so its instances start without one. +export function newLinkify(): LinkifyIt { + return createLinkify?.() as LinkifyIt +} + +export function requireLinkify(linkify: LinkifyIt | undefined): LinkifyIt { + if (!linkify) + throw new Error('markdown-exit/core does not include linkify-it. Set `md.linkify = new LinkifyIt()` before enabling `linkify`.') + return linkify +} diff --git a/packages/markdown-exit/src/parser/parser.ts b/packages/markdown-exit/src/parser/parser.ts index 27a000e..c0d16ad 100644 --- a/packages/markdown-exit/src/parser/parser.ts +++ b/packages/markdown-exit/src/parser/parser.ts @@ -1,10 +1,11 @@ +import type { LinkifyIt } from 'linkify-it' import type { Token } from '../token' import type { MarkdownExitEnv } from '../types/shared' -import { LinkifyIt } from 'linkify-it' import ParserBlock from './block/parser_block' import ParserCore from './core/parser_core' import { helpers } from './helpers' import ParserInline from './inline/parser_inline' +import { newLinkify } from './linkify-it' import { normalizeLink, normalizeLinkText, validateLink } from './utils/link' export interface ParserOptions { @@ -84,9 +85,9 @@ export class Parser { /** * [linkify-it](https://github.com/markdown-it/linkify-it) instance. * Used by [linkify](https://github.com/serkodev/markdown-exit/blob/main/packages/markdown-exit/src/parser/core/rules/linkify.ts) - * rule. + * rule. Unset in `markdown-exit/core` until you assign one. */ - linkify: LinkifyIt = new LinkifyIt() + linkify: LinkifyIt = newLinkify() /** * Link validation function. CommonMark allows too much in links. By default diff --git a/packages/markdown-exit/tests/core-entry.test.ts b/packages/markdown-exit/tests/core-entry.test.ts new file mode 100644 index 0000000..91aef68 --- /dev/null +++ b/packages/markdown-exit/tests/core-entry.test.ts @@ -0,0 +1,41 @@ +import type { Rollup } from 'vite' +import { fileURLToPath } from 'node:url' +import { LinkifyIt } from 'linkify-it' +import { build } from 'vite' +import { assert, describe, it } from 'vitest' +import MarkdownExit from '../src/index.core' + +async function bundleImports(entry: string): Promise { + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + lib: { entry: fileURLToPath(new URL(entry, import.meta.url)), formats: ['es'] }, + rollupOptions: { external: id => !id.startsWith('.') && !id.startsWith('/') }, + }, + }) as Rollup.RollupOutput[] + return result[0].output.flatMap(chunk => chunk.type === 'chunk' ? chunk.imports : []) +} + +describe('markdown-exit/core', () => { + it('does not bundle linkify-it', async () => { + assert.include(await bundleImports('../src/index.ts'), 'linkify-it') + assert.notInclude(await bundleImports('../src/index.core.ts'), 'linkify-it') + }) + + it('renders without linkify-it', () => { + const md = MarkdownExit() + + assert.strictEqual(md.render('https://example.com'), '

https://example.com

\n') + }) + + it('needs a linkify-it instance to enable linkify', () => { + const md = MarkdownExit({ linkify: true }) + + assert.throws(() => md.render('https://example.com'), /linkify-it/) + + md.linkify = new LinkifyIt() + assert.strictEqual(md.render('https://example.com'), '

https://example.com

\n') + }) +}) diff --git a/packages/markdown-exit/tests/index.test.ts b/packages/markdown-exit/tests/index.test.ts index e954673..b7a9fa6 100644 --- a/packages/markdown-exit/tests/index.test.ts +++ b/packages/markdown-exit/tests/index.test.ts @@ -1,3 +1,4 @@ +import { LinkifyIt } from 'linkify-it' import { describe, expect, expectTypeOf, it } from 'vitest' import MarkdownExit, { createMarkdownExit, MarkdownExit as MarkdownExitClass } from '../src' @@ -96,3 +97,23 @@ describe('callable and constructable', () => { expectTypeOf(a.use).parameter(0).toBeFunction() }) }) + +describe('linkify-it', () => { + it('creates a linkify-it instance for every instance', () => { + const a = MarkdownExit() + const b = new MarkdownExitClass() + const c = createMarkdownExit() + + expect(a.linkify).toBeInstanceOf(LinkifyIt) + expect(b.linkify).toBeInstanceOf(LinkifyIt) + expect(c.linkify).toBeInstanceOf(LinkifyIt) + expect(a.linkify).not.toBe(b.linkify) + }) + + it('lets plugins configure md.linkify', () => { + const md = createMarkdownExit({ linkify: true }) + md.use(m => m.linkify.set({ fuzzyLink: true })) + + expect(md.render('example.com')).toBe('

example.com

\n') + }) +}) diff --git a/packages/markdown-exit/tsdown.config.ts b/packages/markdown-exit/tsdown.config.ts index f30bbed..8fbf384 100644 --- a/packages/markdown-exit/tsdown.config.ts +++ b/packages/markdown-exit/tsdown.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from 'tsdown' export default defineConfig([ { - entry: ['./src/index.ts'], + entry: { index: './src/index.ts', core: './src/index.core.ts' }, platform: 'neutral', dts: true, },