UNPKG

2.77 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5"use strict";
6
7const Source = require("./Source");
8const RawSource = require("./RawSource");
9const streamChunks = require("./helpers/streamChunks");
10const { getMap, getSourceAndMap } = require("./helpers/getFromStreamChunks");
11
12const REPLACE_REGEX = /\n(?=.|\s)/g;
13
14class PrefixSource extends Source {
15 constructor(prefix, source) {
16 super();
17 this._source =
18 typeof source === "string" || Buffer.isBuffer(source)
19 ? new RawSource(source, true)
20 : source;
21 this._prefix = prefix;
22 }
23
24 getPrefix() {
25 return this._prefix;
26 }
27
28 original() {
29 return this._source;
30 }
31
32 source() {
33 const node = this._source.source();
34 const prefix = this._prefix;
35 return prefix + node.replace(REPLACE_REGEX, "\n" + prefix);
36 }
37
38 // TODO efficient buffer() implementation
39
40 map(options) {
41 return getMap(this, options);
42 }
43
44 sourceAndMap(options) {
45 return getSourceAndMap(this, options);
46 }
47
48 streamChunks(options, onChunk, onSource, onName) {
49 const prefix = this._prefix;
50 const prefixOffset = prefix.length;
51 const linesOnly = !!(options && options.columns === false);
52 const { generatedLine, generatedColumn, source } = streamChunks(
53 this._source,
54 options,
55 (
56 chunk,
57 generatedLine,
58 generatedColumn,
59 sourceIndex,
60 originalLine,
61 originalColumn,
62 nameIndex
63 ) => {
64 if (generatedColumn !== 0) {
65 // In the middle of the line, we just adject the column
66 generatedColumn += prefixOffset;
67 } else if (chunk !== undefined) {
68 // At the start of the line, when we have source content
69 // add the prefix as generated mapping
70 // (in lines only mode we just add it to the original mapping
71 // for performance reasons)
72 if (linesOnly || sourceIndex < 0) {
73 chunk = prefix + chunk;
74 } else {
75 onChunk(prefix, generatedLine, generatedColumn, -1, -1, -1, -1);
76 generatedColumn += prefixOffset;
77 }
78 } else if (!linesOnly) {
79 // Without source content, we only need to adject the column info
80 // expect in lines only mode where prefix is added to original mapping
81 generatedColumn += prefixOffset;
82 }
83 onChunk(
84 chunk,
85 generatedLine,
86 generatedColumn,
87 sourceIndex,
88 originalLine,
89 originalColumn,
90 nameIndex
91 );
92 },
93 onSource,
94 onName
95 );
96 return {
97 generatedLine,
98 generatedColumn:
99 generatedColumn === 0 ? 0 : prefixOffset + generatedColumn,
100 source:
101 source !== undefined
102 ? prefix + source.replace(REPLACE_REGEX, "\n" + prefix)
103 : undefined
104 };
105 }
106
107 updateHash(hash) {
108 hash.update("PrefixSource");
109 this._source.updateHash(hash);
110 hash.update(this._prefix);
111 }
112}
113
114module.exports = PrefixSource;