index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /**
  2. * @typedef {import('unist').Node} Node
  3. * @typedef {import('unist').Point} Point
  4. * @typedef {import('unist').Position} Position
  5. * @typedef {import('vfile-message').Options} MessageOptions
  6. * @typedef {import('../index.js').Data} Data
  7. * @typedef {import('../index.js').Value} Value
  8. */
  9. /**
  10. * @typedef {object & {type: string, position?: Position | undefined}} NodeLike
  11. *
  12. * @typedef {Options | URL | VFile | Value} Compatible
  13. * Things that can be passed to the constructor.
  14. *
  15. * @typedef VFileCoreOptions
  16. * Set multiple values.
  17. * @property {string | null | undefined} [basename]
  18. * Set `basename` (name).
  19. * @property {string | null | undefined} [cwd]
  20. * Set `cwd` (working directory).
  21. * @property {Data | null | undefined} [data]
  22. * Set `data` (associated info).
  23. * @property {string | null | undefined} [dirname]
  24. * Set `dirname` (path w/o basename).
  25. * @property {string | null | undefined} [extname]
  26. * Set `extname` (extension with dot).
  27. * @property {Array<string> | null | undefined} [history]
  28. * Set `history` (paths the file moved between).
  29. * @property {URL | string | null | undefined} [path]
  30. * Set `path` (current path).
  31. * @property {string | null | undefined} [stem]
  32. * Set `stem` (name without extension).
  33. * @property {Value | null | undefined} [value]
  34. * Set `value` (the contents of the file).
  35. *
  36. * @typedef Map
  37. * Raw source map.
  38. *
  39. * See:
  40. * <https://github.com/mozilla/source-map/blob/60adcb0/source-map.d.ts#L15-L23>.
  41. * @property {number} version
  42. * Which version of the source map spec this map is following.
  43. * @property {Array<string>} sources
  44. * An array of URLs to the original source files.
  45. * @property {Array<string>} names
  46. * An array of identifiers which can be referenced by individual mappings.
  47. * @property {string | undefined} [sourceRoot]
  48. * The URL root from which all sources are relative.
  49. * @property {Array<string> | undefined} [sourcesContent]
  50. * An array of contents of the original source files.
  51. * @property {string} mappings
  52. * A string of base64 VLQs which contain the actual mappings.
  53. * @property {string} file
  54. * The generated file this source map is associated with.
  55. *
  56. * @typedef {Record<string, unknown> & VFileCoreOptions} Options
  57. * Configuration.
  58. *
  59. * A bunch of keys that will be shallow copied over to the new file.
  60. *
  61. * @typedef {Record<string, unknown>} ReporterSettings
  62. * Configuration for reporters.
  63. */
  64. /**
  65. * @template [Settings=ReporterSettings]
  66. * Options type.
  67. * @callback Reporter
  68. * Type for a reporter.
  69. * @param {Array<VFile>} files
  70. * Files to report.
  71. * @param {Settings} options
  72. * Configuration.
  73. * @returns {string}
  74. * Report.
  75. */
  76. import {VFileMessage} from 'vfile-message'
  77. import {path} from 'vfile/do-not-use-conditional-minpath'
  78. import {proc} from 'vfile/do-not-use-conditional-minproc'
  79. import {urlToPath, isUrl} from 'vfile/do-not-use-conditional-minurl'
  80. /**
  81. * Order of setting (least specific to most), we need this because otherwise
  82. * `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a
  83. * stem can be set.
  84. */
  85. const order = /** @type {const} */ ([
  86. 'history',
  87. 'path',
  88. 'basename',
  89. 'stem',
  90. 'extname',
  91. 'dirname'
  92. ])
  93. export class VFile {
  94. /**
  95. * Create a new virtual file.
  96. *
  97. * `options` is treated as:
  98. *
  99. * * `string` or `Uint8Array` — `{value: options}`
  100. * * `URL` — `{path: options}`
  101. * * `VFile` — shallow copies its data over to the new file
  102. * * `object` — all fields are shallow copied over to the new file
  103. *
  104. * Path related fields are set in the following order (least specific to
  105. * most specific): `history`, `path`, `basename`, `stem`, `extname`,
  106. * `dirname`.
  107. *
  108. * You cannot set `dirname` or `extname` without setting either `history`,
  109. * `path`, `basename`, or `stem` too.
  110. *
  111. * @param {Compatible | null | undefined} [value]
  112. * File value.
  113. * @returns
  114. * New instance.
  115. */
  116. constructor(value) {
  117. /** @type {Options | VFile} */
  118. let options
  119. if (!value) {
  120. options = {}
  121. } else if (isUrl(value)) {
  122. options = {path: value}
  123. } else if (typeof value === 'string' || isUint8Array(value)) {
  124. options = {value}
  125. } else {
  126. options = value
  127. }
  128. /* eslint-disable no-unused-expressions */
  129. /**
  130. * Base of `path` (default: `process.cwd()` or `'/'` in browsers).
  131. *
  132. * @type {string}
  133. */
  134. this.cwd = proc.cwd()
  135. /**
  136. * Place to store custom info (default: `{}`).
  137. *
  138. * It’s OK to store custom data directly on the file but moving it to
  139. * `data` is recommended.
  140. *
  141. * @type {Data}
  142. */
  143. this.data = {}
  144. /**
  145. * List of file paths the file moved between.
  146. *
  147. * The first is the original path and the last is the current path.
  148. *
  149. * @type {Array<string>}
  150. */
  151. this.history = []
  152. /**
  153. * List of messages associated with the file.
  154. *
  155. * @type {Array<VFileMessage>}
  156. */
  157. this.messages = []
  158. /**
  159. * Raw value.
  160. *
  161. * @type {Value}
  162. */
  163. this.value
  164. // The below are non-standard, they are “well-known”.
  165. // As in, used in several tools.
  166. /**
  167. * Source map.
  168. *
  169. * This type is equivalent to the `RawSourceMap` type from the `source-map`
  170. * module.
  171. *
  172. * @type {Map | null | undefined}
  173. */
  174. this.map
  175. /**
  176. * Custom, non-string, compiled, representation.
  177. *
  178. * This is used by unified to store non-string results.
  179. * One example is when turning markdown into React nodes.
  180. *
  181. * @type {unknown}
  182. */
  183. this.result
  184. /**
  185. * Whether a file was saved to disk.
  186. *
  187. * This is used by vfile reporters.
  188. *
  189. * @type {boolean}
  190. */
  191. this.stored
  192. /* eslint-enable no-unused-expressions */
  193. // Set path related properties in the correct order.
  194. let index = -1
  195. while (++index < order.length) {
  196. const prop = order[index]
  197. // Note: we specifically use `in` instead of `hasOwnProperty` to accept
  198. // `vfile`s too.
  199. if (
  200. prop in options &&
  201. options[prop] !== undefined &&
  202. options[prop] !== null
  203. ) {
  204. // @ts-expect-error: TS doesn’t understand basic reality.
  205. this[prop] = prop === 'history' ? [...options[prop]] : options[prop]
  206. }
  207. }
  208. /** @type {string} */
  209. let prop
  210. // Set non-path related properties.
  211. for (prop in options) {
  212. // @ts-expect-error: fine to set other things.
  213. if (!order.includes(prop)) {
  214. // @ts-expect-error: fine to set other things.
  215. this[prop] = options[prop]
  216. }
  217. }
  218. }
  219. /**
  220. * Get the basename (including extname) (example: `'index.min.js'`).
  221. *
  222. * @returns {string | undefined}
  223. * Basename.
  224. */
  225. get basename() {
  226. return typeof this.path === 'string' ? path.basename(this.path) : undefined
  227. }
  228. /**
  229. * Set basename (including extname) (`'index.min.js'`).
  230. *
  231. * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
  232. * on windows).
  233. * Cannot be nullified (use `file.path = file.dirname` instead).
  234. *
  235. * @param {string} basename
  236. * Basename.
  237. * @returns {undefined}
  238. * Nothing.
  239. */
  240. set basename(basename) {
  241. assertNonEmpty(basename, 'basename')
  242. assertPart(basename, 'basename')
  243. this.path = path.join(this.dirname || '', basename)
  244. }
  245. /**
  246. * Get the parent path (example: `'~'`).
  247. *
  248. * @returns {string | undefined}
  249. * Dirname.
  250. */
  251. get dirname() {
  252. return typeof this.path === 'string' ? path.dirname(this.path) : undefined
  253. }
  254. /**
  255. * Set the parent path (example: `'~'`).
  256. *
  257. * Cannot be set if there’s no `path` yet.
  258. *
  259. * @param {string | undefined} dirname
  260. * Dirname.
  261. * @returns {undefined}
  262. * Nothing.
  263. */
  264. set dirname(dirname) {
  265. assertPath(this.basename, 'dirname')
  266. this.path = path.join(dirname || '', this.basename)
  267. }
  268. /**
  269. * Get the extname (including dot) (example: `'.js'`).
  270. *
  271. * @returns {string | undefined}
  272. * Extname.
  273. */
  274. get extname() {
  275. return typeof this.path === 'string' ? path.extname(this.path) : undefined
  276. }
  277. /**
  278. * Set the extname (including dot) (example: `'.js'`).
  279. *
  280. * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
  281. * on windows).
  282. * Cannot be set if there’s no `path` yet.
  283. *
  284. * @param {string | undefined} extname
  285. * Extname.
  286. * @returns {undefined}
  287. * Nothing.
  288. */
  289. set extname(extname) {
  290. assertPart(extname, 'extname')
  291. assertPath(this.dirname, 'extname')
  292. if (extname) {
  293. if (extname.codePointAt(0) !== 46 /* `.` */) {
  294. throw new Error('`extname` must start with `.`')
  295. }
  296. if (extname.includes('.', 1)) {
  297. throw new Error('`extname` cannot contain multiple dots')
  298. }
  299. }
  300. this.path = path.join(this.dirname, this.stem + (extname || ''))
  301. }
  302. /**
  303. * Get the full path (example: `'~/index.min.js'`).
  304. *
  305. * @returns {string}
  306. * Path.
  307. */
  308. get path() {
  309. return this.history[this.history.length - 1]
  310. }
  311. /**
  312. * Set the full path (example: `'~/index.min.js'`).
  313. *
  314. * Cannot be nullified.
  315. * You can set a file URL (a `URL` object with a `file:` protocol) which will
  316. * be turned into a path with `url.fileURLToPath`.
  317. *
  318. * @param {URL | string} path
  319. * Path.
  320. * @returns {undefined}
  321. * Nothing.
  322. */
  323. set path(path) {
  324. if (isUrl(path)) {
  325. path = urlToPath(path)
  326. }
  327. assertNonEmpty(path, 'path')
  328. if (this.path !== path) {
  329. this.history.push(path)
  330. }
  331. }
  332. /**
  333. * Get the stem (basename w/o extname) (example: `'index.min'`).
  334. *
  335. * @returns {string | undefined}
  336. * Stem.
  337. */
  338. get stem() {
  339. return typeof this.path === 'string'
  340. ? path.basename(this.path, this.extname)
  341. : undefined
  342. }
  343. /**
  344. * Set the stem (basename w/o extname) (example: `'index.min'`).
  345. *
  346. * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
  347. * on windows).
  348. * Cannot be nullified (use `file.path = file.dirname` instead).
  349. *
  350. * @param {string} stem
  351. * Stem.
  352. * @returns {undefined}
  353. * Nothing.
  354. */
  355. set stem(stem) {
  356. assertNonEmpty(stem, 'stem')
  357. assertPart(stem, 'stem')
  358. this.path = path.join(this.dirname || '', stem + (this.extname || ''))
  359. }
  360. // Normal prototypal methods.
  361. /**
  362. * Create a fatal message for `reason` associated with the file.
  363. *
  364. * The `fatal` field of the message is set to `true` (error; file not usable)
  365. * and the `file` field is set to the current file path.
  366. * The message is added to the `messages` field on `file`.
  367. *
  368. * > 🪦 **Note**: also has obsolete signatures.
  369. *
  370. * @overload
  371. * @param {string} reason
  372. * @param {MessageOptions | null | undefined} [options]
  373. * @returns {never}
  374. *
  375. * @overload
  376. * @param {string} reason
  377. * @param {Node | NodeLike | null | undefined} parent
  378. * @param {string | null | undefined} [origin]
  379. * @returns {never}
  380. *
  381. * @overload
  382. * @param {string} reason
  383. * @param {Point | Position | null | undefined} place
  384. * @param {string | null | undefined} [origin]
  385. * @returns {never}
  386. *
  387. * @overload
  388. * @param {string} reason
  389. * @param {string | null | undefined} [origin]
  390. * @returns {never}
  391. *
  392. * @overload
  393. * @param {Error | VFileMessage} cause
  394. * @param {Node | NodeLike | null | undefined} parent
  395. * @param {string | null | undefined} [origin]
  396. * @returns {never}
  397. *
  398. * @overload
  399. * @param {Error | VFileMessage} cause
  400. * @param {Point | Position | null | undefined} place
  401. * @param {string | null | undefined} [origin]
  402. * @returns {never}
  403. *
  404. * @overload
  405. * @param {Error | VFileMessage} cause
  406. * @param {string | null | undefined} [origin]
  407. * @returns {never}
  408. *
  409. * @param {Error | VFileMessage | string} causeOrReason
  410. * Reason for message, should use markdown.
  411. * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
  412. * Configuration (optional).
  413. * @param {string | null | undefined} [origin]
  414. * Place in code where the message originates (example:
  415. * `'my-package:my-rule'` or `'my-rule'`).
  416. * @returns {never}
  417. * Never.
  418. * @throws {VFileMessage}
  419. * Message.
  420. */
  421. fail(causeOrReason, optionsOrParentOrPlace, origin) {
  422. // @ts-expect-error: the overloads are fine.
  423. const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)
  424. message.fatal = true
  425. throw message
  426. }
  427. /**
  428. * Create an info message for `reason` associated with the file.
  429. *
  430. * The `fatal` field of the message is set to `undefined` (info; change
  431. * likely not needed) and the `file` field is set to the current file path.
  432. * The message is added to the `messages` field on `file`.
  433. *
  434. * > 🪦 **Note**: also has obsolete signatures.
  435. *
  436. * @overload
  437. * @param {string} reason
  438. * @param {MessageOptions | null | undefined} [options]
  439. * @returns {VFileMessage}
  440. *
  441. * @overload
  442. * @param {string} reason
  443. * @param {Node | NodeLike | null | undefined} parent
  444. * @param {string | null | undefined} [origin]
  445. * @returns {VFileMessage}
  446. *
  447. * @overload
  448. * @param {string} reason
  449. * @param {Point | Position | null | undefined} place
  450. * @param {string | null | undefined} [origin]
  451. * @returns {VFileMessage}
  452. *
  453. * @overload
  454. * @param {string} reason
  455. * @param {string | null | undefined} [origin]
  456. * @returns {VFileMessage}
  457. *
  458. * @overload
  459. * @param {Error | VFileMessage} cause
  460. * @param {Node | NodeLike | null | undefined} parent
  461. * @param {string | null | undefined} [origin]
  462. * @returns {VFileMessage}
  463. *
  464. * @overload
  465. * @param {Error | VFileMessage} cause
  466. * @param {Point | Position | null | undefined} place
  467. * @param {string | null | undefined} [origin]
  468. * @returns {VFileMessage}
  469. *
  470. * @overload
  471. * @param {Error | VFileMessage} cause
  472. * @param {string | null | undefined} [origin]
  473. * @returns {VFileMessage}
  474. *
  475. * @param {Error | VFileMessage | string} causeOrReason
  476. * Reason for message, should use markdown.
  477. * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
  478. * Configuration (optional).
  479. * @param {string | null | undefined} [origin]
  480. * Place in code where the message originates (example:
  481. * `'my-package:my-rule'` or `'my-rule'`).
  482. * @returns {VFileMessage}
  483. * Message.
  484. */
  485. info(causeOrReason, optionsOrParentOrPlace, origin) {
  486. // @ts-expect-error: the overloads are fine.
  487. const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)
  488. message.fatal = undefined
  489. return message
  490. }
  491. /**
  492. * Create a message for `reason` associated with the file.
  493. *
  494. * The `fatal` field of the message is set to `false` (warning; change may be
  495. * needed) and the `file` field is set to the current file path.
  496. * The message is added to the `messages` field on `file`.
  497. *
  498. * > 🪦 **Note**: also has obsolete signatures.
  499. *
  500. * @overload
  501. * @param {string} reason
  502. * @param {MessageOptions | null | undefined} [options]
  503. * @returns {VFileMessage}
  504. *
  505. * @overload
  506. * @param {string} reason
  507. * @param {Node | NodeLike | null | undefined} parent
  508. * @param {string | null | undefined} [origin]
  509. * @returns {VFileMessage}
  510. *
  511. * @overload
  512. * @param {string} reason
  513. * @param {Point | Position | null | undefined} place
  514. * @param {string | null | undefined} [origin]
  515. * @returns {VFileMessage}
  516. *
  517. * @overload
  518. * @param {string} reason
  519. * @param {string | null | undefined} [origin]
  520. * @returns {VFileMessage}
  521. *
  522. * @overload
  523. * @param {Error | VFileMessage} cause
  524. * @param {Node | NodeLike | null | undefined} parent
  525. * @param {string | null | undefined} [origin]
  526. * @returns {VFileMessage}
  527. *
  528. * @overload
  529. * @param {Error | VFileMessage} cause
  530. * @param {Point | Position | null | undefined} place
  531. * @param {string | null | undefined} [origin]
  532. * @returns {VFileMessage}
  533. *
  534. * @overload
  535. * @param {Error | VFileMessage} cause
  536. * @param {string | null | undefined} [origin]
  537. * @returns {VFileMessage}
  538. *
  539. * @param {Error | VFileMessage | string} causeOrReason
  540. * Reason for message, should use markdown.
  541. * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
  542. * Configuration (optional).
  543. * @param {string | null | undefined} [origin]
  544. * Place in code where the message originates (example:
  545. * `'my-package:my-rule'` or `'my-rule'`).
  546. * @returns {VFileMessage}
  547. * Message.
  548. */
  549. message(causeOrReason, optionsOrParentOrPlace, origin) {
  550. const message = new VFileMessage(
  551. // @ts-expect-error: the overloads are fine.
  552. causeOrReason,
  553. optionsOrParentOrPlace,
  554. origin
  555. )
  556. if (this.path) {
  557. message.name = this.path + ':' + message.name
  558. message.file = this.path
  559. }
  560. message.fatal = false
  561. this.messages.push(message)
  562. return message
  563. }
  564. /**
  565. * Serialize the file.
  566. *
  567. * > **Note**: which encodings are supported depends on the engine.
  568. * > For info on Node.js, see:
  569. * > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.
  570. *
  571. * @param {string | null | undefined} [encoding='utf8']
  572. * Character encoding to understand `value` as when it’s a `Uint8Array`
  573. * (default: `'utf-8'`).
  574. * @returns {string}
  575. * Serialized file.
  576. */
  577. toString(encoding) {
  578. if (this.value === undefined) {
  579. return ''
  580. }
  581. if (typeof this.value === 'string') {
  582. return this.value
  583. }
  584. const decoder = new TextDecoder(encoding || undefined)
  585. return decoder.decode(this.value)
  586. }
  587. }
  588. /**
  589. * Assert that `part` is not a path (as in, does not contain `path.sep`).
  590. *
  591. * @param {string | null | undefined} part
  592. * File path part.
  593. * @param {string} name
  594. * Part name.
  595. * @returns {undefined}
  596. * Nothing.
  597. */
  598. function assertPart(part, name) {
  599. if (part && part.includes(path.sep)) {
  600. throw new Error(
  601. '`' + name + '` cannot be a path: did not expect `' + path.sep + '`'
  602. )
  603. }
  604. }
  605. /**
  606. * Assert that `part` is not empty.
  607. *
  608. * @param {string | undefined} part
  609. * Thing.
  610. * @param {string} name
  611. * Part name.
  612. * @returns {asserts part is string}
  613. * Nothing.
  614. */
  615. function assertNonEmpty(part, name) {
  616. if (!part) {
  617. throw new Error('`' + name + '` cannot be empty')
  618. }
  619. }
  620. /**
  621. * Assert `path` exists.
  622. *
  623. * @param {string | undefined} path
  624. * Path.
  625. * @param {string} name
  626. * Dependency name.
  627. * @returns {asserts path is string}
  628. * Nothing.
  629. */
  630. function assertPath(path, name) {
  631. if (!path) {
  632. throw new Error('Setting `' + name + '` requires `path` to be set too')
  633. }
  634. }
  635. /**
  636. * Assert `value` is an `Uint8Array`.
  637. *
  638. * @param {unknown} value
  639. * thing.
  640. * @returns {value is Uint8Array}
  641. * Whether `value` is an `Uint8Array`.
  642. */
  643. function isUint8Array(value) {
  644. return Boolean(
  645. value &&
  646. typeof value === 'object' &&
  647. 'byteLength' in value &&
  648. 'byteOffset' in value
  649. )
  650. }