Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/guide/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
25 changes: 25 additions & 0 deletions docs/guide/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -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') // <p>https://example.com</p>
```

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.
1 change: 1 addition & 0 deletions packages/markdown-exit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
],
"exports": {
".": "./dist/index.js",
"./core": "./dist/core.js",
"./package.json": "./package.json"
},
"main": "./dist/index.js",
Expand Down
17 changes: 17 additions & 0 deletions packages/markdown-exit/src/index.core.ts
Original file line number Diff line number Diff line change
@@ -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<typeof MarkdownExit>

// eslint-disable-next-line ts/no-redeclare
const MarkdownExitConstructor = callable(MarkdownExit) as unknown as (typeof createMarkdownExit & typeof MarkdownExit)

export default MarkdownExitConstructor
20 changes: 5 additions & 15 deletions packages/markdown-exit/src/index.ts
Original file line number Diff line number Diff line change
@@ -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<typeof MarkdownExit>

// 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'
3 changes: 2 additions & 1 deletion packages/markdown-exit/src/parser/core/rules/linkify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

import type StateCore from '../state_core'
import { requireLinkify } from '../../linkify-it'

function isLinkOpen(str: string) {
return /^<a[>\s]/i.test(str)
Expand All @@ -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' ||
Expand Down
3 changes: 2 additions & 1 deletion packages/markdown-exit/src/parser/inline/rules/linkify.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions packages/markdown-exit/src/parser/linkify-it.ts
Original file line number Diff line number Diff line change
@@ -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
}
7 changes: 4 additions & 3 deletions packages/markdown-exit/src/parser/parser.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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
Expand Down
41 changes: 41 additions & 0 deletions packages/markdown-exit/tests/core-entry.test.ts
Original file line number Diff line number Diff line change
@@ -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<string[]> {
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'), '<p>https://example.com</p>\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'), '<p><a href="https://example.com">https://example.com</a></p>\n')
})
})
21 changes: 21 additions & 0 deletions packages/markdown-exit/tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { LinkifyIt } from 'linkify-it'
import { describe, expect, expectTypeOf, it } from 'vitest'
import MarkdownExit, { createMarkdownExit, MarkdownExit as MarkdownExitClass } from '../src'

Expand Down Expand Up @@ -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('<p><a href="http://example.com">example.com</a></p>\n')
})
})
2 changes: 1 addition & 1 deletion packages/markdown-exit/tsdown.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down
Loading