all files / dist/ j2c.commonjs.js

99.62% Statements 259/260
99.43% Branches 175/176
97.67% Functions 42/43
100% Lines 215/215
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        2999× 2723×   384×     24× 51× 59× 32× 24×                                   30×   30×   27× 18×     30× 16× 16×   30× 30×             15×   11× 11×   12×       56× 111× 70×       186× 172× 172× 172×     46×                             298× 298×   282×   19×   34×   19×         137× 74× 74× 22×   15×         67×       68×           195×           190×   190×     14×   16×         190×                                                           106×   14×               98×   29×     69×       68×   14×   10×     11×                 54× 11×   12×         43×             40×   35×             35×           34×   34×               35×                                     359×   359×     669× 387×   387× 130× 127×   127×     130×           128×       257×   106×   106×             151×   151×     149×                               24× 31×                                                                   336×       12×             13×   13×                           340× 340× 134×   134× 134×     58× 58×     39× 39×     136× 133× 133× 133×               178× 178× 178×               178×     173× 31× 31×   173×                                             65×       173×             134× 44×   173× 173×     171×   171×     171× 164×   166× 153×     15× 15×   15×   51×     33× 119×   119× 172×       171× 171× 171× 171× 171×           171× 33× 43×   42× 42× 42× 42×     170× 170×   170×                 170× 340× 378×               170×      
'use strict';
 
var emptyObject = {};
var type = emptyObject.toString;
var ARRAY =  type.call([]);
var NUMBER = type.call(0);
var OBJECT = type.call(emptyObject);
var STRING = type.call('');
var FUNCTION = type.call(type);
var own =  emptyObject.hasOwnProperty;
var freeze = Object.freeze || function(o) {return o};
 
 
function defaults(target, source) {
  for (var k in source) if (own.call(source, k)) {
    if (k.indexOf('$') && !(k in target)) target[k] = source[k];
  }
  return target
}
 
function cartesian(a,b) {
  var res = [], i, j;
  for (j in b) if(own.call(b, j))
    for (i in a) if(own.call(a, i))
      res.push(a[i] + b[j]);
  return res
}
 
// "Tokenizes" the selectors into parts relevant for the next function.
// Strings and comments are matched, but ignored afterwards.
// This is not a full tokenizers. It only recognizes comas, parentheses,
// strings and comments.
// regexp generated by scripts/regexps.js then trimmed by hand
var selectorTokenizer = /[(),]|"(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'|\/\*[\s\S]*?\*\//g;
 
 
/**
 * This will split a coma-separated selector list into individual selectors,
 * ignoring comas in strings, comments and in :pseudo-selectors(parameter, lists).
 *
 * @param {string} selector
 * @return {string[]}
 */
 
function splitSelector(selector) {
  var indices = [], res = [], inParen = 0, o;
  /*eslint-disable no-cond-assign*/
  while (o = selectorTokenizer.exec(selector)) {
  /*eslint-enable no-cond-assign*/
    switch (o[0]) {
    case '(': inParen++; break
    case ')': inParen--; break
    case ',': if (inParen) break; indices.push(o.index);
    }
  }
  for (o = indices.length; o--;){
    res.unshift(selector.slice(indices[o] + 1));
    selector = selector.slice(0, indices[o]);
  }
  res.unshift(selector);
  return res
}
 
// Like the `selectorTokenizer`, but for the `&` operator
var ampersandTokenizer = /&|"(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'|\/\*[\s\S]*?\*\//g;
 
function ampersand (selector, parents) {
  var indices = [], split = [], res, o;
  /*eslint-disable no-cond-assign*/
  while (o = ampersandTokenizer.exec(selector)) {
  /*eslint-enable no-cond-assign*/
    if (o[0] == '&') indices.push(o.index);
  }
  for (o = indices.length; o--;){
    split.unshift(selector.slice(indices[o] + 1));
    selector = selector.slice(0, indices[o]);
  }
  split.unshift(selector);
  if (split.length === 1) split.unshift('');
  res = [split[0]];
  for (o = 1; o < split.length; o++) {
    res = cartesian(res, cartesian(parents, [split[o]]));
  }
  return res.join(',')
}
 
function flatIter (f) {
  return function iter(arg) {
    if (type.call(arg) === ARRAY) for (var i= 0 ; i < arg.length; i ++) iter(arg[i]);
    else f(arg);
  }
}
 
var chars = '';
function randChars(n) {
  while(chars.length < n) chars += Math.floor(Math.random() * 0x100000000).toString(36);
  var res = '_' + chars.slice(0, n);
  chars = chars.slice(n);
  return res
}
 
function decamelize(match) {
  return '-' + match.toLowerCase()
}
 
/**
 * Handles the property:value; pairs.
 *
 * @param {object} state - holds the localizer- and walker-related methods
 *                         and state
 * @param {object} emit - the contextual emitters to the final buffer
 * @param {string} prefix - the current property or a prefix in case of nested
 *                          sub-properties.
 * @param {array|object|string} o - the declarations.
 * @param {boolean} local - are we in @local or in @global scope.
 */
 
function declarations(state, emit, prefix, o, local) {
  var k, v, kk;
  if (o==null) return
 
  switch ( type.call(o = o.valueOf()) ) {
  case ARRAY:
    for (k = 0; k < o.length; k++)
 
      declarations(state, emit, prefix, o[k], local);
 
    break
  case OBJECT:
    // prefix is falsy iif it is the empty string, which means we're at the root
    // of the declarations list.
 
    for (k in o) if (own.call(o, k)){
      v = o[k];
      if (/\$/.test(k)) {
        for (kk in (k = k.split('$'))) if (own.call(k, kk)) {
 
          declarations(state, emit, prefix + k[kk], v, local);
 
        }
      } else {
 
        declarations(state, emit, prefix + k, v, local);
 
      }
    }
    break
  default:
    // prefix is falsy when it is "", which means that we're
    // at the top level.
    // `o` is then treated as a `property:value` pair, or a
    // semi-colon-separated list thereof.
    if (!prefix) return emit.raw(o)
 
    // Otherwise, `prefix` is the property name, and
    // `o` is the value.
 
    // restore the dashes
    k = prefix.replace(/[A-Z]/g, decamelize);
 
    if (local && (k == 'animation-name' || k == 'animation')) {
      // no need to tokenize here a plain `.split(',')` has all bases covered.
      // We may 'localize' a comment, but it's not a big deal.
      o = o.split(',').map(function (o) {
 
        return o.replace(/^\s*(?:(var\([^)]+\))|:?global\(\s*([_A-Za-z][-\w]*)\s*\)|()(-?[_A-Za-z][-\w]*))/, state.localizeReplacer)
 
      }).join(',');
    }
 
    emit.decl(k, o);
  }
}
 
/**
 * Handles a single at-rules
 *
 * @param {object} state - holds the localizer- and walker-related methods
 *                         and state
 * @param {object} emit - the contextual emitters to the final buffer
 * @param {array} k - The parsed at-rule, including the parameters,
 *                    if takes both parameters and a block.
 *                    k == [match, fullAtRule, atRuleType, params?]
 *                    So in `@-webkit-keyframes foo`, we have
 *                     - match = "@-webkit-keyframes foo"
 *                     - fullAtRule = "@-webkit-keyframes"
 *                     - atRuleType = "keyframes"
 *                     - params = "foo"
 * @param {string|string[]|object|object[]} v - Either parameters for
 *                                              block-less rules or
 *                                              their block
 *                                              for the others.
 * @param {string} prefix - the current selector or the selector prefix
 *                          in case of nested rules
 * @param {boolean} local - are we in @local or in @global scope?
 * @param {string} nestingDepth - are we nested in an at-rule or a selector?
 */
 
function atRules(state, emit, k, v, prefix, local, nestingDepth) {
 
  // First iterate over user-provided at-rules and return if one of them corresponds to the current one
  for (var i = 0; i < state.atruleHandlers.length; i++) {
 
    if (state.atruleHandlers[i](state, emit, k, v, prefix, local, nestingDepth)) return
 
  }
 
  // using `/^global$/.test(k[2])` rather that 'global' == k[2] gzips
  // slightly better thanks to the regexps tests further down.
  // It is slightly less efficient but this isn't a critical path.
 
  if (!k[3] && /^global$/.test(k[2])) {
 
    rules(state, emit, prefix, v, 0, nestingDepth);
 
 
  } else if (!k[3] && /^local$/.test(k[2])) {
 
    rules(state, emit, prefix, v, 1, nestingDepth);
 
 
  } else if (k[3] && /^adopt$/.test(k[2])) {
 
    if (!local || nestingDepth) return emit.err('@adopt global or nested: ' + k[0])
 
    if (!/^\.?[_A-Za-z][-\w]*$/.test(k[3])) return emit.err('bad adopter ' + JSON.stringify(k[3]) + ' in ' + k[0])
 
    i = [];
    flatIter(function(adoptee, asString) {
 
      if(adoptee == null || !/^\.?[_A-Za-z][-\w]*(?:\s+\.?[_A-Za-z][-\w]*)*$/.test(asString = adoptee + '')) emit.err('bad adoptee '+ JSON.stringify(adoptee) + ' in ' + k[0]);
 
      else i.push(asString.replace(/\./g, ''));
 
    })(v);
 
    // we may end up with duplicate classes but AFAIK it has no consequences on specificity.
    if (i.length) {
      state.localize(k[3] = k[3].replace(/\./g, ''));
      state.names[k[3]] += (' ' + i.join(' '));
    }
 
 
  } else if (!k[3] && /^(?:namespace|import|charset)$/.test(k[2])) {
    flatIter(function(v) {
 
      emit.atrule(k[1], k[2], v);
 
    })(v);
 
 
  } else if (!k[3] && /^(?:font-face|viewport)$/.test(k[2])) {
    flatIter(function(v) {
 
      emit.atrule(k[1], k[2], k[3], 'decl');
 
      declarations(state, emit, '', v, local);
 
      emit._atrule();
 
    })(v);
 
  } else if (k[3] && /^(?:media|supports|page|keyframes)$/.test(k[2])) {
 
    if (local && 'keyframes' == k[2]) {
      k[3] = k[3].replace(
        // generated by script/regexps.js
        /(var\([^)]+\))|:?global\(\s*([_A-Za-z][-\w]*)\s*\)|()(-?[_A-Za-z][-\w]*)/,
        state.localizeReplacer
      );
    }
 
    if ('page' == k[2]) {
 
      emit.atrule(k[1], k[2], k[3], 'decl');
 
      declarations(state, emit, '', v, local);
 
    } else {
 
      emit.atrule(k[1], k[2], k[3], 'rule');
 
      rules(
        state, emit,
        'keyframes' == k[2] ? '' : prefix,
        v, local, nestingDepth + 1
      );
 
    }
 
    emit._atrule();
 
  } else {
 
    emit.err('Unsupported at-rule: ' + k[0]);
 
  }
}
 
/**
 * Add rulesets and other CSS tree to the sheet.
 *
 * @param {object} state - holds the localizer- and walker-related methods
 *                         and state
 * @param {object} emit - the contextual emitters to the final buffer
 * @param {string} prefix - the current selector or a prefix in case of nested rules
 * @param {array|string|object} tree - a source object or sub-object.
 * @param {string} nestingDepth - are we nested in an at-rule?
 * @param {boolean} local - are we in @local or in @global scope?
 */
function rules(state, emit, prefix, tree, local, nestingDepth) {
  var k, v, inDeclaration, kk;
 
  switch (type.call(tree)) {
 
  case OBJECT:
    for (k in tree) if (own.call(tree, k)) {
      v = tree[k];
 
      if (prefix.length > 0 && /^\*?[-\w$]+$/.test(k)) {
        if (!inDeclaration) {
          inDeclaration = 1;
 
          emit.rule(prefix);
 
        }
        if (/\$/.test(k)) {
          for (kk in (k = k.split('$'))) if (own.call(k, kk)) {
 
            declarations(state, emit, k[kk], v, local);
 
          }
        } else {
 
          declarations(state, emit, k, v, local);
 
        }
 
      } else if (/^@/.test(k)) {
        // Handle At-rules
        inDeclaration = 0;
 
        atRules(state, emit,
          /^(.(?:-[\w]+-)?([_A-Za-z][-\w]*))\b\s*([\s\S]*?)\s*$/.exec(k) || [k,'@','',''],
          v, prefix, local, nestingDepth
        );
 
      } else {
        // selector or nested sub-selectors
        inDeclaration = 0;
 
        if (k === '') {
          emit._rule();
          emit.err("Invalid selector ''");
          continue
        }
 
        rules(
          state, emit,
          // build the selector `prefix` for the next iteration.
          // ugly and full of redundant bits but so far the fastest/shortest.gz
          /*0 if*/(prefix.length > 0 && (/,/.test(prefix) || /,/.test(k))) ?
 
            /*0 then*/ (kk = splitSelector(prefix), splitSelector(
              local ?
 
                k.replace(
                  /("(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'|\/\*[\s\S]*?\*\/)|:global\(\s*(\.-?[_A-Za-z][-\w]*)\s*\)|(\.)(-?[_A-Za-z][-\w]*)/g,
                  state.localizeReplacer
                ) :
 
                k
            ).map(function (k) {
              return /&/.test(k) ? ampersand(k, kk) : kk.map(function(kk) {
                return kk + k
              }).join(',')
            }).join(',')) :
 
            /*0 else*/ /*1 if*/ /&/.test(k) ?
 
              /*1 then*/ ampersand(
                local ?
 
                  k.replace(
                    /("(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'|\/\*[\s\S]*?\*\/)|:global\(\s*(\.-?[_A-Za-z][-\w]*)\s*\)|(\.)(-?[_A-Za-z][-\w]*)/g,
                    state.localizeReplacer
                  ) :
 
                  k,
                [prefix]
              ) :
 
              /*1 else*/ prefix + (
                local ?
 
                  k.replace(
                    /("(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'|\/\*[\s\S]*?\*\/)|:global\(\s*(\.-?[_A-Za-z][-\w]*)\s*\)|(\.)(-?[_A-Za-z][-\w]*)/g,
                    state.localizeReplacer
                  ) :
 
                  k
                ),
           v, local, nestingDepth + 1
        );
 
      }
    }
 
    break
 
  case ARRAY:
    for (k = 0; k < tree.length; k++){
 
      rules(state, emit, prefix, tree[k], local, nestingDepth);
 
    }
    break
 
  case STRING:
    // CSS hacks or ouptut of `j2c.inline`. Even raw rulesets if in top position.
 
    if (prefix.length) emit.rule(prefix);
 
    emit.raw(tree);
 
  }
}
 
// This is the first entry in the filters array, which is
// actually the last step of the compiler. It inserts
// closing braces to close normal (non at-) rules (those
// that start with a selector). Doing it earlier is
// impossible without passing state around in unrelated code
// or ending up with duplicated selectors when the source tree
// contains arrays.
// There's no `_rule` handler, because the core compiler never
// calls it.
function closeSelectors(next, inline) {
  var lastSelector;
  return inline ? next : {
    init: function(){lastSelector = ''; next.init();},
    done: function () {
      if (lastSelector) {next._rule(); lastSelector = '';}
      return next.done()
    },
    atrule: function (rule, kind, param, takesBlock) {
      if (lastSelector) {next._rule(); lastSelector = '';}
      next.atrule(rule, kind, param, takesBlock);
    },
    _atrule: function (rule) {
      if (lastSelector) {next._rule(); lastSelector = '';}
      next._atrule(rule);
    },
    rule: function (selector) {
      if (selector !== lastSelector){
        if (lastSelector) next._rule();
        next.rule(selector);
        lastSelector = selector;
      }
    },
    _rule: function(){
      if (lastSelector) {next._rule(); lastSelector = '';}
    }
  }
}
 
function invoke(fn, tree, state, backend) {
  backend.init();
  try{
    fn(
      state,
      backend,
      '', // prefix
      tree,
      1,  // local, by default
      0   // nesting depth, only for sheet
    );
  } catch(e) {backend.err(e instanceof Error ? e.stack : '' + e);}
  return backend.done()
}
 
function makeInstance(prefix, suffix, atruleHandlers, nsCache, backend, setPropList) {
  var names = {};
  function localize(name) {
    if (!own.call(names, name)) names[name] = prefix + name + suffix;
    return names[name].match(/^\S+/)
  }
  var state =  {
    atruleHandlers: atruleHandlers,
    names: names,
    /**
     * Returns a localized version of a given name.
     * Registers the pair in `instnace.name` if needed.
     *
     * @param {string} name - the name to localize
     * @return {string} - the localized version
     */
    localize: localize,
    /**
     * Used as second argument for str.replace(localizeRegex, replacer)
     * `ignore`, `global` and `(dot, name)` are mutually exclusive
     *
     * @param {string} match - the whole match (ignored)
     * @param {string|null} ignore - a comment or a string literal
     * @param {string|null} global - a global name
     * @param {string|null} dot - either '.' for a local class name or the empty string otherwise
     * @param {string|null} name - the name to localize
     * @return {string}
     */
    localizeReplacer: function (match, ignore, global, dot, name) {
      return ignore || global || dot + localize(name)
    }
  };
 
  var instance = {
    ns: function(name) {
      var prefix = '__'+name.replace(/\W+/g, '_') + '_';
      if (!own.call(nsCache, prefix)) {
        nsCache[prefix] = makeInstance(prefix, suffix, atruleHandlers, nsCache, backend, setPropList);
      }
      return nsCache[prefix]
    },
    names: names,
    prefix: prefix,
    suffix: suffix,
    sheet: function(tree) {return invoke(rules, tree, state, backend[0])},
    inline: function (tree) {return invoke(declarations, tree, state, backend[1])}
  };
  for (var i = setPropList.length; i--;) defaults(instance, setPropList[i]);
  return instance
}
 
function J2c(options) {
  options = options || {};
  // the buffer that accumulates the output. Initialized in `$sink.init()`
  var buf, err;
 
  // the default sink.
  var _backend = [{
    init: function () {buf=[], err=[];},
    done: function (raw) {
      if (err.length != 0) throw new Error('j2c error(s): ' + JSON.stringify(err,null,2) + ' in context:\n' + buf.join(''))
      return raw ? buf : buf.join('')
    },
    err: function (msg) {
      err.push(msg);
      buf.push('/* +++ ERROR +++ ' + msg + ' */\n');
    },
    raw: function (str) {buf.push(str, '\n');},
    atrule: function (rule, kind, param, takesBlock) {
      buf.push(rule, param && ' ', param, takesBlock ? ' {\n' : ';\n');
    },
    // close atrule
    _atrule: function () {buf.push('}\n');},
    rule: function (selector) {buf.push(selector, ' {\n');},
    // close rule
    _rule: function () {buf.push('}\n');},
    decl: function (prop, value) {buf.push(prop, ':', value, ';\n');}
  }];
 
  // holds the `_filter` and `atrule` handlers
  var _filters = [closeSelectors];
  var _atruleHandlers = [];
  var _setPropList = [];
  var _suffix = randChars(7);
  var _nsCache = {};
 
  // the public API (see the main docs)
 
 
  // handler options
  if (type.call(options.plugins) === ARRAY) {
    flatIter(function(plugin) {
      if (type.call(plugin) !== OBJECT) throw new Error('bad plugin, object expected, got '+ type.call(plugin))
 
      if (type.call(plugin.filter) === FUNCTION) _filters.push(plugin.filter);
      if (type.call(plugin.atrule) === FUNCTION) _atruleHandlers.push(plugin.atrule);
      if (type.call(plugin.sink) === FUNCTION) _backend = plugin.sink();
      if (type.call(plugin.set) === OBJECT) _setPropList.push(plugin.set);
    })(options.plugins);
  }
  if (type.call(options.suffix) === STRING) _suffix = options.suffix;
  if (type.call(options.suffix) === NUMBER) _suffix = randChars(options.suffix);
 
  _backend[1] = _backend[1] || {
    init: _backend[0].init,
    done: _backend[0].done,
    raw: _backend[0].raw,
    err: _backend[0].err,
    decl: _backend[0].decl
  };
 
  // finalize the backend by merging in the filters
  for(var i = 0; i < 2; i++){ // 0 for j2c.sheet, 1 for j2c.inline
    for (var j = _filters.length; j--;) {
      _backend[i] = freeze(
        defaults(
          _filters[j](_backend[i], !!i),
          _backend[i]
        )
      );
    }
  }
  return freeze(makeInstance('', _suffix, _atruleHandlers, _nsCache, _backend, _setPropList))
}
 
module.exports = J2c;