forked from unifiedjs/unified
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1317 lines (1219 loc) · 39.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @import {Pipeline} from 'trough'
* @import {CompileResultMap, Data, Settings} from 'unified'
* @import {Node} from 'unist'
* @import {Compatible, Value} from 'vfile'
*/
/**
* @typedef {CompileResultMap[keyof CompileResultMap]} CompileResults
* Acceptable results from compilers.
*
* To register custom results, add them to
* {@linkcode CompileResultMap}.
*/
/**
* @template {Node} [Tree=Node]
* The node that the compiler receives (default: `Node`).
* @template {CompileResults} [Result=CompileResults]
* The thing that the compiler yields (default: `CompileResults`).
* @callback Compiler
* A **compiler** handles the compiling of a syntax tree to something else
* (in most cases, text) (TypeScript type).
*
* It is used in the stringify phase and called with a {@linkcode Node}
* and {@linkcode VFile} representation of the document to compile.
* It should return the textual representation of the given tree (typically
* `string`).
*
* > **Note**: unified typically compiles by serializing: most compilers
* > return `string` (or `Uint8Array`).
* > Some compilers, such as the one configured with
* > [`rehype-react`][rehype-react], return other values (in this case, a
* > React tree).
* > If you’re using a compiler that doesn’t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@linkcode CompileResultMap}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
* @param {Tree} tree
* Tree to compile.
* @param {VFile} file
* File associated with `tree`.
* @returns {Result}
* New content: compiled text (`string` or `Uint8Array`, for `file.value`) or
* something else (for `file.result`).
*/
/**
* @template {Node} [Tree=Node]
* The node that the parser yields (default: `Node`)
* @callback Parser
* A **parser** handles the parsing of text to a syntax tree.
*
* It is used in the parse phase and is called with a `string` and
* {@linkcode VFile} of the document to parse.
* It must return the syntax tree representation of the given file
* ({@linkcode Node}).
* @param {string} document
* Document to parse.
* @param {VFile} file
* File associated with `document`.
* @returns {Tree}
* Node representing the given file.
*/
/**
* @typedef {(
* Plugin<Array<any>, any, any> |
* PluginTuple<Array<any>, any, any> |
* Preset
* )} Pluggable
* Union of the different ways to add plugins and settings.
*/
/**
* @typedef {Array<Pluggable>} PluggableList
* List of plugins and presets.
*/
// Note: we can’t use `callback` yet as it messes up `this`:
// <https://github.com/microsoft/TypeScript/issues/55197>.
/**
* @template {Array<unknown>} [PluginParameters=[]]
* Arguments passed to the plugin (default: `[]`, the empty tuple).
* @template {Node | string | undefined} [Input=Node]
* Value that is expected as input (default: `Node`).
*
* * If the plugin returns a {@linkcode Transformer}, this
* should be the node it expects.
* * If the plugin sets a {@linkcode Parser}, this should be
* `string`.
* * If the plugin sets a {@linkcode Compiler}, this should be the
* node it expects.
* @template [Output=Input]
* Value that is yielded as output (default: `Input`).
*
* * If the plugin returns a {@linkcode Transformer}, this
* should be the node that that yields.
* * If the plugin sets a {@linkcode Parser}, this should be the
* node that it yields.
* * If the plugin sets a {@linkcode Compiler}, this should be
* result it yields.
* @typedef {(
* (this: Processor, ...parameters: PluginParameters) =>
* Input extends string ? // Parser.
* Output extends Node | undefined ? undefined | void : never :
* Output extends CompileResults ? // Compiler.
* Input extends Node | undefined ? undefined | void : never :
* Transformer<
* Input extends Node ? Input : Node,
* Output extends Node ? Output : Node
* > | undefined | void
* )} Plugin
* Single plugin.
*
* Plugins configure the processors they are applied on in the following
* ways:
*
* * they change the processor, such as the parser, the compiler, or by
* configuring data
* * they specify how to handle trees and files
*
* In practice, they are functions that can receive options and configure the
* processor (`this`).
*
* > **Note**: plugins are called when the processor is *frozen*, not when
* > they are applied.
*/
/**
* Tuple of a plugin and its configuration.
*
* The first item is a plugin, the rest are its parameters.
*
* @template {Array<unknown>} [TupleParameters=[]]
* Arguments passed to the plugin (default: `[]`, the empty tuple).
* @template {Node | string | undefined} [Input=undefined]
* Value that is expected as input (optional).
*
* * If the plugin returns a {@linkcode Transformer}, this
* should be the node it expects.
* * If the plugin sets a {@linkcode Parser}, this should be
* `string`.
* * If the plugin sets a {@linkcode Compiler}, this should be the
* node it expects.
* @template [Output=undefined] (optional).
* Value that is yielded as output.
*
* * If the plugin returns a {@linkcode Transformer}, this
* should be the node that that yields.
* * If the plugin sets a {@linkcode Parser}, this should be the
* node that it yields.
* * If the plugin sets a {@linkcode Compiler}, this should be
* result it yields.
* @typedef {(
* [
* plugin: Plugin<TupleParameters, Input, Output>,
* ...parameters: TupleParameters
* ]
* )} PluginTuple
*/
/**
* @typedef Preset
* Sharable configuration.
*
* They can contain plugins and settings.
* @property {PluggableList | undefined} [plugins]
* List of plugins and presets (optional).
* @property {Settings | undefined} [settings]
* Shared settings for parsers and compilers (optional).
*/
/**
* @template {VFile} [File=VFile]
* The file that the callback receives (default: `VFile`).
* @callback ProcessCallback
* Callback called when the process is done.
*
* Called with either an error or a result.
* @param {Error | undefined} [error]
* Fatal error (optional).
* @param {File | undefined} [file]
* Processed file (optional).
* @returns {undefined}
* Nothing.
*/
/**
* @template {Node} [Tree=Node]
* The tree that the callback receives (default: `Node`).
* @callback RunCallback
* Callback called when transformers are done.
*
* Called with either an error or results.
* @param {Error | undefined} [error]
* Fatal error (optional).
* @param {Tree | undefined} [tree]
* Transformed tree (optional).
* @param {VFile | undefined} [file]
* File (optional).
* @returns {undefined}
* Nothing.
*/
/**
* @template {Node} [Output=Node]
* Node type that the transformer yields (default: `Node`).
* @callback TransformCallback
* Callback passed to transforms.
*
* If the signature of a `transformer` accepts a third argument, the
* transformer may perform asynchronous operations, and must call it.
* @param {Error | undefined} [error]
* Fatal error to stop the process (optional).
* @param {Output | undefined} [tree]
* New, changed, tree (optional).
* @param {VFile | undefined} [file]
* New, changed, file (optional).
* @returns {undefined}
* Nothing.
*/
/**
* @template {Node} [Input=Node]
* Node type that the transformer expects (default: `Node`).
* @template {Node} [Output=Input]
* Node type that the transformer yields (default: `Input`).
* @callback Transformer
* Transformers handle syntax trees and files.
*
* They are functions that are called each time a syntax tree and file are
* passed through the run phase.
* When an error occurs in them (either because it’s thrown, returned,
* rejected, or passed to `next`), the process stops.
*
* The run phase is handled by [`trough`][trough], see its documentation for
* the exact semantics of these functions.
*
* > **Note**: you should likely ignore `next`: don’t accept it.
* > it supports callback-style async work.
* > But promises are likely easier to reason about.
*
* [trough]: https://github.com/wooorm/trough#function-fninput-next
* @param {Input} tree
* Tree to handle.
* @param {VFile} file
* File to handle.
* @param {TransformCallback<Output>} next
* Callback.
* @returns {(
* Promise<Output | undefined | void> |
* Promise<never> | // For some reason this is needed separately.
* Output |
* Error |
* undefined |
* void
* )}
* If you accept `next`, nothing.
* Otherwise:
*
* * `Error` — fatal error to stop the process
* * `Promise<undefined>` or `undefined` — the next transformer keeps using
* same tree
* * `Promise<Node>` or `Node` — new, changed, tree
*/
/**
* @template {Node | undefined} ParseTree
* Output of `parse`.
* @template {Node | undefined} HeadTree
* Input for `run`.
* @template {Node | undefined} TailTree
* Output for `run`.
* @template {Node | undefined} CompileTree
* Input of `stringify`.
* @template {CompileResults | undefined} CompileResult
* Output of `stringify`.
* @template {Node | string | undefined} Input
* Input of plugin.
* @template Output
* Output of plugin (optional).
* @typedef {(
* Input extends string
* ? Output extends Node | undefined
* ? // Parser.
* Processor<
* Output extends undefined ? ParseTree : Output,
* HeadTree,
* TailTree,
* CompileTree,
* CompileResult
* >
* : // Unknown.
* Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
* : Output extends CompileResults
* ? Input extends Node | undefined
* ? // Compiler.
* Processor<
* ParseTree,
* HeadTree,
* TailTree,
* Input extends undefined ? CompileTree : Input,
* Output extends undefined ? CompileResult : Output
* >
* : // Unknown.
* Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
* : Input extends Node | undefined
* ? Output extends Node | undefined
* ? // Transform.
* Processor<
* ParseTree,
* HeadTree extends undefined ? Input : HeadTree,
* Output extends undefined ? TailTree : Output,
* CompileTree,
* CompileResult
* >
* : // Unknown.
* Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
* : // Unknown.
* Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
* )} UsePlugin
* Create a processor based on the input/output of a {@link Plugin plugin}.
*/
/**
* @template {CompileResults | undefined} Result
* Node type that the transformer yields.
* @typedef {(
* Result extends Value | undefined ?
* VFile :
* VFile & {result: Result}
* )} VFileWithOutput
* Type to generate a {@linkcode VFile} corresponding to a compiler result.
*
* If a result that is not acceptable on a `VFile` is used, that will
* be stored on the `result` field of {@linkcode VFile}.
*/
import {bail} from 'bail'
import extend from 'extend'
import {ok as assert} from 'devlop'
import isPlainObj from 'is-plain-obj'
import {trough} from 'trough'
import {VFile} from 'vfile'
import {CallableInstance} from './callable-instance.js'
// To do: next major: drop `Compiler`, `Parser`: prefer lowercase.
// To do: we could start yielding `never` in TS when a parser is missing and
// `parse` is called.
// Currently, we allow directly setting `processor.parser`, which is untyped.
const own = {}.hasOwnProperty
/**
* @template {Node | undefined} [ParseTree=undefined]
* Output of `parse` (optional).
* @template {Node | undefined} [HeadTree=undefined]
* Input for `run` (optional).
* @template {Node | undefined} [TailTree=undefined]
* Output for `run` (optional).
* @template {Node | undefined} [CompileTree=undefined]
* Input of `stringify` (optional).
* @template {CompileResults | undefined} [CompileResult=undefined]
* Output of `stringify` (optional).
* @extends {CallableInstance<[], Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>>}
*/
export class Processor extends CallableInstance {
/**
* Create a processor.
*/
constructor() {
// If `Processor()` is called (w/o new), `copy` is called instead.
super('copy')
/**
* Compiler to use (deprecated).
*
* @deprecated
* Use `compiler` instead.
* @type {(
* Compiler<
* CompileTree extends undefined ? Node : CompileTree,
* CompileResult extends undefined ? CompileResults : CompileResult
* > |
* undefined
* )}
*/
this.Compiler = undefined
/**
* Parser to use (deprecated).
*
* @deprecated
* Use `parser` instead.
* @type {(
* Parser<ParseTree extends undefined ? Node : ParseTree> |
* undefined
* )}
*/
this.Parser = undefined
// Note: the following fields are considered private.
// However, they are needed for tests, and TSC generates an untyped
// `private freezeIndex` field for, which trips `type-coverage` up.
// Instead, we use `@deprecated` to visualize that they shouldn’t be used.
/**
* Internal list of configured plugins.
*
* @deprecated
* This is a private internal property and should not be used.
* @type {Array<PluginTuple<Array<unknown>>>}
*/
this.attachers = []
/**
* Compiler to use.
*
* @type {(
* Compiler<
* CompileTree extends undefined ? Node : CompileTree,
* CompileResult extends undefined ? CompileResults : CompileResult
* > |
* undefined
* )}
*/
this.compiler = undefined
/**
* Internal state to track where we are while freezing.
*
* @deprecated
* This is a private internal property and should not be used.
* @type {number}
*/
this.freezeIndex = -1
/**
* Internal state to track whether we’re frozen.
*
* @deprecated
* This is a private internal property and should not be used.
* @type {boolean | undefined}
*/
this.frozen = undefined
/**
* Internal state.
*
* @deprecated
* This is a private internal property and should not be used.
* @type {Data}
*/
this.namespace = {}
/**
* Parser to use.
*
* @type {(
* Parser<ParseTree extends undefined ? Node : ParseTree> |
* undefined
* )}
*/
this.parser = undefined
/**
* Internal list of configured transformers.
*
* @deprecated
* This is a private internal property and should not be used.
* @type {Pipeline}
*/
this.transformers = trough()
}
/**
* Copy a processor.
*
* @deprecated
* This is a private internal method and should not be used.
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
* New *unfrozen* processor ({@linkcode Processor}) that is
* configured to work the same as its ancestor.
* When the descendant processor is configured in the future it does not
* affect the ancestral processor.
*/
copy() {
// Cast as the type parameters will be the same after attaching.
const destination =
/** @type {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} */ (
new Processor()
)
let index = -1
while (++index < this.attachers.length) {
const attacher = this.attachers[index]
destination.use(...attacher)
}
destination.data(extend(true, {}, this.namespace))
return destination
}
/**
* Configure the processor with info available to all plugins.
* Information is stored in an object.
*
* Typically, options can be given to a specific plugin, but sometimes it
* makes sense to have information shared with several plugins.
* For example, a list of HTML elements that are self-closing, which is
* needed during all phases.
*
* > **Note**: setting information cannot occur on *frozen* processors.
* > Call the processor first to create a new unfrozen processor.
*
* > **Note**: to register custom data in TypeScript, augment the
* > {@linkcode Data} interface.
*
* @example
* This example show how to get and set info:
*
* ```js
* import {unified} from 'unified'
*
* const processor = unified().data('alpha', 'bravo')
*
* processor.data('alpha') // => 'bravo'
*
* processor.data() // => {alpha: 'bravo'}
*
* processor.data({charlie: 'delta'})
*
* processor.data() // => {charlie: 'delta'}
* ```
*
* @template {keyof Data} Key
*
* @overload
* @returns {Data}
*
* @overload
* @param {Data} dataset
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
*
* @overload
* @param {Key} key
* @returns {Data[Key]}
*
* @overload
* @param {Key} key
* @param {Data[Key]} value
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
*
* @param {Data | Key} [key]
* Key to get or set, or entire dataset to set, or nothing to get the
* entire dataset (optional).
* @param {Data[Key]} [value]
* Value to set (optional).
* @returns {unknown}
* The current processor when setting, the value at `key` when getting, or
* the entire dataset when getting without key.
*/
data(key, value) {
if (typeof key === 'string') {
// Set `key`.
if (arguments.length === 2) {
assertUnfrozen('data', this.frozen)
this.namespace[key] = value
return this
}
// Get `key`.
return (own.call(this.namespace, key) && this.namespace[key]) || undefined
}
// Set space.
if (key) {
assertUnfrozen('data', this.frozen)
this.namespace = key
return this
}
// Get space.
return this.namespace
}
/**
* Freeze a processor.
*
* Frozen processors are meant to be extended and not to be configured
* directly.
*
* When a processor is frozen it cannot be unfrozen.
* New processors working the same way can be created by calling the
* processor.
*
* It’s possible to freeze processors explicitly by calling `.freeze()`.
* Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,
* `.stringify()`, `.process()`, or `.processSync()` are called.
*
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
* The current processor.
*/
freeze() {
if (this.frozen) {
return this
}
// Cast so that we can type plugins easier.
// Plugins are supposed to be usable on different processors, not just on
// this exact processor.
const self = /** @type {Processor} */ (/** @type {unknown} */ (this))
while (++this.freezeIndex < this.attachers.length) {
const [attacher, ...options] = this.attachers[this.freezeIndex]
if (options[0] === false) {
continue
}
if (options[0] === true) {
options[0] = undefined
}
const transformer = attacher.call(self, ...options)
if (typeof transformer === 'function') {
this.transformers.use(transformer)
}
}
this.frozen = true
this.freezeIndex = Number.POSITIVE_INFINITY
return this
}
/**
* Parse text to a syntax tree.
*
* > **Note**: `parse` freezes the processor if not already *frozen*.
*
* > **Note**: `parse` performs the parse phase, not the run phase or other
* > phases.
*
* @param {Compatible | undefined} [file]
* file to parse (optional); typically `string` or `VFile`; any value
* accepted as `x` in `new VFile(x)`.
* @returns {ParseTree extends undefined ? Node : ParseTree}
* Syntax tree representing `file`.
*/
parse(file) {
this.freeze()
const realFile = vfile(file)
const parser = this.parser || this.Parser
assertParser('parse', parser)
return parser(String(realFile), realFile)
}
/**
* Process the given file as configured on the processor.
*
* > **Note**: `process` freezes the processor if not already *frozen*.
*
* > **Note**: `process` performs the parse, run, and stringify phases.
*
* @overload
* @param {Compatible | undefined} file
* @param {ProcessCallback<VFileWithOutput<CompileResult>>} done
* @returns {undefined}
*
* @overload
* @param {Compatible | undefined} [file]
* @returns {Promise<VFileWithOutput<CompileResult>>}
*
* @param {Compatible | undefined} [file]
* File (optional); typically `string` or `VFile`]; any value accepted as
* `x` in `new VFile(x)`.
* @param {ProcessCallback<VFileWithOutput<CompileResult>> | undefined} [done]
* Callback (optional).
* @returns {Promise<VFile> | undefined}
* Nothing if `done` is given.
* Otherwise a promise, rejected with a fatal error or resolved with the
* processed file.
*
* The parsed, transformed, and compiled value is available at
* `file.value` (see note).
*
* > **Note**: unified typically compiles by serializing: most
* > compilers return `string` (or `Uint8Array`).
* > Some compilers, such as the one configured with
* > [`rehype-react`][rehype-react], return other values (in this case, a
* > React tree).
* > If you’re using a compiler that doesn’t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@linkcode CompileResultMap}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
process(file, done) {
const self = this
this.freeze()
assertParser('process', this.parser || this.Parser)
assertCompiler('process', this.compiler || this.Compiler)
return done ? executor(undefined, done) : new Promise(executor)
// Note: `void`s needed for TS.
/**
* @param {((file: VFileWithOutput<CompileResult>) => undefined | void) | undefined} resolve
* @param {(error: Error | undefined) => undefined | void} reject
* @returns {undefined}
*/
function executor(resolve, reject) {
const realFile = vfile(file)
// Assume `ParseTree` (the result of the parser) matches `HeadTree` (the
// input of the first transform).
const parseTree =
/** @type {HeadTree extends undefined ? Node : HeadTree} */ (
/** @type {unknown} */ (self.parse(realFile))
)
self.run(parseTree, realFile, function (error, tree, file) {
if (error || !tree || !file) {
return realDone(error)
}
// Assume `TailTree` (the output of the last transform) matches
// `CompileTree` (the input of the compiler).
const compileTree =
/** @type {CompileTree extends undefined ? Node : CompileTree} */ (
/** @type {unknown} */ (tree)
)
const compileResult = self.stringify(compileTree, file)
if (looksLikeAValue(compileResult)) {
file.value = compileResult
} else {
file.result = compileResult
}
realDone(error, /** @type {VFileWithOutput<CompileResult>} */ (file))
})
/**
* @param {Error | undefined} error
* @param {VFileWithOutput<CompileResult> | undefined} [file]
* @returns {undefined}
*/
function realDone(error, file) {
if (error || !file) {
reject(error)
} else if (resolve) {
resolve(file)
} else {
assert(done, '`done` is defined if `resolve` is not')
done(undefined, file)
}
}
}
}
/**
* Process the given file as configured on the processor.
*
* An error is thrown if asynchronous transforms are configured.
*
* > **Note**: `processSync` freezes the processor if not already *frozen*.
*
* > **Note**: `processSync` performs the parse, run, and stringify phases.
*
* @param {Compatible | undefined} [file]
* File (optional); typically `string` or `VFile`; any value accepted as
* `x` in `new VFile(x)`.
* @returns {VFileWithOutput<CompileResult>}
* The processed file.
*
* The parsed, transformed, and compiled value is available at
* `file.value` (see note).
*
* > **Note**: unified typically compiles by serializing: most
* > compilers return `string` (or `Uint8Array`).
* > Some compilers, such as the one configured with
* > [`rehype-react`][rehype-react], return other values (in this case, a
* > React tree).
* > If you’re using a compiler that doesn’t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@linkcode CompileResultMap}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
processSync(file) {
/** @type {boolean} */
let complete = false
/** @type {VFileWithOutput<CompileResult> | undefined} */
let result
this.freeze()
assertParser('processSync', this.parser || this.Parser)
assertCompiler('processSync', this.compiler || this.Compiler)
this.process(file, realDone)
assertDone('processSync', 'process', complete)
assert(result, 'we either bailed on an error or have a tree')
return result
/**
* @type {ProcessCallback<VFileWithOutput<CompileResult>>}
*/
function realDone(error, file) {
complete = true
bail(error)
result = file
}
}
/**
* Run *transformers* on a syntax tree.
*
* > **Note**: `run` freezes the processor if not already *frozen*.
*
* > **Note**: `run` performs the run phase, not other phases.
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
* @returns {undefined}
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {Compatible | undefined} file
* @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
* @returns {undefined}
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {Compatible | undefined} [file]
* @returns {Promise<TailTree extends undefined ? Node : TailTree>}
*
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* Tree to transform and inspect.
* @param {(
* RunCallback<TailTree extends undefined ? Node : TailTree> |
* Compatible
* )} [file]
* File associated with `node` (optional); any value accepted as `x` in
* `new VFile(x)`.
* @param {RunCallback<TailTree extends undefined ? Node : TailTree>} [done]
* Callback (optional).
* @returns {Promise<TailTree extends undefined ? Node : TailTree> | undefined}
* Nothing if `done` is given.
* Otherwise, a promise rejected with a fatal error or resolved with the
* transformed tree.
*/
run(tree, file, done) {
assertNode(tree)
this.freeze()
const transformers = this.transformers
if (!done && typeof file === 'function') {
done = file
file = undefined
}
return done ? executor(undefined, done) : new Promise(executor)
// Note: `void`s needed for TS.
/**
* @param {(
* ((tree: TailTree extends undefined ? Node : TailTree) => undefined | void) |
* undefined
* )} resolve
* @param {(error: Error) => undefined | void} reject
* @returns {undefined}
*/
function executor(resolve, reject) {
assert(
typeof file !== 'function',
'`file` can’t be a `done` anymore, we checked'
)
const realFile = vfile(file)
transformers.run(tree, realFile, realDone)
/**
* @param {Error | undefined} error
* @param {Node} outputTree
* @param {VFile} file
* @returns {undefined}
*/
function realDone(error, outputTree, file) {
const resultingTree =
/** @type {TailTree extends undefined ? Node : TailTree} */ (
outputTree || tree
)
if (error) {
reject(error)
} else if (resolve) {
resolve(resultingTree)
} else {
assert(done, '`done` is defined if `resolve` is not')
done(undefined, resultingTree, file)
}
}
}
}
/**
* Run *transformers* on a syntax tree.
*
* An error is thrown if asynchronous transforms are configured.
*
* > **Note**: `runSync` freezes the processor if not already *frozen*.
*
* > **Note**: `runSync` performs the run phase, not other phases.
*
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* Tree to transform and inspect.
* @param {Compatible | undefined} [file]
* File associated with `node` (optional); any value accepted as `x` in
* `new VFile(x)`.
* @returns {TailTree extends undefined ? Node : TailTree}
* Transformed tree.
*/
runSync(tree, file) {
/** @type {boolean} */
let complete = false
/** @type {(TailTree extends undefined ? Node : TailTree) | undefined} */
let result
this.run(tree, file, realDone)
assertDone('runSync', 'run', complete)
assert(result, 'we either bailed on an error or have a tree')
return result
/**
* @type {RunCallback<TailTree extends undefined ? Node : TailTree>}
*/
function realDone(error, tree) {
bail(error)
result = tree
complete = true
}
}
/**
* Compile a syntax tree.
*
* > **Note**: `stringify` freezes the processor if not already *frozen*.
*
* > **Note**: `stringify` performs the stringify phase, not the run phase
* > or other phases.
*
* @param {CompileTree extends undefined ? Node : CompileTree} tree
* Tree to compile.
* @param {Compatible | undefined} [file]
* File associated with `node` (optional); any value accepted as `x` in
* `new VFile(x)`.
* @returns {CompileResult extends undefined ? Value : CompileResult}
* Textual representation of the tree (see note).
*
* > **Note**: unified typically compiles by serializing: most compilers
* > return `string` (or `Uint8Array`).
* > Some compilers, such as the one configured with
* > [`rehype-react`][rehype-react], return other values (in this case, a
* > React tree).
* > If you’re using a compiler that doesn’t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@linkcode CompileResultMap}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
stringify(tree, file) {
this.freeze()
const realFile = vfile(file)
const compiler = this.compiler || this.Compiler
assertCompiler('stringify', compiler)
assertNode(tree)
return compiler(tree, realFile)
}
/**
* Configure the processor to use a plugin, a list of usable values, or a