#![allow(
clippy::collapsible_else_if,
clippy::collapsible_if,
clippy::comparison_chain,
clippy::if_same_then_else,
clippy::int_plus_one,
clippy::manual_range_contains,
clippy::needless_late_init,
clippy::needless_range_loop,
clippy::nonminimal_bool,
clippy::too_many_arguments,
clippy::while_let_loop
)]
pub mod common;
pub mod helpers;
pub mod js;
pub mod linkify_it;
pub mod mdurl;
pub mod parser_block;
pub mod parser_core;
pub mod parser_inline;
pub mod presets;
pub mod punycode;
pub mod ruler;
pub mod rules_block;
pub mod rules_core;
pub mod rules_inline;
pub mod token;
#[cfg(test)]
mod robustness;
use std::collections::HashMap;
use serde_json::Value;
pub use parser_block::{BlockRule, ParserBlock};
pub use parser_core::{CoreRule, ParserCore};
pub use parser_inline::{InlineRule, InlineRule2, ParserInline};
pub use presets::{ComponentRules, Components, Preset};
pub use ruler::{Rule, Ruler, RulerError};
pub use rules_block::state_block::StateBlock;
pub use rules_core::state_core::StateCore;
pub use rules_inline::state_inline::{
Delimiter, DelimiterList, ScannedDelims, StateInline, TokenMeta,
};
pub use token::{AttrValue, PseudoShape, PseudoToken, Token};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkdownItError(pub String);
impl std::fmt::Display for MarkdownItError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for MarkdownItError {}
impl From<RulerError> for MarkdownItError {
fn from(e: RulerError) -> Self {
MarkdownItError(e.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JsError {
pub name: String,
pub message: String,
}
impl JsError {
pub fn new(name: &str, message: impl Into<String>) -> Self {
JsError {
name: name.to_owned(),
message: message.into(),
}
}
pub fn error(message: impl Into<String>) -> Self {
Self::new("Error", message)
}
pub fn type_error(message: impl Into<String>) -> Self {
Self::new("TypeError", message)
}
pub fn range_error(message: impl Into<String>) -> Self {
Self::new("RangeError", message)
}
pub fn stack_overflow() -> Self {
Self::range_error("Maximum call stack size exceeded")
}
}
impl std::fmt::Display for JsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.name, self.message)
}
}
impl std::error::Error for JsError {}
#[derive(Debug, Clone, PartialEq)]
pub enum Quotes {
Str(String),
Array(Vec<String>),
Object(HashMap<String, String>),
Null,
}
impl Quotes {
pub fn get(&self, i: usize) -> Result<Option<Vec<u16>>, JsError> {
Ok(match self {
Quotes::Str(s) => js::to_utf16(s).get(i).map(|&u| vec![u]),
Quotes::Array(a) => a.get(i).map(|s| js::to_utf16(s)),
Quotes::Object(o) => o.get(&i.to_string()).map(|s| js::to_utf16(s)),
Quotes::Null => {
return Err(JsError::type_error(format!(
"Cannot read properties of null (reading '{i}')"
)));
}
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Options {
pub html: bool,
pub xhtml_out: bool,
pub breaks: bool,
pub lang_prefix: String,
pub linkify: bool,
pub typographer: bool,
pub quotes: Quotes,
pub max_nesting: f64,
pub allow_indentation: bool,
pub extra: serde_json::Map<String, Value>,
}
fn truthy(v: &Value) -> bool {
match v {
Value::Null => false,
Value::Bool(b) => *b,
Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
Value::String(s) => !s.is_empty(),
Value::Array(_) | Value::Object(_) => true,
}
}
fn js_string_of(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
Value::Null => "null".into(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => js::number_to_string(n.as_f64().unwrap_or(f64::NAN)),
Value::Array(a) => a
.iter()
.map(|x| {
if x.is_null() {
String::new()
} else {
js_string_of(x)
}
})
.collect::<Vec<_>>()
.join(","),
Value::Object(_) => "[object Object]".into(),
}
}
fn js_to_number(v: &Value) -> f64 {
match v {
Value::Null => 0.0,
Value::Bool(b) => f64::from(u8::from(*b)),
Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
Value::String(_) | Value::Array(_) | Value::Object(_) => {
js::string_to_number(&js::to_utf16(&js_string_of(v)))
}
}
}
impl Options {
pub fn assign(&mut self, key: &str, value: &Value) {
match key {
"html" => self.html = truthy(value),
"xhtmlOut" => self.xhtml_out = truthy(value),
"breaks" => self.breaks = truthy(value),
"langPrefix" => self.lang_prefix = js_string_of(value),
"linkify" => self.linkify = truthy(value),
"typographer" => self.typographer = truthy(value),
"quotes" => {
self.quotes = match value {
Value::String(s) => Quotes::Str(s.clone()),
Value::Array(a) => Quotes::Array(a.iter().map(js_string_of).collect()),
Value::Object(o) => Quotes::Object(
o.iter()
.map(|(k, v)| (k.clone(), js_string_of(v)))
.collect(),
),
Value::Null => Quotes::Null,
Value::Number(_) | Value::Bool(_) => Quotes::Array(Vec::new()),
}
}
"maxNesting" => self.max_nesting = js_to_number(value),
"allowIndentation" => self.allow_indentation = truthy(value),
_ => {
self.extra.insert(key.to_owned(), value.clone());
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reference {
pub href: String,
pub title: String,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Env {
pub references: Option<HashMap<String, Reference>>,
pub extra: serde_json::Map<String, Value>,
pub thrown: Option<JsError>,
depth: usize,
}
impl Env {
pub fn throw(&mut self, error: JsError) {
if self.thrown.is_none() {
self.thrown = Some(error);
}
}
pub fn has_thrown(&self) -> bool {
self.thrown.is_some()
}
pub(crate) fn enter(&mut self) -> bool {
if self.thrown.is_some() {
return false;
}
if self.depth >= MAX_DEPTH && !crate::depth::can_grow() {
self.throw(JsError::stack_overflow());
return false;
}
self.depth += 1;
true
}
pub(crate) fn level(&mut self, cost: u64) -> Option<crate::depth::Level> {
let level = crate::depth::enter(cost);
if level.is_none() {
self.throw(JsError::stack_overflow());
}
level
}
pub(crate) fn leave(&mut self) {
self.depth -= 1;
}
}
pub const MAX_DEPTH: usize = 160;
pub mod cost {
use crate::depth::per_level;
pub const BLOCKQUOTE: u64 = per_level(1_789);
pub const LIST: u64 = per_level(1_690);
pub const LINK: u64 = per_level(1_604);
pub const IMAGE: u64 = per_level(1_642);
}
const RECODE_HOSTNAME_FOR: [&str; 3] = ["http:", "https:", "mailto:"];
#[derive(Debug, Clone)]
pub struct MarkdownIt {
pub inline: ParserInline,
pub block: ParserBlock,
pub core: ParserCore,
pub linkify: linkify_it::LinkifyIt,
pub options: Options,
options_undefined: bool,
}
impl Default for MarkdownIt {
fn default() -> Self {
Self::new("default").expect("the default preset exists")
}
}
impl MarkdownIt {
fn bare() -> Self {
MarkdownIt {
inline: ParserInline::new(),
block: ParserBlock::new(),
core: ParserCore::new(),
linkify: linkify_it::LinkifyIt::new(),
options: presets::default::options(),
options_undefined: false,
}
}
pub fn new(preset_name: &str) -> Result<Self, MarkdownItError> {
let mut md = Self::bare();
if presets::by_name(preset_name).is_none() && presets::is_inherited(preset_name) {
md.options_undefined = true;
return Ok(md);
}
md.configure_named(preset_name)?;
Ok(md)
}
pub fn has_options(&self) -> bool {
!self.options_undefined
}
pub fn try_set(
&mut self,
options: &serde_json::Map<String, Value>,
) -> Result<&mut Self, JsError> {
if self.options_undefined {
return Err(JsError::type_error(
"Cannot convert undefined or null to object",
));
}
Ok(self.set(options))
}
pub fn with_options(
preset_name: &str,
options: &serde_json::Map<String, Value>,
) -> Result<Self, MarkdownItError> {
let mut md = Self::new(preset_name)?;
md.try_set(options)
.map_err(|e| MarkdownItError(format!("{}: {}", e.name, e.message)))?;
Ok(md)
}
pub fn set(&mut self, options: &serde_json::Map<String, Value>) -> &mut Self {
if self.options_undefined {
return self;
}
for (key, value) in options {
self.options.assign(key, value);
}
self
}
pub fn configure_named(&mut self, preset_name: &str) -> Result<&mut Self, MarkdownItError> {
if presets::by_name(preset_name).is_none() && presets::is_inherited(preset_name) {
return Ok(self);
}
let Some(p) = presets::by_name(preset_name) else {
return Err(MarkdownItError(format!(
"Wrong 'markdown-it' preset \"{preset_name}\", check name"
)));
};
self.configure(&p)
}
pub fn configure(&mut self, p: &Preset) -> Result<&mut Self, MarkdownItError> {
if let Some(options) = &p.options {
self.options = options.clone();
self.options_undefined = false;
}
if let Some(components) = &p.components {
if let Some(rules) = components.core.as_ref().and_then(|c| c.rules.as_ref()) {
self.core.ruler.enable_only(rules, false)?;
}
if let Some(rules) = components.block.as_ref().and_then(|c| c.rules.as_ref()) {
self.block.ruler.enable_only(rules, false)?;
}
if let Some(rules) = components.inline.as_ref().and_then(|c| c.rules.as_ref()) {
self.inline.ruler.enable_only(rules, false)?;
}
if let Some(rules2) = components.inline.as_ref().and_then(|c| c.rules2.as_ref()) {
self.inline.ruler2.enable_only(rules2, false)?;
}
}
Ok(self)
}
pub fn enable<S: AsRef<str>>(
&mut self,
list: &[S],
ignore_invalid: bool,
) -> Result<&mut Self, MarkdownItError> {
let mut result: Vec<String> = Vec::new();
result.extend(self.core.ruler.enable(list, true)?);
result.extend(self.block.ruler.enable(list, true)?);
result.extend(self.inline.ruler.enable(list, true)?);
result.extend(self.inline.ruler2.enable(list, true)?);
let missed: Vec<&str> = list
.iter()
.map(AsRef::as_ref)
.filter(|name| !result.iter().any(|r| r == name))
.collect();
if !missed.is_empty() && !ignore_invalid {
return Err(MarkdownItError(format!(
"MarkdownIt. Failed to enable unknown rule(s): {}",
missed.join(",")
)));
}
Ok(self)
}
pub fn disable<S: AsRef<str>>(
&mut self,
list: &[S],
ignore_invalid: bool,
) -> Result<&mut Self, MarkdownItError> {
let mut result: Vec<String> = Vec::new();
result.extend(self.core.ruler.disable(list, true)?);
result.extend(self.block.ruler.disable(list, true)?);
result.extend(self.inline.ruler.disable(list, true)?);
result.extend(self.inline.ruler2.disable(list, true)?);
let missed: Vec<&str> = list
.iter()
.map(AsRef::as_ref)
.filter(|name| !result.iter().any(|r| r == name))
.collect();
if !missed.is_empty() && !ignore_invalid {
return Err(MarkdownItError(format!(
"MarkdownIt. Failed to disable unknown rule(s): {}",
missed.join(",")
)));
}
Ok(self)
}
pub fn use_plugin(&mut self, plugin: impl FnOnce(&mut MarkdownIt)) -> &mut Self {
plugin(self);
self
}
pub fn parse(&self, src: &str, env: &mut Env) -> Vec<Token> {
if self.options_undefined {
return Self::no_options(env);
}
let mut state = StateCore::new(js::to_utf16(src), self, env);
self.core.process(&mut state);
state.tokens
}
pub fn try_parse(&self, src: &str, env: &mut Env) -> Result<Vec<Token>, JsError> {
let tokens = self.parse(src, env);
match env.thrown.take() {
Some(error) => Err(error),
None => Ok(tokens),
}
}
pub fn parse_inline(&self, src: &str, env: &mut Env) -> Vec<Token> {
if self.options_undefined {
return Self::no_options(env);
}
let mut state = StateCore::new(js::to_utf16(src), self, env);
state.inline_mode = true;
self.core.process(&mut state);
state.tokens
}
fn no_options(env: &mut Env) -> Vec<Token> {
env.throw(JsError::type_error(
"Cannot read properties of undefined (reading 'maxNesting')",
));
Vec::new()
}
pub fn try_parse_inline(&self, src: &str, env: &mut Env) -> Result<Vec<Token>, JsError> {
let tokens = self.parse_inline(src, env);
match env.thrown.take() {
Some(error) => Err(error),
None => Ok(tokens),
}
}
pub fn validate_link(&self, url: &[u16]) -> bool {
let s = js::to_lower_case(js::trim(url));
let starts = |prefix: &str| js::starts_with(&s, &js::to_utf16(prefix), 0);
let bad_proto = ["vbscript:", "javascript:", "file:", "data:"]
.iter()
.any(|p| starts(p));
if bad_proto {
[
"data:image/gif;",
"data:image/png;",
"data:image/jpeg;",
"data:image/webp;",
]
.iter()
.any(|p| starts(p))
} else {
true
}
}
pub fn normalize_link(&self, url: &[u16]) -> Vec<u16> {
let mut parsed = mdurl::parse(url, true);
if parsed.hostname.as_ref().is_some_and(|h| !h.is_empty()) {
if recode_hostname(&parsed)
&& let Ok(hostname) =
punycode::to_ascii(parsed.hostname.as_deref().unwrap_or_default())
{
parsed.hostname = Some(hostname);
}
}
for part in [
&mut parsed.auth,
&mut parsed.hostname,
&mut parsed.pathname,
&mut parsed.search,
&mut parsed.hash,
] {
if let Some(value) = part.as_ref().filter(|v| !v.is_empty()) {
*part = Some(mdurl::encode(value, None, None));
}
}
mdurl::format(&parsed)
}
pub fn normalize_link_text(&self, url: &[u16]) -> Vec<u16> {
let mut parsed = mdurl::parse(url, true);
if parsed.hostname.as_ref().is_some_and(|h| !h.is_empty()) {
if recode_hostname(&parsed)
&& let Ok(hostname) =
punycode::to_unicode(parsed.hostname.as_deref().unwrap_or_default())
{
parsed.hostname = Some(hostname);
}
}
let exclude = format!("{}%", mdurl::decode::DEFAULT_CHARS);
mdurl::decode(&mdurl::format(&parsed), Some(&exclude))
}
}
fn recode_hostname(parsed: &mdurl::Url) -> bool {
match parsed.protocol.as_deref() {
None | Some([]) => true,
Some(protocol) => RECODE_HOSTNAME_FOR
.iter()
.any(|p| js::to_utf16(p) == protocol),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn s(x: &str) -> Vec<u16> {
js::to_utf16(x)
}
#[test]
fn presets_and_errors() {
assert!(MarkdownIt::new("default").is_ok());
for name in ["nope", "", "Default", "Constructor", "__proto"] {
assert_eq!(
MarkdownIt::new(name).err(),
Some(MarkdownItError(format!(
"Wrong 'markdown-it' preset \"{name}\", check name"
)))
);
}
assert_eq!(
MarkdownIt::new("nope").err(),
Some(MarkdownItError(
"Wrong 'markdown-it' preset \"nope\", check name".into()
))
);
for name in crate::markdown_it::mdurl::OBJECT_PROTOTYPE_KEYS {
let mut md = MarkdownIt::new(name).expect("an instance");
assert!(!md.has_options());
let mut env = Env::default();
assert_eq!(
md.try_parse("# a", &mut env).err(),
Some(JsError::type_error(
"Cannot read properties of undefined (reading 'maxNesting')"
))
);
assert_eq!(
md.try_parse_inline("a", &mut env).err(),
Some(JsError::type_error(
"Cannot read properties of undefined (reading 'maxNesting')"
))
);
assert_eq!(
md.try_set(&serde_json::Map::new()).err(),
Some(JsError::type_error(
"Cannot convert undefined or null to object"
))
);
let options = serde_json::json!({"html": true});
assert_eq!(
MarkdownIt::with_options(name, options.as_object().unwrap()).err(),
Some(MarkdownItError(
"TypeError: Cannot convert undefined or null to object".into()
))
);
let mut md = MarkdownIt::default();
md.configure_named(name).expect("configures nothing");
assert!(md.has_options() && md.options.max_nesting == 100.0);
}
let cm = MarkdownIt::new("commonmark").unwrap();
assert!(cm.options.html && cm.options.xhtml_out && cm.options.max_nesting == 20.0);
let zero = MarkdownIt::new("zero").unwrap();
let names = |r: &[Rule<BlockRule>]| {
r.iter()
.filter(|x| x.enabled)
.map(|x| x.name.clone())
.collect::<Vec<_>>()
};
assert_eq!(names(zero.block.ruler.rules()), ["paragraph"]);
}
#[test]
fn enable_disable_report_unknown_rules_like_js() {
let mut md = MarkdownIt::default();
assert!(md.disable(&["lheading", "code"], false).is_ok());
assert_eq!(
md.disable(&["code", "nope", "nada"], false).err(),
Some(MarkdownItError(
"MarkdownIt. Failed to disable unknown rule(s): nope,nada".into()
))
);
assert!(md.enable(&["nope"], true).is_ok());
assert_eq!(
md.enable(&["nope"], false).err(),
Some(MarkdownItError(
"MarkdownIt. Failed to enable unknown rule(s): nope".into()
))
);
md.disable(&["emphasis"], false).unwrap();
assert!(
md.inline
.ruler2
.rules()
.iter()
.any(|r| r.name == "emphasis" && !r.enabled)
);
}
#[test]
fn set_follows_object_assign() {
let mut md = MarkdownIt::default();
let opts: serde_json::Map<String, Value> = serde_json::from_str(
r#"{"allowIndentation": true, "maxNesting": 7, "quotes": ["a","b","c","d"], "allowComments": true}"#,
)
.unwrap();
md.set(&opts);
assert!(md.options.allow_indentation);
assert_eq!(md.options.max_nesting, 7.0);
assert_eq!(md.options.quotes.get(1), Ok(Some(s("b"))));
assert_eq!(
md.options.extra.get("allowComments"),
Some(&Value::Bool(true))
);
md.configure_named("default").unwrap();
assert!(!md.options.allow_indentation && md.options.extra.is_empty());
assert_eq!(
Quotes::Str("\u{201c}\u{201d}".into()).get(1),
Ok(Some(vec![0x201D]))
);
assert_eq!(Quotes::Str("ab".into()).get(5), Ok(None));
}
#[test]
fn max_nesting_is_compared_as_a_js_number() {
let types = |v: Value| {
let mut options = serde_json::Map::new();
options.insert("maxNesting".into(), v);
let md = MarkdownIt::with_options("default", &options).unwrap();
let kinds = |ts: &[Token]| {
let kinds: Vec<_> = ts
.iter()
.map(|t| t.kind.replace("blockquote", "bq"))
.collect();
kinds.join(" ")
};
let block = md.parse("> > > a\n", &mut Env::default());
let inline = md.parse_inline("*a* [b](c)", &mut Env::default());
(kinds(&block), kinds(inline[0].children.as_ref().unwrap()))
};
let rich = "em_open text em_close text link_open text link_close";
let pair = |block: &str, inline: &str| (block.to_owned(), inline.to_owned());
let two = "bq_open bq_open bq_close bq_close";
assert_eq!(types(Value::from("2")), pair(two, rich));
assert_eq!(types(Value::Null), pair("", "text"));
assert_eq!(types(Value::Bool(true)), pair("bq_open bq_close", rich));
assert_eq!(types(Value::from(" 0x1 ")), pair("bq_open bq_close", rich));
let three = "bq_open bq_open bq_open bq_close bq_close bq_close";
assert_eq!(types(serde_json::json!([3])), pair(three, rich));
let deep = "bq_open bq_open bq_open paragraph_open inline paragraph_close bq_close bq_close bq_close";
assert_eq!(types(Value::from("abc")), pair(deep, "text"));
assert_eq!(types(serde_json::json!({})), pair(deep, "text"));
}
#[test]
fn quotes_option_is_indexed_as_js_indexes_it() {
let text = |quotes: Value, src: &str| {
let mut options = serde_json::Map::new();
options.insert("typographer".into(), Value::Bool(true));
options.insert("quotes".into(), quotes);
let md = MarkdownIt::with_options("default", &options).unwrap();
let tokens = md.parse_inline(src, &mut Env::default());
tokens[0].children.as_ref().unwrap()[0].content.clone()
};
let object =
serde_json::json!({"0": "\u{ab}", "1": [1, [2, null]], "2": null, "3": {"a": 1}});
assert_eq!(
text(object, "\"a\" 'b'"),
"\u{ab}a1,2, nullb[object Object]"
);
let partial = serde_json::json!({"1": "R", "3": 7});
assert_eq!(text(partial, "\"a\" 'b'"), "undefinedaR undefinedb7");
assert_eq!(text(Value::from(5), "\"a\""), "undefinedaundefined");
assert_eq!(text(Value::Null, "don't"), "don\u{2019}t");
let thrown = |src: &str| {
let mut options = serde_json::Map::new();
options.insert("typographer".into(), Value::Bool(true));
options.insert("quotes".into(), Value::Null);
let md = MarkdownIt::with_options("default", &options).unwrap();
md.try_parse(src, &mut Env::default()).unwrap_err()
};
let null =
|i: u8| JsError::type_error(format!("Cannot read properties of null (reading '{i}')"));
assert_eq!(thrown("\"a\""), null(0));
assert_eq!(thrown("'a' \"b\""), null(2));
assert_eq!(thrown("x\n\n> \"a\" 'b'"), null(0));
}
#[test]
fn validate_link_matches_markdown_it() {
let md = MarkdownIt::default();
for (url, ok) in [
("http://x", true),
("javascript:alert(1)", false),
(" JavaScript:x", false),
("vbscript:x", false),
("file:///etc", false),
("data:text/html,x", false),
("data:image/png;base64,x", true),
("DATA:IMAGE/WEBP;x", true),
("data:image/svg+xml;x", false),
("javascript", true),
] {
assert_eq!(md.validate_link(&s(url)), ok, "{url}");
}
}
fn children(options: &str, src: &str) -> Vec<String> {
let options: serde_json::Map<String, Value> = serde_json::from_str(options).unwrap();
let md = MarkdownIt::with_options("default", &options).unwrap();
let tokens = md.parse(src, &mut Env::default());
let inline = tokens.iter().find(|t| t.kind == "inline").unwrap();
inline
.children
.as_ref()
.unwrap()
.iter()
.map(|t| match t.attr_get("href") {
Some(href) => format!("{} {}", t.kind, href.to_js_string()),
None => format!("{} {}", t.kind, t.content),
})
.collect()
}
#[test]
fn lone_surrogates_the_engine_makes_are_u_fffd_and_halves_that_meet_pair_again() {
let quotes = r#"{"typographer": true, "quotes": "šššš"}"#;
assert_eq!(
children(quotes, "\"\" '' \"a\" 'b'"),
["text š š \u{FFFD}a\u{FFFD} \u{FFFD}b\u{FFFD}"]
);
let links = |options: &str, src: &str| {
assert_eq!(
children(options, src),
[
"link_open http://xn--Zc0c.com",
"text http://\u{FFFD}.com",
"link_close ",
"text ",
"link_open http://xn--8c9bk9h.com",
"text http://š.com",
"link_close ",
"text ",
"link_open http://xn--a-8f4g.com",
"text http://a\u{FFFD}.com",
"link_close ",
],
"{src}"
);
};
links(
"{}",
"<http://xn--Zc0c.com> <http://xn--8c9bk9h.com> <http://xn--a-8f4g.com>",
);
links(
r#"{"linkify": true}"#,
"http://xn--Zc0c.com http://xn--8c9bk9h.com http://xn--a-8f4g.com",
);
let md = MarkdownIt::default();
let text = |url: &str| js::to_string(&md.normalize_link_text(&s(url)));
assert_eq!(text("http://xn--8c9bk9h.com"), "http://š.com");
assert_eq!(text("http://xn--zc0c.com"), "http://\u{FFFD}.com");
assert_eq!(text("xn--8c9bk9h.xn--zc0c"), "xn--8c9bk9h.xn--zc0c");
let a = "a".repeat(9991);
let cut = format!("http://a.com/{a}šz");
assert_eq!(
children(r#"{"linkify": true}"#, &cut),
[
format!("link_open http://a.com/{a}%EF%BF%BD"),
format!("text http://a.com/{a}\u{FFFD}"),
"link_close ".to_owned(),
"text \u{FFFD}z".to_owned(),
]
);
}
fn exact_children(options: &str, src: &str) -> Vec<String> {
let options: serde_json::Map<String, Value> = serde_json::from_str(options).unwrap();
let md = MarkdownIt::with_options("default", &options).unwrap();
let tokens = md.parse(src, &mut Env::default());
let inline = tokens.iter().find(|t| t.kind == "inline").unwrap();
let escaped = |units: &[u16]| -> String {
char::decode_utf16(units.iter().copied())
.map(|c| match c {
Ok(c) => c.to_string(),
Err(e) => format!("\\u{:04x}", e.unpaired_surrogate()),
})
.collect()
};
inline
.children
.as_ref()
.unwrap()
.iter()
.map(|t| match t.attr_get("href") {
Some(href) => format!("{} {}", t.kind, href.to_js_string()),
None => format!("{} {}", t.kind, escaped(&t.content_utf16())),
})
.collect()
}
#[test]
fn a_lone_surrogate_the_engine_made_reads_back_as_node_reads_it() {
let a = "a".repeat(9991);
let cases: &[(&str, &str, &[&str])] = &[
(
r#"{"linkify": true, "typographer": true}"#,
"http://xn--Zc0c\"a\"",
&[
"link_open http://xn--Zc0c",
"text http://\\udcfd",
"link_close ",
"text \"a\"",
],
),
(
r#"{"typographer": true}"#,
"<http://xn--Zc0c\"a\">",
&[
"link_open http://xn--Zc0c%22a%22",
"text http://\\udcfd\"a\"",
"link_close ",
],
),
(
r#"{"typographer": true}"#,
"\"b <http://xn--Zc0c>\"c\"",
&[
"text āb ",
"link_open http://xn--Zc0c",
"text http://\\udcfd",
"link_close ",
"text \"cā",
],
),
(
r#"{"linkify": true, "typographer": true}"#,
"http://a.com/{a}š\"x\"",
&[
"link_open http://a.com/{a}%EF%BF%BD",
"text http://a.com/{a}\\ud83d",
"link_close ",
"text \\ude00\"x\"",
],
),
(
r#"{"typographer": true, "quotes": "šššš"}"#,
"\"\" '' \"a\" 'b'",
&["text š š \\ud83da\\ude00 \\ud83db\\ude00"],
),
(
r#"{"typographer": true, "quotes": "šššš¤£"}"#,
"\"*a*\" '_b_' \"`c`\" x\"y\" \"\\\"\" \"<http://xn--Zc0c>\"",
&[
"text \\ud83d",
"em_open ",
"text a",
"em_close ",
"text \\ude00 \\ud83d",
"em_open ",
"text b",
"em_close ",
"text \\ude01 \\ud83d",
"code_inline c",
"text \\ude00 x\"y\" \\ud83d\"\\ude00 \\ud83d",
"link_open http://xn--Zc0c",
"text http://\\udcfd",
"link_close ",
"text \\ude00",
],
),
(
r#"{"typographer": true, "linkify": true, "quotes": "šššš¤£"}"#,
"\"http://xn--Zc0c\" (c)http://xn--Zc0c.com'x' 'http://a.com/{a}š'",
&[
"text \\ud83d",
"link_open http://xn--Zc0c",
"text http://\\udcfd",
"link_close ",
"text \\ude00 Ā©",
"link_open http://xn--Zc0c.com",
"text http://\\udcfd.com",
"link_close ",
"text āxā \\ud83d",
"link_open http://a.com/{a}%EF%BF%BD",
"text http://a.com/{a}\\ud83d",
"link_close ",
"text \\ude00\\ude01",
],
),
];
for (options, src, want) in cases {
let src = src.replace("{a}", &a);
let want: Vec<String> = want.iter().map(|w| w.replace("{a}", &a)).collect();
assert_eq!(exact_children(options, &src), want, "{options} {src:?}");
let lossy: Vec<String> = want
.iter()
.map(|w| {
let mut out = w.clone();
for hex in ["d83d", "dcfd", "de00", "de01"] {
out = out.replace(&format!("\\u{hex}"), "\u{FFFD}");
}
out
})
.collect();
assert_eq!(children(options, &src), lossy, "{options} {src:?}");
}
}
}