source: trip-planner-front/node_modules/postcss-custom-properties/index.cjs.js@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 18.2 KB
Line 
1'use strict';
2
3function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
5var postcss = _interopDefault(require('postcss'));
6var valueParser = _interopDefault(require('postcss-values-parser'));
7var fs = _interopDefault(require('fs'));
8var path = _interopDefault(require('path'));
9
10function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11 try {
12 var info = gen[key](arg);
13 var value = info.value;
14 } catch (error) {
15 reject(error);
16 return;
17 }
18
19 if (info.done) {
20 resolve(value);
21 } else {
22 Promise.resolve(value).then(_next, _throw);
23 }
24}
25
26function _asyncToGenerator(fn) {
27 return function () {
28 var self = this,
29 args = arguments;
30 return new Promise(function (resolve, reject) {
31 var gen = fn.apply(self, args);
32
33 function _next(value) {
34 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
35 }
36
37 function _throw(err) {
38 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
39 }
40
41 _next(undefined);
42 });
43 };
44}
45
46function parse(string) {
47 return valueParser(string).parse();
48}
49
50function isBlockIgnored(ruleOrDeclaration) {
51 var rule = ruleOrDeclaration.selector ? ruleOrDeclaration : ruleOrDeclaration.parent;
52 return /(!\s*)?postcss-custom-properties:\s*off\b/i.test(rule.toString());
53}
54
55function isRuleIgnored(rule) {
56 var previous = rule.prev();
57 return Boolean(isBlockIgnored(rule) || previous && previous.type === 'comment' && /(!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i.test(previous.text));
58}
59
60function getCustomPropertiesFromRoot(root, opts) {
61 // initialize custom selectors
62 const customPropertiesFromHtmlElement = {};
63 const customPropertiesFromRootPseudo = {}; // for each html or :root rule
64
65 root.nodes.slice().forEach(rule => {
66 const customPropertiesObject = isHtmlRule(rule) ? customPropertiesFromHtmlElement : isRootRule(rule) ? customPropertiesFromRootPseudo : null; // for each custom property
67
68 if (customPropertiesObject) {
69 rule.nodes.slice().forEach(decl => {
70 if (isCustomDecl(decl) && !isBlockIgnored(decl)) {
71 const prop = decl.prop; // write the parsed value to the custom property
72
73 customPropertiesObject[prop] = parse(decl.value).nodes; // conditionally remove the custom property declaration
74
75 if (!opts.preserve) {
76 decl.remove();
77 }
78 }
79 }); // conditionally remove the empty html or :root rule
80
81 if (!opts.preserve && isEmptyParent(rule) && !isBlockIgnored(rule)) {
82 rule.remove();
83 }
84 }
85 }); // return all custom properties, preferring :root properties over html properties
86
87 return Object.assign({}, customPropertiesFromHtmlElement, customPropertiesFromRootPseudo);
88} // match html and :root rules
89
90const htmlSelectorRegExp = /^html$/i;
91const rootSelectorRegExp = /^:root$/i;
92const customPropertyRegExp = /^--[A-z][\w-]*$/; // whether the node is an html or :root rule
93
94const isHtmlRule = node => node.type === 'rule' && htmlSelectorRegExp.test(node.selector) && Object(node.nodes).length;
95
96const isRootRule = node => node.type === 'rule' && rootSelectorRegExp.test(node.selector) && Object(node.nodes).length; // whether the node is an custom property
97
98
99const isCustomDecl = node => node.type === 'decl' && customPropertyRegExp.test(node.prop); // whether the node is a parent without children
100
101
102const isEmptyParent = node => Object(node.nodes).length === 0;
103
104/* Get Custom Properties from CSS File
105/* ========================================================================== */
106
107function getCustomPropertiesFromCSSFile(_x) {
108 return _getCustomPropertiesFromCSSFile.apply(this, arguments);
109}
110/* Get Custom Properties from Object
111/* ========================================================================== */
112
113
114function _getCustomPropertiesFromCSSFile() {
115 _getCustomPropertiesFromCSSFile = _asyncToGenerator(function* (from) {
116 const css = yield readFile(from);
117 const root = postcss.parse(css, {
118 from
119 });
120 return getCustomPropertiesFromRoot(root, {
121 preserve: true
122 });
123 });
124 return _getCustomPropertiesFromCSSFile.apply(this, arguments);
125}
126
127function getCustomPropertiesFromObject(object) {
128 const customProperties = Object.assign({}, Object(object).customProperties, Object(object)['custom-properties']);
129
130 for (const key in customProperties) {
131 customProperties[key] = parse(String(customProperties[key])).nodes;
132 }
133
134 return customProperties;
135}
136/* Get Custom Properties from JSON file
137/* ========================================================================== */
138
139
140function getCustomPropertiesFromJSONFile(_x2) {
141 return _getCustomPropertiesFromJSONFile.apply(this, arguments);
142}
143/* Get Custom Properties from JS file
144/* ========================================================================== */
145
146
147function _getCustomPropertiesFromJSONFile() {
148 _getCustomPropertiesFromJSONFile = _asyncToGenerator(function* (from) {
149 const object = yield readJSON(from);
150 return getCustomPropertiesFromObject(object);
151 });
152 return _getCustomPropertiesFromJSONFile.apply(this, arguments);
153}
154
155function getCustomPropertiesFromJSFile(_x3) {
156 return _getCustomPropertiesFromJSFile.apply(this, arguments);
157}
158/* Get Custom Properties from Imports
159/* ========================================================================== */
160
161
162function _getCustomPropertiesFromJSFile() {
163 _getCustomPropertiesFromJSFile = _asyncToGenerator(function* (from) {
164 const object = yield Promise.resolve(require(from));
165 return getCustomPropertiesFromObject(object);
166 });
167 return _getCustomPropertiesFromJSFile.apply(this, arguments);
168}
169
170function getCustomPropertiesFromImports(sources) {
171 return sources.map(source => {
172 if (source instanceof Promise) {
173 return source;
174 } else if (source instanceof Function) {
175 return source();
176 } // read the source as an object
177
178
179 const opts = source === Object(source) ? source : {
180 from: String(source)
181 }; // skip objects with Custom Properties
182
183 if (opts.customProperties || opts['custom-properties']) {
184 return opts;
185 } // source pathname
186
187
188 const from = path.resolve(String(opts.from || '')); // type of file being read from
189
190 const type = (opts.type || path.extname(from).slice(1)).toLowerCase();
191 return {
192 type,
193 from
194 };
195 }).reduce(
196 /*#__PURE__*/
197 function () {
198 var _ref = _asyncToGenerator(function* (customProperties, source) {
199 const _ref2 = yield source,
200 type = _ref2.type,
201 from = _ref2.from;
202
203 if (type === 'css') {
204 return Object.assign((yield customProperties), (yield getCustomPropertiesFromCSSFile(from)));
205 }
206
207 if (type === 'js') {
208 return Object.assign((yield customProperties), (yield getCustomPropertiesFromJSFile(from)));
209 }
210
211 if (type === 'json') {
212 return Object.assign((yield customProperties), (yield getCustomPropertiesFromJSONFile(from)));
213 }
214
215 return Object.assign((yield customProperties), (yield getCustomPropertiesFromObject((yield source))));
216 });
217
218 return function (_x4, _x5) {
219 return _ref.apply(this, arguments);
220 };
221 }(), {});
222}
223/* Helper utilities
224/* ========================================================================== */
225
226const readFile = from => new Promise((resolve, reject) => {
227 fs.readFile(from, 'utf8', (error, result) => {
228 if (error) {
229 reject(error);
230 } else {
231 resolve(result);
232 }
233 });
234});
235
236const readJSON =
237/*#__PURE__*/
238function () {
239 var _ref3 = _asyncToGenerator(function* (from) {
240 return JSON.parse((yield readFile(from)));
241 });
242
243 return function readJSON(_x6) {
244 return _ref3.apply(this, arguments);
245 };
246}();
247
248function transformValueAST(root, customProperties) {
249 if (root.nodes && root.nodes.length) {
250 root.nodes.slice().forEach(child => {
251 if (isVarFunction(child)) {
252 // eslint-disable-next-line no-unused-vars
253 const _child$nodes$slice = child.nodes.slice(1, -1),
254 propertyNode = _child$nodes$slice[0],
255 comma = _child$nodes$slice[1],
256 fallbacks = _child$nodes$slice.slice(2);
257
258 const name = propertyNode.value;
259
260 if (name in Object(customProperties)) {
261 // conditionally replace a known custom property
262 const nodes = asClonedArrayWithBeforeSpacing(customProperties[name], child.raws.before);
263 child.replaceWith(...nodes);
264 retransformValueAST({
265 nodes
266 }, customProperties, name);
267 } else if (fallbacks.length) {
268 // conditionally replace a custom property with a fallback
269 const index = root.nodes.indexOf(child);
270
271 if (index !== -1) {
272 root.nodes.splice(index, 1, ...asClonedArrayWithBeforeSpacing(fallbacks, child.raws.before));
273 }
274
275 transformValueAST(root, customProperties);
276 }
277 } else {
278 transformValueAST(child, customProperties);
279 }
280 });
281 }
282
283 return root;
284} // retransform the current ast without a custom property (to prevent recursion)
285
286function retransformValueAST(root, customProperties, withoutProperty) {
287 const nextCustomProperties = Object.assign({}, customProperties);
288 delete nextCustomProperties[withoutProperty];
289 return transformValueAST(root, nextCustomProperties);
290} // match var() functions
291
292
293const varRegExp = /^var$/i; // whether the node is a var() function
294
295const isVarFunction = node => node.type === 'func' && varRegExp.test(node.value) && Object(node.nodes).length > 0; // return an array with its nodes cloned, preserving the raw
296
297
298const asClonedArrayWithBeforeSpacing = (array, beforeSpacing) => {
299 const clonedArray = asClonedArray(array, null);
300
301 if (clonedArray[0]) {
302 clonedArray[0].raws.before = beforeSpacing;
303 }
304
305 return clonedArray;
306}; // return an array with its nodes cloned
307
308
309const asClonedArray = (array, parent) => array.map(node => asClonedNode(node, parent)); // return a cloned node
310
311
312const asClonedNode = (node, parent) => {
313 const cloneNode = new node.constructor(node);
314
315 for (const key in node) {
316 if (key === 'parent') {
317 cloneNode.parent = parent;
318 } else if (Object(node[key]).constructor === Array) {
319 cloneNode[key] = asClonedArray(node.nodes, cloneNode);
320 } else if (Object(node[key]).constructor === Object) {
321 cloneNode[key] = Object.assign({}, node[key]);
322 }
323 }
324
325 return cloneNode;
326};
327
328var transformProperties = ((root, customProperties, opts) => {
329 // walk decls that can be transformed
330 root.walkDecls(decl => {
331 if (isTransformableDecl(decl) && !isRuleIgnored(decl)) {
332 const originalValue = decl.value;
333 const valueAST = parse(originalValue);
334 const value = String(transformValueAST(valueAST, customProperties)); // conditionally transform values that have changed
335
336 if (value !== originalValue) {
337 if (opts.preserve) {
338 decl.cloneBefore({
339 value
340 });
341 } else {
342 decl.value = value;
343 }
344 }
345 }
346 });
347}); // match custom properties
348
349const customPropertyRegExp$1 = /^--[A-z][\w-]*$/; // match custom property inclusions
350
351const customPropertiesRegExp = /(^|[^\w-])var\([\W\w]+\)/; // whether the declaration should be potentially transformed
352
353const isTransformableDecl = decl => !customPropertyRegExp$1.test(decl.prop) && customPropertiesRegExp.test(decl.value);
354
355/* Write Custom Properties to CSS File
356/* ========================================================================== */
357
358function writeCustomPropertiesToCssFile(_x, _x2) {
359 return _writeCustomPropertiesToCssFile.apply(this, arguments);
360}
361/* Write Custom Properties to JSON file
362/* ========================================================================== */
363
364
365function _writeCustomPropertiesToCssFile() {
366 _writeCustomPropertiesToCssFile = _asyncToGenerator(function* (to, customProperties) {
367 const cssContent = Object.keys(customProperties).reduce((cssLines, name) => {
368 cssLines.push(`\t${name}: ${customProperties[name]};`);
369 return cssLines;
370 }, []).join('\n');
371 const css = `:root {\n${cssContent}\n}\n`;
372 yield writeFile(to, css);
373 });
374 return _writeCustomPropertiesToCssFile.apply(this, arguments);
375}
376
377function writeCustomPropertiesToJsonFile(_x3, _x4) {
378 return _writeCustomPropertiesToJsonFile.apply(this, arguments);
379}
380/* Write Custom Properties to Common JS file
381/* ========================================================================== */
382
383
384function _writeCustomPropertiesToJsonFile() {
385 _writeCustomPropertiesToJsonFile = _asyncToGenerator(function* (to, customProperties) {
386 const jsonContent = JSON.stringify({
387 'custom-properties': customProperties
388 }, null, ' ');
389 const json = `${jsonContent}\n`;
390 yield writeFile(to, json);
391 });
392 return _writeCustomPropertiesToJsonFile.apply(this, arguments);
393}
394
395function writeCustomPropertiesToCjsFile(_x5, _x6) {
396 return _writeCustomPropertiesToCjsFile.apply(this, arguments);
397}
398/* Write Custom Properties to Module JS file
399/* ========================================================================== */
400
401
402function _writeCustomPropertiesToCjsFile() {
403 _writeCustomPropertiesToCjsFile = _asyncToGenerator(function* (to, customProperties) {
404 const jsContents = Object.keys(customProperties).reduce((jsLines, name) => {
405 jsLines.push(`\t\t'${escapeForJS(name)}': '${escapeForJS(customProperties[name])}'`);
406 return jsLines;
407 }, []).join(',\n');
408 const js = `module.exports = {\n\tcustomProperties: {\n${jsContents}\n\t}\n};\n`;
409 yield writeFile(to, js);
410 });
411 return _writeCustomPropertiesToCjsFile.apply(this, arguments);
412}
413
414function writeCustomPropertiesToMjsFile(_x7, _x8) {
415 return _writeCustomPropertiesToMjsFile.apply(this, arguments);
416}
417/* Write Custom Properties to Exports
418/* ========================================================================== */
419
420
421function _writeCustomPropertiesToMjsFile() {
422 _writeCustomPropertiesToMjsFile = _asyncToGenerator(function* (to, customProperties) {
423 const mjsContents = Object.keys(customProperties).reduce((mjsLines, name) => {
424 mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(customProperties[name])}'`);
425 return mjsLines;
426 }, []).join(',\n');
427 const mjs = `export const customProperties = {\n${mjsContents}\n};\n`;
428 yield writeFile(to, mjs);
429 });
430 return _writeCustomPropertiesToMjsFile.apply(this, arguments);
431}
432
433function writeCustomPropertiesToExports(customProperties, destinations) {
434 return Promise.all(destinations.map(
435 /*#__PURE__*/
436 function () {
437 var _ref = _asyncToGenerator(function* (destination) {
438 if (destination instanceof Function) {
439 yield destination(defaultCustomPropertiesToJSON(customProperties));
440 } else {
441 // read the destination as an object
442 const opts = destination === Object(destination) ? destination : {
443 to: String(destination)
444 }; // transformer for Custom Properties into a JSON-compatible object
445
446 const toJSON = opts.toJSON || defaultCustomPropertiesToJSON;
447
448 if ('customProperties' in opts) {
449 // write directly to an object as customProperties
450 opts.customProperties = toJSON(customProperties);
451 } else if ('custom-properties' in opts) {
452 // write directly to an object as custom-properties
453 opts['custom-properties'] = toJSON(customProperties);
454 } else {
455 // destination pathname
456 const to = String(opts.to || ''); // type of file being written to
457
458 const type = (opts.type || path.extname(opts.to).slice(1)).toLowerCase(); // transformed Custom Properties
459
460 const customPropertiesJSON = toJSON(customProperties);
461
462 if (type === 'css') {
463 yield writeCustomPropertiesToCssFile(to, customPropertiesJSON);
464 }
465
466 if (type === 'js') {
467 yield writeCustomPropertiesToCjsFile(to, customPropertiesJSON);
468 }
469
470 if (type === 'json') {
471 yield writeCustomPropertiesToJsonFile(to, customPropertiesJSON);
472 }
473
474 if (type === 'mjs') {
475 yield writeCustomPropertiesToMjsFile(to, customPropertiesJSON);
476 }
477 }
478 }
479 });
480
481 return function (_x9) {
482 return _ref.apply(this, arguments);
483 };
484 }()));
485}
486/* Helper utilities
487/* ========================================================================== */
488
489const defaultCustomPropertiesToJSON = customProperties => {
490 return Object.keys(customProperties).reduce((customPropertiesJSON, key) => {
491 customPropertiesJSON[key] = String(customProperties[key]);
492 return customPropertiesJSON;
493 }, {});
494};
495
496const writeFile = (to, text) => new Promise((resolve, reject) => {
497 fs.writeFile(to, text, error => {
498 if (error) {
499 reject(error);
500 } else {
501 resolve();
502 }
503 });
504});
505
506const escapeForJS = string => string.replace(/\\([\s\S])|(')/g, '\\$1$2').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
507
508var index = postcss.plugin('postcss-custom-properties', opts => {
509 // whether to preserve custom selectors and rules using them
510 const preserve = 'preserve' in Object(opts) ? Boolean(opts.preserve) : true; // sources to import custom selectors from
511
512 const importFrom = [].concat(Object(opts).importFrom || []); // destinations to export custom selectors to
513
514 const exportTo = [].concat(Object(opts).exportTo || []); // promise any custom selectors are imported
515
516 const customPropertiesPromise = getCustomPropertiesFromImports(importFrom); // synchronous transform
517
518 const syncTransform = root => {
519 const customProperties = getCustomPropertiesFromRoot(root, {
520 preserve
521 });
522 transformProperties(root, customProperties, {
523 preserve
524 });
525 }; // asynchronous transform
526
527
528 const asyncTransform =
529 /*#__PURE__*/
530 function () {
531 var _ref = _asyncToGenerator(function* (root) {
532 const customProperties = Object.assign({}, (yield customPropertiesPromise), getCustomPropertiesFromRoot(root, {
533 preserve
534 }));
535 yield writeCustomPropertiesToExports(customProperties, exportTo);
536 transformProperties(root, customProperties, {
537 preserve
538 });
539 });
540
541 return function asyncTransform(_x) {
542 return _ref.apply(this, arguments);
543 };
544 }(); // whether to return synchronous function if no asynchronous operations are requested
545
546
547 const canReturnSyncFunction = importFrom.length === 0 && exportTo.length === 0;
548 return canReturnSyncFunction ? syncTransform : asyncTransform;
549});
550
551module.exports = index;
552//# sourceMappingURL=index.cjs.js.map
Note: See TracBrowser for help on using the repository browser.