You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
11 KiB

  1. /*
  2. `util/bio_metadata`
  3. ===================
  4. > For more information on the contents of this file, please contact:
  5. >
  6. > - kibigo! [@kibi@glitch.social]
  7. This file provides two functions for dealing with bio metadata. The
  8. functions are:
  9. - __`processBio(content)` :__
  10. Processes `content` to extract any frontmatter. The returned
  11. object has two properties: `text`, which contains the text of
  12. `content` sans-frontmatter, and `metadata`, which is an array
  13. of key-value pairs (in two-element array format). If no
  14. frontmatter was provided in `content`, then `metadata` will be
  15. an empty array.
  16. - __`createBio(note, data)` :__
  17. Reverses the process in `processBio()`; takes a `note` and an
  18. array of two-element arrays (which should give keys and values)
  19. and outputs a string containing a well-formed bio with
  20. frontmatter.
  21. */
  22. // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  23. /*********************************************************************\
  24. To my lovely code maintainers,
  25. The syntax recognized by the Mastodon frontend for its bio metadata
  26. feature is a subset of that provided by the YAML 1.2 specification.
  27. In particular, Mastodon recognizes metadata which is provided as an
  28. implicit YAML map, where each key-value pair takes up only a single
  29. line (no multi-line values are permitted). To simplify the level of
  30. processing required, Mastodon metadata frontmatter has been limited
  31. to only allow those characters in the `c-printable` set, as defined
  32. by the YAML 1.2 specification, instead of permitting those from the
  33. `nb-json` characters inside double-quoted strings like YAML proper.
  34. It is important to note that Mastodon only borrows the *syntax*
  35. of YAML, not its semantics. This is to say, Mastodon won't make any
  36. attempt to interpret the data it receives. `true` will not become a
  37. boolean; `56` will not be interpreted as a number. Rather, each key
  38. and every value will be read as a string, and as a string they will
  39. remain. The order of the pairs is unchanged, and any duplicate keys
  40. are preserved. However, YAML escape sequences will be replaced with
  41. the proper interpretations according to the YAML 1.2 specification.
  42. The implementation provided below interprets `<br>` as `\n` and
  43. allows for an open <p> tag at the beginning of the bio. It replaces
  44. the escaped character entities `&apos;` and `&quot;` with single or
  45. double quotes, respectively, prior to processing. However, no other
  46. escaped characters are replaced, not even those which might have an
  47. impact on the syntax otherwise. These minor allowances are provided
  48. because the Mastodon backend will insert these things automatically
  49. into a bio before sending it through the API, so it is important we
  50. account for them. Aside from this, the YAML frontmatter must be the
  51. very first thing in the bio, leading with three consecutive hyphen-
  52. minues (`---`), and ending with the same or, alternatively, instead
  53. with three periods (`...`). No limits have been set with respect to
  54. the number of characters permitted in the frontmatter, although one
  55. should note that only limited space is provided for them in the UI.
  56. The regular expression used to check the existence of, and then
  57. process, the YAML frontmatter has been split into a number of small
  58. components in the code below, in the vain hope that it will be much
  59. easier to read and to maintain. I leave it to the future readers of
  60. this code to determine the extent of my successes in this endeavor.
  61. UPDATE 19 Oct 2017: We no longer allow character escapes inside our
  62. double-quoted strings for ease of processing. We now internally use
  63. the name "ƔAML" in our code to clarify that this is Not Quite YAML.
  64. Sending love + warmth eternal,
  65. - kibigo [@kibi@glitch.social]
  66. \*********************************************************************/
  67. /* "u" FLAG COMPATABILITY */
  68. let compat_mode = false;
  69. try {
  70. new RegExp('.', 'u');
  71. } catch (e) {
  72. compat_mode = true;
  73. }
  74. /* CONVENIENCE FUNCTIONS */
  75. const unirex = str => compat_mode ? new RegExp(str) : new RegExp(str, 'u');
  76. const rexstr = exp => '(?:' + exp.source + ')';
  77. /* CHARACTER CLASSES */
  78. const DOCUMENT_START = /^/;
  79. const DOCUMENT_END = /$/;
  80. const ALLOWED_CHAR = unirex( // `c-printable` in the YAML 1.2 spec.
  81. compat_mode ? '[\t\n\r\x20-\x7e\x85\xa0-\ufffd]' : '[\t\n\r\x20-\x7e\x85\xa0-\ud7ff\ue000-\ufffd\u{10000}-\u{10FFFF}]'
  82. );
  83. const WHITE_SPACE = /[ \t]/;
  84. const LINE_BREAK = /\r?\n|\r|<br\s*\/?>/;
  85. const INDICATOR = /[-?:,[\]{}&#*!|>'"%@`]/;
  86. const FLOW_CHAR = /[,[\]{}]/;
  87. /* NEGATED CHARACTER CLASSES */
  88. const NOT_WHITE_SPACE = unirex('(?!' + rexstr(WHITE_SPACE) + ')[^]');
  89. const NOT_LINE_BREAK = unirex('(?!' + rexstr(LINE_BREAK) + ')[^]');
  90. const NOT_INDICATOR = unirex('(?!' + rexstr(INDICATOR) + ')[^]');
  91. const NOT_FLOW_CHAR = unirex('(?!' + rexstr(FLOW_CHAR) + ')[^]');
  92. const NOT_ALLOWED_CHAR = unirex(
  93. '(?!' + rexstr(ALLOWED_CHAR) + ')[^]'
  94. );
  95. /* BASIC CONSTRUCTS */
  96. const ANY_WHITE_SPACE = unirex(rexstr(WHITE_SPACE) + '*');
  97. const ANY_ALLOWED_CHARS = unirex(rexstr(ALLOWED_CHAR) + '*');
  98. const NEW_LINE = unirex(
  99. rexstr(ANY_WHITE_SPACE) + rexstr(LINE_BREAK)
  100. );
  101. const SOME_NEW_LINES = unirex(
  102. '(?:' + rexstr(NEW_LINE) + ')+'
  103. );
  104. const POSSIBLE_STARTS = unirex(
  105. rexstr(DOCUMENT_START) + rexstr(/<p[^<>]*>/) + '?'
  106. );
  107. const POSSIBLE_ENDS = unirex(
  108. rexstr(SOME_NEW_LINES) + '|' +
  109. rexstr(DOCUMENT_END) + '|' +
  110. rexstr(/<\/p>/)
  111. );
  112. const QUOTE_CHAR = unirex(
  113. '(?=' + rexstr(NOT_LINE_BREAK) + ')[^"]'
  114. );
  115. const ANY_QUOTE_CHAR = unirex(
  116. rexstr(QUOTE_CHAR) + '*'
  117. );
  118. const ESCAPED_APOS = unirex(
  119. '(?=' + rexstr(NOT_LINE_BREAK) + ')' + rexstr(/[^']|''/)
  120. );
  121. const ANY_ESCAPED_APOS = unirex(
  122. rexstr(ESCAPED_APOS) + '*'
  123. );
  124. const FIRST_KEY_CHAR = unirex(
  125. '(?=' + rexstr(NOT_LINE_BREAK) + ')' +
  126. '(?=' + rexstr(NOT_WHITE_SPACE) + ')' +
  127. rexstr(NOT_INDICATOR) + '|' +
  128. rexstr(/[?:-]/) +
  129. '(?=' + rexstr(NOT_LINE_BREAK) + ')' +
  130. '(?=' + rexstr(NOT_WHITE_SPACE) + ')' +
  131. '(?=' + rexstr(NOT_FLOW_CHAR) + ')'
  132. );
  133. const FIRST_VALUE_CHAR = unirex(
  134. '(?=' + rexstr(NOT_LINE_BREAK) + ')' +
  135. '(?=' + rexstr(NOT_WHITE_SPACE) + ')' +
  136. rexstr(NOT_INDICATOR) + '|' +
  137. rexstr(/[?:-]/) +
  138. '(?=' + rexstr(NOT_LINE_BREAK) + ')' +
  139. '(?=' + rexstr(NOT_WHITE_SPACE) + ')'
  140. // Flow indicators are allowed in values.
  141. );
  142. const LATER_KEY_CHAR = unirex(
  143. rexstr(WHITE_SPACE) + '|' +
  144. '(?=' + rexstr(NOT_LINE_BREAK) + ')' +
  145. '(?=' + rexstr(NOT_WHITE_SPACE) + ')' +
  146. '(?=' + rexstr(NOT_FLOW_CHAR) + ')' +
  147. rexstr(/[^:#]#?/) + '|' +
  148. rexstr(/:/) + '(?=' + rexstr(NOT_WHITE_SPACE) + ')'
  149. );
  150. const LATER_VALUE_CHAR = unirex(
  151. rexstr(WHITE_SPACE) + '|' +
  152. '(?=' + rexstr(NOT_LINE_BREAK) + ')' +
  153. '(?=' + rexstr(NOT_WHITE_SPACE) + ')' +
  154. // Flow indicators are allowed in values.
  155. rexstr(/[^:#]#?/) + '|' +
  156. rexstr(/:/) + '(?=' + rexstr(NOT_WHITE_SPACE) + ')'
  157. );
  158. /* YAML CONSTRUCTS */
  159. const ƔAML_START = unirex(
  160. rexstr(ANY_WHITE_SPACE) + '---'
  161. );
  162. const ƔAML_END = unirex(
  163. rexstr(ANY_WHITE_SPACE) + '(?:---|\.\.\.)'
  164. );
  165. const ƔAML_LOOKAHEAD = unirex(
  166. '(?=' +
  167. rexstr(ƔAML_START) +
  168. rexstr(ANY_ALLOWED_CHARS) + rexstr(NEW_LINE) +
  169. rexstr(ƔAML_END) + rexstr(POSSIBLE_ENDS) +
  170. ')'
  171. );
  172. const ƔAML_DOUBLE_QUOTE = unirex(
  173. '"' + rexstr(ANY_QUOTE_CHAR) + '"'
  174. );
  175. const ƔAML_SINGLE_QUOTE = unirex(
  176. '\'' + rexstr(ANY_ESCAPED_APOS) + '\''
  177. );
  178. const ƔAML_SIMPLE_KEY = unirex(
  179. rexstr(FIRST_KEY_CHAR) + rexstr(LATER_KEY_CHAR) + '*'
  180. );
  181. const ƔAML_SIMPLE_VALUE = unirex(
  182. rexstr(FIRST_VALUE_CHAR) + rexstr(LATER_VALUE_CHAR) + '*'
  183. );
  184. const ƔAML_KEY = unirex(
  185. rexstr(ƔAML_DOUBLE_QUOTE) + '|' +
  186. rexstr(ƔAML_SINGLE_QUOTE) + '|' +
  187. rexstr(ƔAML_SIMPLE_KEY)
  188. );
  189. const ƔAML_VALUE = unirex(
  190. rexstr(ƔAML_DOUBLE_QUOTE) + '|' +
  191. rexstr(ƔAML_SINGLE_QUOTE) + '|' +
  192. rexstr(ƔAML_SIMPLE_VALUE)
  193. );
  194. const ƔAML_SEPARATOR = unirex(
  195. rexstr(ANY_WHITE_SPACE) +
  196. ':' + rexstr(WHITE_SPACE) +
  197. rexstr(ANY_WHITE_SPACE)
  198. );
  199. const ƔAML_LINE = unirex(
  200. '(' + rexstr(ƔAML_KEY) + ')' +
  201. rexstr(ƔAML_SEPARATOR) +
  202. '(' + rexstr(ƔAML_VALUE) + ')'
  203. );
  204. /* FRONTMATTER REGEX */
  205. const ƔAML_FRONTMATTER = unirex(
  206. rexstr(POSSIBLE_STARTS) +
  207. rexstr(ƔAML_LOOKAHEAD) +
  208. rexstr(ƔAML_START) + rexstr(SOME_NEW_LINES) +
  209. '(?:' +
  210. rexstr(ANY_WHITE_SPACE) + rexstr(ƔAML_LINE) + rexstr(SOME_NEW_LINES) +
  211. '){0,5}' +
  212. rexstr(ƔAML_END) + rexstr(POSSIBLE_ENDS)
  213. );
  214. /* SEARCHES */
  215. const FIND_ƔAML_LINE = unirex(
  216. rexstr(NEW_LINE) + rexstr(ANY_WHITE_SPACE) + rexstr(ƔAML_LINE)
  217. );
  218. /* STRING PROCESSING */
  219. function processString (str) {
  220. switch (str.charAt(0)) {
  221. case '"':
  222. return str.substring(1, str.length - 1);
  223. case '\'':
  224. return str
  225. .substring(1, str.length - 1)
  226. .replace(/''/g, '\'');
  227. default:
  228. return str;
  229. }
  230. }
  231. /* BIO PROCESSING */
  232. export function processBio(content) {
  233. content = content.replace(/&quot;/g, '"').replace(/&apos;/g, '\'');
  234. let result = {
  235. text: content,
  236. metadata: [],
  237. };
  238. let ɣaml = content.match(ƔAML_FRONTMATTER);
  239. if (!ɣaml) {
  240. return result;
  241. } else {
  242. ɣaml = ɣaml[0];
  243. }
  244. const start = content.search(ƔAML_START);
  245. const end = start + ɣaml.length - ɣaml.search(ƔAML_START);
  246. result.text = content.substr(end);
  247. let metadata = null;
  248. let query = new RegExp(rexstr(FIND_ƔAML_LINE), 'g'); // Some browsers don't allow flags unless both args are strings
  249. while ((metadata = query.exec(ɣaml))) {
  250. result.metadata.push([
  251. processString(metadata[1]),
  252. processString(metadata[2]),
  253. ]);
  254. }
  255. return result;
  256. }
  257. /* BIO CREATION */
  258. export function createBio(note, data) {
  259. if (!note) note = '';
  260. let frontmatter = '';
  261. if ((data && data.length) || note.match(/^\s*---\s+/)) {
  262. if (!data) frontmatter = '---\n...\n';
  263. else {
  264. frontmatter += '---\n';
  265. for (let i = 0; i < data.length; i++) {
  266. let key = '' + data[i][0];
  267. let val = '' + data[i][1];
  268. // Key processing
  269. if (key === (key.match(ƔAML_SIMPLE_KEY) || [])[0]) /* do nothing */;
  270. else if (key === (key.match(ANY_QUOTE_CHAR) || [])[0]) key = '"' + key + '"';
  271. else {
  272. key = key
  273. .replace(/'/g, '\'\'')
  274. .replace(new RegExp(rexstr(NOT_ALLOWED_CHAR), compat_mode ? 'g' : 'gu'), '�');
  275. key = '\'' + key + '\'';
  276. }
  277. // Value processing
  278. if (val === (val.match(ƔAML_SIMPLE_VALUE) || [])[0]) /* do nothing */;
  279. else if (val === (val.match(ANY_QUOTE_CHAR) || [])[0]) val = '"' + val + '"';
  280. else {
  281. key = key
  282. .replace(/'/g, '\'\'')
  283. .replace(new RegExp(rexstr(NOT_ALLOWED_CHAR), compat_mode ? 'g' : 'gu'), '�');
  284. key = '\'' + key + '\'';
  285. }
  286. frontmatter += key + ': ' + val + '\n';
  287. }
  288. frontmatter += '...\n';
  289. }
  290. }
  291. return frontmatter + note;
  292. }