node.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. 'use strict'
  2. let CssSyntaxError = require('./css-syntax-error')
  3. let Stringifier = require('./stringifier')
  4. let stringify = require('./stringify')
  5. let { isClean, my } = require('./symbols')
  6. function cloneNode(obj, parent) {
  7. let cloned = new obj.constructor()
  8. // An explicit stack instead of recursive calls to survive deeply
  9. // nested trees. Each entry is [source, its clone, clone's parent].
  10. let stack = [[obj, cloned, parent]]
  11. while (stack.length > 0) {
  12. let [source, target, targetParent] = stack.pop()
  13. for (let i in source) {
  14. if (!Object.prototype.hasOwnProperty.call(source, i)) {
  15. /* c8 ignore next 2 */
  16. continue
  17. }
  18. if (i === 'proxyCache') continue
  19. let value = source[i]
  20. let type = typeof value
  21. if (i === 'parent' && type === 'object') {
  22. if (targetParent) target[i] = targetParent
  23. } else if (i === 'source') {
  24. target[i] = value
  25. } else if (Array.isArray(value)) {
  26. let children = []
  27. target[i] = children
  28. for (let j of value) {
  29. let childClone = new j.constructor()
  30. children.push(childClone)
  31. stack.push([j, childClone, target])
  32. }
  33. } else {
  34. if (type === 'object' && value !== null) {
  35. let valueClone = new value.constructor()
  36. stack.push([value, valueClone, undefined])
  37. value = valueClone
  38. }
  39. target[i] = value
  40. }
  41. }
  42. }
  43. return cloned
  44. }
  45. function sourceOffset(inputCSS, position) {
  46. // Not all custom syntaxes support `offset` in `source.start` and `source.end`
  47. if (position && typeof position.offset !== 'undefined') {
  48. return position.offset
  49. }
  50. let column = 1
  51. let line = 1
  52. let offset = 0
  53. for (let i = 0; i < inputCSS.length; i++) {
  54. if (line === position.line && column === position.column) {
  55. offset = i
  56. break
  57. }
  58. if (inputCSS[i] === '\n') {
  59. column = 1
  60. line += 1
  61. } else {
  62. column += 1
  63. }
  64. }
  65. return offset
  66. }
  67. class Node {
  68. get proxyOf() {
  69. return this
  70. }
  71. constructor(defaults = {}) {
  72. this.raws = {}
  73. this[isClean] = false
  74. this[my] = true
  75. for (let name of Object.keys(defaults)) {
  76. if (name === '__proto__') continue
  77. if (name === 'nodes') {
  78. this.nodes = []
  79. for (let node of defaults[name]) {
  80. // Clone only nodes that already belong to another tree, so passing a
  81. // freshly created (parent-less) node adopts that instance instead of
  82. // a copy and keeps the caller's reference usable. See #1987.
  83. if (typeof node.clone === 'function' && node.parent) {
  84. this.append(node.clone())
  85. } else {
  86. this.append(node)
  87. }
  88. }
  89. } else {
  90. this[name] = defaults[name]
  91. }
  92. }
  93. }
  94. addToError(error) {
  95. error.postcssNode = this
  96. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  97. let s = this.source
  98. error.stack = error.stack.replace(
  99. /\n\s{4}at /,
  100. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  101. )
  102. }
  103. return error
  104. }
  105. after(add) {
  106. this.parent.insertAfter(this, add)
  107. return this
  108. }
  109. assign(overrides = {}) {
  110. for (let name in overrides) {
  111. this[name] = overrides[name]
  112. }
  113. return this
  114. }
  115. before(add) {
  116. this.parent.insertBefore(this, add)
  117. return this
  118. }
  119. cleanRaws(keepBetween) {
  120. delete this.raws.before
  121. delete this.raws.after
  122. if (!keepBetween) delete this.raws.between
  123. }
  124. clone(overrides = {}) {
  125. let cloned = cloneNode(this)
  126. for (let name in overrides) {
  127. cloned[name] = overrides[name]
  128. }
  129. return cloned
  130. }
  131. cloneAfter(overrides = {}) {
  132. let cloned = this.clone(overrides)
  133. this.parent.insertAfter(this, cloned)
  134. return cloned
  135. }
  136. cloneBefore(overrides = {}) {
  137. let cloned = this.clone(overrides)
  138. this.parent.insertBefore(this, cloned)
  139. return cloned
  140. }
  141. error(message, opts = {}) {
  142. if (this.source) {
  143. let { end, start } = this.rangeBy(opts)
  144. return this.source.input.error(
  145. message,
  146. { column: start.column, line: start.line },
  147. { column: end.column, line: end.line },
  148. opts
  149. )
  150. }
  151. return new CssSyntaxError(message)
  152. }
  153. getProxyProcessor() {
  154. return {
  155. get(node, prop) {
  156. if (prop === 'proxyOf') {
  157. return node
  158. } else if (prop === 'root') {
  159. return () => node.root().toProxy()
  160. } else {
  161. return node[prop]
  162. }
  163. },
  164. set(node, prop, value) {
  165. if (node[prop] === value) return true
  166. node[prop] = value
  167. if (
  168. prop === 'prop' ||
  169. prop === 'value' ||
  170. prop === 'name' ||
  171. prop === 'params' ||
  172. prop === 'important' ||
  173. /* c8 ignore next */
  174. prop === 'text'
  175. ) {
  176. node.markDirty()
  177. }
  178. return true
  179. }
  180. }
  181. }
  182. /* c8 ignore next 3 */
  183. markClean() {
  184. this[isClean] = true
  185. }
  186. markDirty() {
  187. if (this[isClean]) {
  188. this[isClean] = false
  189. let next = this
  190. while ((next = next.parent)) {
  191. next[isClean] = false
  192. }
  193. }
  194. }
  195. next() {
  196. if (!this.parent) return undefined
  197. let index = this.parent.index(this)
  198. return this.parent.nodes[index + 1]
  199. }
  200. positionBy(opts = {}) {
  201. let inputString =
  202. 'document' in this.source.input
  203. ? this.source.input.document
  204. : this.source.input.css
  205. let pos = {
  206. column: this.source.start.column,
  207. line: this.source.start.line,
  208. offset: sourceOffset(inputString, this.source.start)
  209. }
  210. if (opts.index) {
  211. pos = this.positionInside(opts.index)
  212. } else if (opts.word) {
  213. let stringRepresentation = inputString.slice(
  214. sourceOffset(inputString, this.source.start),
  215. sourceOffset(inputString, this.source.end)
  216. )
  217. let index = stringRepresentation.indexOf(opts.word)
  218. if (index !== -1) pos = this.positionInside(index)
  219. }
  220. return pos
  221. }
  222. positionInside(index) {
  223. let column = this.source.start.column
  224. let line = this.source.start.line
  225. let inputString =
  226. 'document' in this.source.input
  227. ? this.source.input.document
  228. : this.source.input.css
  229. let offset = sourceOffset(inputString, this.source.start)
  230. let end = offset + index
  231. for (let i = offset; i < end; i++) {
  232. if (inputString[i] === '\n') {
  233. column = 1
  234. line += 1
  235. } else {
  236. column += 1
  237. }
  238. }
  239. return { column, line, offset: end }
  240. }
  241. prev() {
  242. if (!this.parent) return undefined
  243. let index = this.parent.index(this)
  244. return this.parent.nodes[index - 1]
  245. }
  246. rangeBy(opts = {}) {
  247. let inputString =
  248. 'document' in this.source.input
  249. ? this.source.input.document
  250. : this.source.input.css
  251. let start = {
  252. column: this.source.start.column,
  253. line: this.source.start.line,
  254. offset: sourceOffset(inputString, this.source.start)
  255. }
  256. let end = this.source.end
  257. ? {
  258. column: this.source.end.column + 1,
  259. line: this.source.end.line,
  260. offset:
  261. typeof this.source.end.offset === 'number'
  262. ? // `source.end.offset` is exclusive, so we don't need to add 1
  263. this.source.end.offset
  264. : // Since line/column in this.source.end is inclusive,
  265. // the `sourceOffset(... , this.source.end)` returns an inclusive offset.
  266. // So, we add 1 to convert it to exclusive.
  267. sourceOffset(inputString, this.source.end) + 1
  268. }
  269. : {
  270. column: start.column + 1,
  271. line: start.line,
  272. offset: start.offset + 1
  273. }
  274. if (opts.word) {
  275. let stringRepresentation = inputString.slice(
  276. sourceOffset(inputString, this.source.start),
  277. sourceOffset(inputString, this.source.end)
  278. )
  279. let index = stringRepresentation.indexOf(opts.word)
  280. if (index !== -1) {
  281. start = this.positionInside(index)
  282. end = this.positionInside(index + opts.word.length)
  283. }
  284. } else {
  285. if (opts.start) {
  286. start = {
  287. column: opts.start.column,
  288. line: opts.start.line,
  289. offset: sourceOffset(inputString, opts.start)
  290. }
  291. } else if (typeof opts.index === 'number') {
  292. start = this.positionInside(opts.index)
  293. }
  294. if (opts.end) {
  295. end = {
  296. column: opts.end.column,
  297. line: opts.end.line,
  298. offset: sourceOffset(inputString, opts.end)
  299. }
  300. } else if (typeof opts.endIndex === 'number') {
  301. end = this.positionInside(opts.endIndex)
  302. } else if (typeof opts.index === 'number') {
  303. end = this.positionInside(opts.index + 1)
  304. }
  305. }
  306. if (
  307. end.line < start.line ||
  308. (end.line === start.line && end.column <= start.column)
  309. ) {
  310. end = {
  311. column: start.column + 1,
  312. line: start.line,
  313. offset: start.offset + 1
  314. }
  315. }
  316. return { end, start }
  317. }
  318. raw(prop, defaultType) {
  319. let str = new Stringifier()
  320. return str.raw(this, prop, defaultType)
  321. }
  322. remove() {
  323. if (this.parent) {
  324. this.parent.removeChild(this)
  325. }
  326. this.parent = undefined
  327. return this
  328. }
  329. replaceWith(...nodes) {
  330. if (this.parent) {
  331. let bookmark = this
  332. let foundSelf = false
  333. for (let node of nodes) {
  334. if (node === this) {
  335. foundSelf = true
  336. } else if (foundSelf) {
  337. this.parent.insertAfter(bookmark, node)
  338. bookmark = node
  339. } else {
  340. this.parent.insertBefore(bookmark, node)
  341. }
  342. }
  343. if (!foundSelf) {
  344. this.remove()
  345. }
  346. }
  347. return this
  348. }
  349. root() {
  350. let result = this
  351. while (result.parent && result.parent.type !== 'document') {
  352. result = result.parent
  353. }
  354. return result
  355. }
  356. toJSON(_, inputs) {
  357. let emitInputs = inputs == null
  358. inputs = inputs || new Map()
  359. // A worklist instead of recursive `toJSON()` calls to survive deeply
  360. // nested trees. Each entry converts one node and writes the result
  361. // into the already converted parent by [holder, key].
  362. let holderOfRoot = []
  363. let queue = [[this, holderOfRoot, 0]]
  364. for (let step = 0; step < queue.length; step++) {
  365. let [node, holder, key] = queue[step]
  366. let fixed = {}
  367. holder[key] = fixed
  368. for (let name in node) {
  369. if (!Object.prototype.hasOwnProperty.call(node, name)) {
  370. /* c8 ignore next 2 */
  371. continue
  372. }
  373. if (name === 'parent' || name === 'proxyCache') continue
  374. let value = node[name]
  375. if (Array.isArray(value)) {
  376. let fixedArray = []
  377. fixed[name] = fixedArray
  378. for (let i = 0; i < value.length; i++) {
  379. let item = value[i]
  380. if (typeof item === 'object' && item.toJSON) {
  381. if (item.toJSON === Node.prototype.toJSON) {
  382. queue.push([item, fixedArray, i])
  383. } else {
  384. fixedArray[i] = item.toJSON(null, inputs)
  385. }
  386. } else {
  387. fixedArray[i] = item
  388. }
  389. }
  390. } else if (typeof value === 'object' && value.toJSON) {
  391. if (value.toJSON === Node.prototype.toJSON) {
  392. queue.push([value, fixed, name])
  393. } else {
  394. fixed[name] = value.toJSON(null, inputs)
  395. }
  396. } else if (name === 'source') {
  397. if (value == null) continue
  398. let inputId = inputs.get(value.input)
  399. if (inputId == null) {
  400. inputId = inputs.size
  401. inputs.set(value.input, inputId)
  402. }
  403. fixed[name] = {
  404. end: value.end,
  405. inputId,
  406. start: value.start
  407. }
  408. } else {
  409. fixed[name] = value
  410. }
  411. }
  412. }
  413. let fixed = holderOfRoot[0]
  414. if (emitInputs) {
  415. fixed.inputs = [...inputs.keys()].map(input => input.toJSON())
  416. }
  417. return fixed
  418. }
  419. toProxy() {
  420. if (!this.proxyCache) {
  421. this.proxyCache = new Proxy(this, this.getProxyProcessor())
  422. }
  423. return this.proxyCache
  424. }
  425. toString(stringifier = stringify) {
  426. if (stringifier.stringify) stringifier = stringifier.stringify
  427. let result = ''
  428. stringifier(this, i => {
  429. result += i
  430. })
  431. return result
  432. }
  433. warn(result, text, opts = {}) {
  434. let data = { node: this }
  435. for (let i in opts) data[i] = opts[i]
  436. return result.warn(text, data)
  437. }
  438. }
  439. module.exports = Node
  440. Node.default = Node