Example #1
0
        .map(match => {
          const relativePath = path.posix.relative(slashedDirname, match);

          return path.posix.dirname(match) === slashedDirname
            ? `./${relativePath}`
            : relativePath;
        })
Example #2
0
function main({ n, path }) {
  bench.start();
  for (var i = 0; i < n; i++) {
    posix.dirname(path);
  }
  bench.end(n);
}
Example #3
0
function main({ n, path }) {
  bench.start();
  for (var i = 0; i < n; i++) {
    posix.dirname(i % 3 === 0 ? `${path}${i}` : path);
  }
  bench.end(n);
}
/**
 * Replace external references in a specification with the contents.  Mutates the given objects.
 * Mutually recursive with `replaceRefs`.
 * @param {string} cwd The path to the file containing a reference.
 * @param {object} top The top-level specification file.
 * @param {object} obj The object referencing an external file.
 * @param {string} context The current reference path, e.g. `"#/paths/%2F/"`
 * @todo test failure
*/
function replaceReference(cwd, top, obj, context) {
  var ref = pathUtils.join(cwd, obj.$ref)
  var external = pathUtils.relative(path.posix.dirname(top["x-spec-path"]), ref)
  var referenced = module.exports.fetchReference(ref)
  if(typeof referenced === "object") {
    resolveLocal(referenced, referenced, "#/")
    referenced["x-external"] = external;
    module.exports.replaceRefs(path.posix.dirname(ref), top, referenced, context)
  }
  if(contexts.definition(context)) {
    if(!top.definitions) { top.definitions = {}; }
    if(!top.definitions[external]) { top.definitions[external] = referenced; }
    // Object.assign(obj, { "$ref": "#/definitions/"+external.replace("/", "%2F") })
    Object.assign(obj, { "$ref": external })
  }
  else if(contexts.path(context)) {
    Object.keys(referenced).forEach(function(method) {
      if(httpMethods.indexOf(method) < 0) {
        delete path[method];
        return;
      }
      var operation = referenced[method];
      operation.method = method;
      var operationTags = operation.tags || ["default"];
      operationTags.forEach(function(tag) {
        top.tags = top.tags || [];
        var tagDef = _.find(top.tags, {name: tag})
        if(!tagDef) {
          tagDef = {name: tag, operations: []};
          top.tags.push(tagDef)
        }
        tagDef.operations = tagDef.operations || [];
        tagDef.operations.push(operation)
      })
    })
    Object.assign(obj, referenced)
    delete obj.$ref;
  }
  else {
    Object.assign(obj, referenced)
    delete obj.$ref;
  }
}
Example #5
0
	const requireFromOutputVia = importer => importee => {
		const outputId = path.posix.join(path.posix.dirname(importer), importee);
		const chunk = output[outputId];
		if (chunk) {
			return requireWithContext(
				chunk.code,
				Object.assign({ require: requireFromOutputVia(outputId) }, context)
			);
		} else {
			return require(importee);
		}
	};
Example #6
0
const splitPrefix = (p, prefixSize) => {
  const pathSize = 100
  let pp = p
  let prefix = ''
  let ret
  const root = pathModule.parse(p).root || '.'

  if (Buffer.byteLength(pp) < pathSize)
    ret = [pp, prefix, false]
  else {
    // first set prefix to the dir, and path to the base
    prefix = pathModule.dirname(pp)
    pp = pathModule.basename(pp)

    do {
      // both fit!
      if (Buffer.byteLength(pp) <= pathSize &&
          Buffer.byteLength(prefix) <= prefixSize)
        ret = [pp, prefix, false]

      // prefix fits in prefix, but path doesn't fit in path
      else if (Buffer.byteLength(pp) > pathSize &&
          Buffer.byteLength(prefix) <= prefixSize)
        ret = [pp.substr(0, pathSize - 1), prefix, true]

      else {
        // make path take a bit from prefix
        pp = pathModule.join(pathModule.basename(prefix), pp)
        prefix = pathModule.dirname(prefix)
      }
    } while (prefix !== root && !ret)

    // at this point, found no resolution, just truncate
    if (!ret)
      ret = [p.substr(0, pathSize - 1), '', true]
  }
  return ret
}
Example #7
0
export default function closestAncestor<T>(
  source: Bundle$Namespace<T>,
  key: string
): void | T {
  const name = posix.basename(key)
  let namespace = posix.dirname(key)

  if (namespace === '.') {
    return source.get(name)
  }

  namespace = posix.dirname(namespace)

  const ancestor = source.get(posix.join(namespace, name))

  if (ancestor) {
    return ancestor
  }

  return closestAncestor(
    source,
    posix.join(posix.dirname(namespace), name)
  )
}
/**
 * Fetches a section of an external file.
 * @param {string} ref The file path or URL referenced.
 * @return {object} The section requested.
 * @throws {LocalRefError} if 'ref' points to a local definition (starts with `#`)
 * @todo Improve YAML detection
 * @todo Improve cache preformance by ensuring paths are normalized, etc.
 * @todo Test failure
*/
function fetchReference(ref) {

  if(localReference(ref)) {
    throw new LocalRefError("fetchReference('"+ref+"') given a reference to the current file.")
  }

  var file = ref.split("#", 1)[0];
  var refPath = ref.substr(file.length + 1)

  var src = null;

  if(_cache[file]) {
    src = _cache[file];
  }
  else {
    if(pathUtils.absoluteURL(file)) {
      src = request("GET", file).body;
    }
    else {
      // fs module can handle posix file separator on Windows
      src = fs.readFileSync(file, "utf8")
    }
    if(file.indexOf(".yml") > -1 || file.indexOf(".yaml") > -1) {
      src = yaml.safeLoad(src)
    }
    else {
      src = JSON.parse(src)
    }
    _cache[file] = src;
  }

  if(refPath.length > 0) {
    src = jsonSearch(refPath, src)
  }

  if(src.$ref && typeof src.$ref === "string" && !localReference(src.$ref)) {
    src = fetchReference(pathUtils.join(path.posix.dirname(ref), src.$ref))
  }

  return src;
}
Example #9
0
 function initDeps(file) {
     if (debug)
         console.log(file);
     var map_dep_chain = getOrInit(map2d_file_dep_chain, file, Map);
     var fileContent = fs.readFileSync(file, "utf8");
     let match;
     // check for import statements
     // Example: import Baz = foo.bar.Baz;
     var importPattern = /^\s*import\s+(?:[^\s]+)\s*=\s*([^\s]+);/gm;
     while (match = importPattern.exec(fileContent)) {
         let fileNoExt = path.join(rootPath, match[1].replace(/\./g, '/'));
         let dep = null;
         while (fileNoExt) {
             dep = FileUtils.findFileWithExtension(fileNoExt, extensions);
             if (dep)
                 break;
             fileNoExt = fileNoExt.substr(0, fileNoExt.lastIndexOf('/'));
         }
         if (dep && dep != file) {
             if (debug)
                 console.log(file, '>', path.basename(dep));
             map_dep_chain.set(dep, [file, dep]);
             graph.add(file, dep);
         }
     }
     // check for extends class in same package
     // Example: export class Foo extends Bar<Baz>
     var extendsPattern = /^\s*(?:export\s+)?(?:abstract\s+)?(?:class|interface)\s+(?:[^\s]+)\s+(?:implements\s+(?:[^\s]+)\s+)?extends\s+([^\s<]+)/gm;
     while (match = extendsPattern.exec(fileContent)) {
         let fileNoExt = path.join(path.dirname(file), match[1]);
         let dep = FileUtils.findFileWithExtension(fileNoExt, ['.tsx', '.ts']);
         if (dep) {
             if (debug)
                 console.log(file, 'extends', path.basename(dep));
             map_dep_chain.set(dep, [file, dep]);
             graph.add(file, dep);
         }
     }
 }
function _joinModulesToString(modules, string, dest, options) {
  for (var idx = 0; idx < modules.length; idx++) {
    var module = modules[idx];

    var relative = path.posix.relative(path.posix.dirname(dest), module);
    var finalPath = path.posix.join('./', relative)

    if (!finalPath.startsWith('.')) {
      finalPath = './' + finalPath;      
    }

    string += options.tab + options.quot + finalPath + options.quot;

    if (idx !== modules.length - 1) {
      string += ',' + options.eol;
    }
  }

  if (options.endComma) {
    string += ',';
  }

  return string;
}
Example #11
0
module.exports = function () {
    let debug = false;
    let FileUtils = require('./FileUtils');
    let fs = require('fs');
    let minimist = require('minimist');
    let path = require('path').posix;
    let lodash = require('lodash');
    let tsort = require('tsort');
    /**
     * main-import-tool
     * -f: Filename for main import file.
     * -d: Base source directory.
     * -x: A comma-separated list of paths to exclude from the output.
     * --ext: A comma-separated list of extensions to include in the output. Default: .tsx,.ts
     */
    let args = minimist(process.argv, { string: ["d", "f", "x", "ext"] });
    let sourceDir = args.d;
    let importFileName = args.f;
    let excludedFiles = args.x ? args.x.split(",") : [];
    let extensions = args.ext ? args.ext.split(",") : [".tsx", ".ts"];
    excludedFiles.push(importFileName);
    if (!sourceDir || !fs.statSync(sourceDir).isDirectory()) {
        console.error("A base source directory must be specified with -d.");
        process.exit(-1);
    }
    if (!importFileName) {
        console.error("A main import file must be specified with -f.");
        process.exit(-1);
    }
    let rootPath = path.dirname(importFileName);
    let filePaths = FileUtils.listFiles(sourceDir, excludedFiles, extensions, []);
    let graph = tsort();
    function getOrInit(map, key, type) {
        return map.has(key) ? map.get(key) : map.set(key, new type()).get(key);
    }
    let map2d_file_dep_chain = new Map();
    function initDeps(file) {
        if (debug)
            console.log(file);
        var map_dep_chain = getOrInit(map2d_file_dep_chain, file, Map);
        var fileContent = fs.readFileSync(file, "utf8");
        let match;
        // check for import statements
        // Example: import Baz = foo.bar.Baz;
        var importPattern = /^\s*import\s+(?:[^\s]+)\s*=\s*([^\s]+);/gm;
        while (match = importPattern.exec(fileContent)) {
            let fileNoExt = path.join(rootPath, match[1].replace(/\./g, '/'));
            let dep = null;
            while (fileNoExt) {
                dep = FileUtils.findFileWithExtension(fileNoExt, extensions);
                if (dep)
                    break;
                fileNoExt = fileNoExt.substr(0, fileNoExt.lastIndexOf('/'));
            }
            if (dep && dep != file) {
                if (debug)
                    console.log(file, '>', path.basename(dep));
                map_dep_chain.set(dep, [file, dep]);
                graph.add(file, dep);
            }
        }
        // check for extends class in same package
        // Example: export class Foo extends Bar<Baz>
        var extendsPattern = /^\s*(?:export\s+)?(?:abstract\s+)?(?:class|interface)\s+(?:[^\s]+)\s+(?:implements\s+(?:[^\s]+)\s+)?extends\s+([^\s<]+)/gm;
        while (match = extendsPattern.exec(fileContent)) {
            let fileNoExt = path.join(path.dirname(file), match[1]);
            let dep = FileUtils.findFileWithExtension(fileNoExt, ['.tsx', '.ts']);
            if (dep) {
                if (debug)
                    console.log(file, 'extends', path.basename(dep));
                map_dep_chain.set(dep, [file, dep]);
                graph.add(file, dep);
            }
        }
    }
    function formatDepChain(chain) {
        return chain.map(filePath => path.basename(filePath)).join(' -> ');
    }
    function checkDependency(file, dep, chain = null) {
        var map_dep_chain = map2d_file_dep_chain.get(file);
        var hasChain = map_dep_chain.get(dep);
        if (hasChain !== undefined)
            return hasChain;
        if (!chain)
            chain = [];
        // avoid infinite recursion
        if (chain.indexOf(file) >= 0)
            return null;
        chain.push(file);
        hasChain = null;
        for (let [ref, hasRef] of map_dep_chain) {
            if (ref == dep || !hasRef)
                continue;
            let subChain = checkDependency(ref, dep, chain);
            if (subChain) {
                let newChain = checkDependency(file, ref).concat(subChain.slice(1));
                if (!hasChain || newChain.length < hasChain.length)
                    map_dep_chain.set(dep, hasChain = newChain);
            }
        }
        chain.pop();
        map_dep_chain.set(dep, hasChain);
        return hasChain;
    }
    // get direct dependencies
    filePaths.sort().forEach(initDeps);
    // topological sort
    let ordered = graph.sort().reverse();
    filePaths = Array.from(new Set(ordered.concat(filePaths)));
    filePaths = filePaths.slice(ordered.length).concat(ordered);
    // check for circular dependencies
    filePaths.forEach(f => {
        var chain = checkDependency(f, f);
        if (chain)
            console.error(`Found circular dependency: ${formatDepChain(chain)}`);
    });
    // generate output file
    let stream = fs.createWriteStream(importFileName, { flags: 'w' });
    for (let filePath of filePaths)
        stream.write(`/// <reference path="${"./" + path.relative(path.dirname(importFileName), filePath)}"/>\n`);
    stream.end();
};
'use strict';!function(require,directRequire){function a(a,c){const d=b.posix.extname(c),f=b.posix.basename(c),i=b.posix.dirname(c);if('.json'===d&&(h(e.JSON_WXAPPCODE_APPSERVICE),h(e.JSON_APPCONFIG),h(e.JSON_PLUGIN),h(e.JSON_PLUGIN_COMPILED),h(e.JSON_WXAPPCODE_PAGEFRAME),h(e.JSON_WXAPPCODE),h(e.JSON_CUSTOMCOMPONENT_CONFIG),h(e.JSON_CUSTOMCOMPONENT_CONFIG_PLUGIN),h(e.JSON_CUSTOMCOMPONENT_FILES),h(e.JS_APPSERVICE),h(e.JS_APPSERVICE_PLUGIN),h(e.JS_PAGEFRAME),h(e.JS_PAGEFRAME_PLUGIN),h(e.WXML_COMPLETE),h(e.WXML_CUT),h(e.WXML_PLUGIN),'app.json'===f&&(h(e.JS_PLUGINCODE_PAGEFRAME),h(e.JS_PLUGINCODE_APPSERVICE),h(e.JS_SUBPACKAGE_APPSERVICE),h(e.JS_APPSERVICE_WIDGET),h(e.WXSS_MAIN),h(e.WXSS_SUBPACKAGE)),('game.json'===f||'app-config.json'===f)&&(h(e.JSON_APPCONFIG_GAME),h(e.JS_SUBPACKAGE_GAME),h(e.JS_SUBCONTEXT_GAME),h(e.JS_APPSERVICE_GAME),h(e.JS_APPSERVICE_WIDGET)),'plugin.json'===f&&h(e.WXSS_PLUGIN),h(e.JSON_FILE)),'.wxss'===d&&(h(e.JS_PAGEFRAME),h(e.JS_PAGEFRAME_PLUGIN),h(e.JSON_WXAPPCODE_PAGEFRAME),h(e.WXSS_MAIN),h(e.WXSS_SUBPACKAGE),h(e.WXSS_PLUGIN)),'.wxs'===d&&(h(e.WXML_COMPLETE),h(e.WXML_CUT),h(e.WXML_PLUGIN),h(e.JS_APPSERVICE_PLUGIN),h(e.JS_PAGEFRAME_PLUGIN)),'.wxml'===d&&(h(e.JSON_WXAPPCODE_APPSERVICE),h(e.JS_PAGEFRAME),h(e.JS_APPSERVICE_PLUGIN),h(e.JS_PAGEFRAME_PLUGIN),h(e.WXML_COMPLETE),h(e.WXML_CUT),h(e.WXML_PLUGIN)),'.js'===d&&(h(e.JS_APPSERVICE_PLUGIN),('add'==a||'unlink'==a)&&(h(e.JS_APPSERVICE),h(e.JS_APPSERVICE_GAME),h(e.JS_APPSERVICE_WIDGET),h(e.JS_SUBCONTEXT_GAME)),g[e.JS_SUBPACKAGE_GAME]))for(const a in g[e.JS_SUBPACKAGE_GAME])0==c.indexOf(a)&&delete g[e.JS_SUBPACKAGE_GAME][a];if(0<=i.indexOf('/miniprogram_npm/'))for(const a in g)g[a]&&g[a].nodeModules&&h(a);if(g[e.JS_SUBPACKAGE_APPSERVICE])for(const a in g[e.JS_SUBPACKAGE_APPSERVICE])0==c.indexOf(a)&&delete g[e.JS_SUBPACKAGE_APPSERVICE][a];h(c)}const b=require('path'),c=require('./d62fc37d7aa6416d5dcc240ba94175cd.js'),d=require('./84b183688a46c9e2626d3e6f83365e13.js'),e={JS_APPSERVICE:'js.appservice',JS_APPSERVICE_PLUGIN:'js.appservice.plugin',JS_APPSERVICE_WIDGET:'js.widget.appservice',JS_APPSERVICE_GAME:'js.game.appservice',JS_PLUGINCODE_APPSERVICE:'js.plugincode.appservice',JS_PLUGINCODE_PAGEFRAME:'js.plugincode.pageframe',JS_SUBPACKAGE_APPSERVICE:'js.subpackage.appservice',JS_PAGEFRAME:'js.pageframe',JS_PAGEFRAME_PLUGIN:'js.pageframe.plugin',JS_SUBPACKAGE_GAME:'js.subpackage.game',JS_SUBCONTEXT_GAME:'js.subcontext.game',JSON_APPCONFIG:'json.appconfig',JSON_APPCONFIG_GAME:'json.appconfig.game',JSON_PLUGIN:'json.plugin',JSON_WXAPPCODE:'json.wxappcode',JSON_WXAPPCODE_APPSERVICE:'json.wxappcode.appservice',JSON_WXAPPCODE_PAGEFRAME:'json.wxappcode.pageframe',JSON_PLUGIN_COMPILED:'plugin.json.compiled',JSON_CUSTOMCOMPONENT_CONFIG_PLUGIN:'json.customcomponent.config.plugin',JSON_CUSTOMCOMPONENT_CONFIG:'json.customcomponent.config',JSON_CUSTOMCOMPONENT_FILES:'custom.component.files',WXML_CUT:'wxml.cut',WXML_COMPLETE:'wxml.complete',WXML_PLUGIN:'wxml.plugin',WXSS_MAIN:'wxss.main',WXSS_SUBPACKAGE:'wxss.subpackage',WXSS_PLUGIN:'wxss.plugin',JS_FILE:'js.file',JS_MAP_FILE:'js.map.file',JSON_FILE:'json.file'};let f,g={};const h=(a)=>{delete g[a]};module.exports={CACHE_KEYS:e,init:async(b)=>{const e=d.normalizePath(b.projectpath);f&&d.normalizePath(f.dirPath)==e||(f&&f.removeListener('all',a),f=await c(b.projectpath,!0),f.on('all',a),g={})},get:(a,b='main')=>g[a]&&g[a][b],set:function(a,b,c){2==arguments.length&&(c=b,b='main'),g[a]||(g[a]={}),g[a][b]=c},remove:h}}(require('lazyload'),require);
Example #13
0
export default function createController<T: Controller>(
  constructor: Class<T>,
  opts: {
    key: string;
    store: Database;
    parent: ?Controller;
    serializers: Bundle$Namespace<Serializer<*>>;
  }
): T {
  const { key, store, serializers } = opts
  const namespace = posix.dirname(key).replace('.', '')
  let { parent } = opts
  let model = tryCatchSync(() => store.modelFor(posix.basename(key)))
  let serializer = serializers.get(key)

  if (!model) {
    model = null
  }

  if (!parent) {
    parent = null
  }

  if (!serializer) {
    serializer = closestAncestor(serializers, key)
  }

  const instance: T = Reflect.construct(constructor, [{
    model,
    namespace,
    serializer
  }])

  if (serializer) {
    if (!instance.filter.length) {
      instance.filter = [...serializer.attributes]
    }

    if (!instance.sort.length) {
      instance.sort = [...serializer.attributes]
    }
  }

  if (parent) {
    instance.beforeAction = [
      ...parent.beforeAction.map(fn => fn.bind(parent)),
      ...instance.beforeAction.map(fn => fn.bind(instance))
    ]

    instance.afterAction = [
      ...instance.afterAction.map(fn => fn.bind(instance)),
      ...parent.afterAction.map(fn => fn.bind(parent))
    ]
  }

  Reflect.defineProperty(instance, 'parent', {
    value: parent,
    writable: false,
    enumerable: true,
    configurable: false
  })

  return deepFreezeProps(instance, true,
    'query',
    'sort',
    'filter',
    'params',
    'beforeAction',
    'afterAction'
  )
}
Example #14
0
 /*
  * Based on the RequireJS 'standard' for relative locations
  * For SourceScripts, just set the filename to something relative
  * */
 get baseUrl() {
     return path.dirname( this.filename );
 }
Example #15
0
Builder.prototype.build = function(options) {
	const that = this;

	// Stores mapping between "virtual" paths (used within LESS) and real filesystem paths.
	// Only relevant when using the "rootPaths" option.
	const mFileMappings = {};

	// Assign default options
	options = assign({
		lessInput: null,
		lessInputPath: null,
		rtl: true,
		rootPaths: [],
		parser: {},
		compiler: {},
		library: {},
		scope: {}
	}, options);

	// Set default of "relativeUrls" parser option to "true" (less default is "false")
	if (!options.parser.hasOwnProperty("relativeUrls")) {
		options.parser.relativeUrls = true;
	}

	function fileHandler(file, currentFileInfo, handleDataAndCallCallback, callback) {
		const pathname = path.posix.join(currentFileInfo.currentDirectory, file);

		that.fileUtils.readFile(pathname, options.rootPaths).then(function(result) {
			if (!result) {
				// eslint-disable-next-line no-console
				console.log("File not found");
				callback({type: "File", message: "'" + file + "' wasn't found"});
			} else {
				try {
					// Save import mapping to calculate full import paths later on
					mFileMappings[currentFileInfo.rootFilename] = mFileMappings[currentFileInfo.rootFilename] || {};
					mFileMappings[currentFileInfo.rootFilename][pathname] = result.path;

					handleDataAndCallCallback(pathname, result.content);
				} catch (e) {
					// eslint-disable-next-line no-console
					console.log(e);
					callback(e);
				}
			}
		}, function(err) {
			// eslint-disable-next-line no-console
			console.log(err);
			callback(err);
		});
	}

	function compile(config) {
		const parserOptions = clone(options.parser);
		let rootpath;

		if (config.path) {
			// Keep rootpath for later usage in the ImportCollectorPlugin
			rootpath = config.path;
			parserOptions.filename = config.localPath;
		}

		// Keep filename for later usage (see ImportCollectorPlugin) as less modifies the parserOptions.filename
		const filename = parserOptions.filename;

		// Only use custom file handler when "rootPaths" or custom "fs" are used
		let fnFileHandler;
		if ((options.rootPaths && options.rootPaths.length > 0) || that.customFs) {
			fnFileHandler = fileHandler;
		}

		return new Promise(function(resolve, reject) {
			const parser = createParser(parserOptions, fnFileHandler);
			parser.parse(config.content, function(err, tree) {
				if (err) {
					reject(err);
				} else {
					resolve(tree);
				}
			});
		}).then(function(tree) {
			const result = {};

			result.tree = tree;

			// plugins to collect imported files and variable values
			const oImportCollector = new ImportCollectorPlugin({
				importMappings: mFileMappings[filename]
			});
			const oVariableCollector = new VariableCollectorPlugin(options.compiler);

			// render to css
			result.css = tree.toCSS(assign(options.compiler, {
				plugins: [oImportCollector, oVariableCollector]
			}));

			// retrieve imported files
			result.imports = oImportCollector.getImports();

			// retrieve reduced set of variables
			result.variables = oVariableCollector.getVariables(Object.keys(mFileMappings[filename] || {}));

			// retrieve all variables
			result.allVariables = oVariableCollector.getAllVariables();

			// also compile rtl-version if requested
			if (options.rtl) {
				result.cssRtl = tree.toCSS(assign(options.compiler, {
					plugins: [new RTLPlugin()]
				}));
			}

			if (rootpath) {
				result.imports.unshift(rootpath);
			}

			return result;
		});
	}

	function addInlineParameters(result) {
		return new Promise(function(resolve, reject) {
			if (typeof options.library === "object" && typeof options.library.name === "string") {
				const parameters = JSON.stringify(result.variables);

				// properly escape the parameters to be part of a data-uri
				// + escaping single quote (') as it is used to surround the data-uri: url('...')
				const escapedParameters = encodeURIComponent(parameters).replace(/'/g, function(char) {
					return escape(char);
				});

				// embed parameter variables as plain-text string into css
				const parameterStyleRule = "\n/* Inline theming parameters */\n#sap-ui-theme-" +
					options.library.name.replace(/\./g, "\\.") +
					"{background-image:url('data:text/plain;utf-8," + escapedParameters + "')}\n";

				// embed parameter variables as plain-text string into css
				result.css += parameterStyleRule;
				if (result.cssRtl) {
					result.cssRtl += parameterStyleRule;
				}
			}
			resolve(result);
		});
	}

	function getScopeVariables(options) {
		const sScopeName = options.scopeName;
		const oVariablesBase = options.baseVariables;
		const oVariablesEmbedded = options.embeddedVariables;
		const oVariablesDiff = {};

		for (const sKey in oVariablesEmbedded) {
			if (sKey in oVariablesBase) {
				if (oVariablesBase[sKey] != oVariablesEmbedded[sKey]) {
					oVariablesDiff[sKey] = oVariablesEmbedded[sKey];
				}
			}
		}

		// Merge variables
		const oVariables = {};
		oVariables["default"] = oVariablesBase;
		oVariables["scopes"] = {};
		oVariables["scopes"][sScopeName] = oVariablesDiff;

		return oVariables;
	}

	function compileWithScope(scopeOptions) {
		// 1. Compile base + embedded files (both default + RTL variants)
		return Promise.all([
			that.fileUtils.readFile(scopeOptions.embeddedCompareFilePath, options.rootPaths).then(compile),
			that.fileUtils.readFile(scopeOptions.embeddedFilePath, options.rootPaths).then(compile)
		]).then(function(results) {
			return {
				embeddedCompare: results[0],
				embedded: results[1]
			};
		}).then(function(results) {
			const sScopeName = scopeOptions.selector;

			function applyScope(embeddedCompareCss, embeddedCss, bRtl) {
				const restoreStringPrototype = cleanupStringPrototype();

				// Create diff object between embeddedCompare and embedded
				const oBase = css.parse(embeddedCompareCss);
				const oEmbedded = css.parse(embeddedCss);

				restoreStringPrototype();

				const oDiff = diff(oBase, oEmbedded);

				// Create scope
				const sScopeSelector = "." + sScopeName;
				const oScope = scope(oDiff.diff, sScopeSelector);

				let oCssScopeRoot;

				if (oDiff.stack) {
					oCssScopeRoot = scope.scopeCssRoot(oDiff.stack.stylesheet.rules, sScopeName);

					if (oCssScopeRoot) {
						oScope.stylesheet.rules.unshift(oCssScopeRoot);
					}
				}

				// Append scope + stack to embeddedCompareFile (actually target file, which is currently always the same i.e. "library.css")
				// The stack gets appended to the embeddedFile only
				let sAppend = css.stringify(oScope, {
					compress: options.compiler && options.compiler.compress === true
				});

				if (scopeOptions.baseFilePath !== options.lessInputPath && oDiff.stack && oDiff.stack.stylesheet.rules.length > 0) {
					sAppend += "\n" + css.stringify(oDiff.stack, {
						compress: options.compiler && options.compiler.compress === true
					});
				}

				return sAppend + "\n";
			}

			results.embeddedCompare.css += applyScope(results.embeddedCompare.css, results.embedded.css);
			if (options.rtl) {
				results.embeddedCompare.cssRtl += applyScope(results.embeddedCompare.cssRtl, results.embedded.cssRtl, true);
			}

			// Create diff between embeddedCompare and embeded variables
			results.embeddedCompare.variables = getScopeVariables({
				baseVariables: results.embeddedCompare.variables,
				embeddedVariables: results.embedded.variables,
				scopeName: sScopeName
			});
			results.embeddedCompare.allVariables = getScopeVariables({
				baseVariables: results.embeddedCompare.allVariables,
				embeddedVariables: results.embedded.allVariables,
				scopeName: sScopeName
			});

			const concatImports = function(aImportsBase, aImportsEmbedded) {
				const aConcats = aImportsBase.concat(aImportsEmbedded);

				return aConcats.filter(function(sImport, sIndex) {
					return aConcats.indexOf(sImport) == sIndex;
				});
			};

			if (scopeOptions.baseFilePath !== options.lessInputPath) {
				results.embeddedCompare.imports = concatImports(results.embedded.imports, results.embeddedCompare.imports);
			} else {
				results.embeddedCompare.imports = concatImports(results.embeddedCompare.imports, results.embedded.imports);
			}

			// 6. Resolve promise with complete result object (css, cssRtl, variables, imports)
			return results.embeddedCompare;
		});
	}


	function readDotTheming(dotThemingInputPath) {
		return that.fileUtils.readFile(dotThemingInputPath, options.rootPaths).then(function(result) {
			let dotTheming;
			let dotThemingFilePath;

			if (result) {
				dotTheming = JSON.parse(result.content);
				dotThemingFilePath = result.path;
			}

			if (dotTheming && dotTheming.mCssScopes) {
				// Currently only the "library" target is supported
				const cssScope = dotTheming.mCssScopes["library"];

				if (cssScope) {
					const aScopes = cssScope.aScopes;
					const oScopeConfig = aScopes[0]; // Currenlty only one scope is supported

					const sBaseFile = dotThemingFileToPath(cssScope.sBaseFile);
					const sEmbeddedCompareFile = dotThemingFileToPath(oScopeConfig.sEmbeddedCompareFile);
					const sEmbeddedFile = dotThemingFileToPath(oScopeConfig.sEmbeddedFile);

					// Currently, only support the use case when "sBaseFile" equals "sEmbeddedCompareFile"
					if (sBaseFile !== sEmbeddedCompareFile) {
						throw new Error("Unsupported content in \"" + dotThemingInputPath + "\": " +
							"\"sBaseFile\" (\"" + cssScope.sBaseFile + "\") must be identical with " +
							"\"sEmbeddedCompareFile\" (\"" + oScopeConfig.sEmbeddedCompareFile + "\")");
					}

					const baseFilePath = path.posix.join(themeDir, sBaseFile) + ".source.less";
					const embeddedCompareFilePath = path.posix.join(themeDir, sEmbeddedCompareFile) + ".source.less";
					const embeddedFilePath = path.posix.join(themeDir, sEmbeddedFile) + ".source.less";

					// 1. Compile base + embedded files (both default + RTL variants)
					return compileWithScope({
						selector: oScopeConfig.sSelector,
						embeddedFilePath: embeddedFilePath,
						embeddedCompareFilePath: embeddedCompareFilePath,
						baseFilePath: baseFilePath
					}).then(function(embeddedCompare) {
						embeddedCompare.imports.push(dotThemingFilePath);
						return embeddedCompare;
					});
				}
			}

			// No css diffing and scoping
			return that.fileUtils.readFile(options.lessInputPath, options.rootPaths).then(compile);
		});
	}

	if (options.lessInput && options.lessInputPath) {
		return Promise.reject(new Error("Please only provide either `lessInput` or `lessInputPath` but not both."));
	}

	if (!options.lessInput && !options.lessInputPath) {
		return Promise.reject(new Error("Missing required option. Please provide either `lessInput` or `lessInputPath`."));
	}

	if (options.lessInput) {
		return compile({
			content: options.lessInput
		}).then(addInlineParameters).then(that.cacheTheme.bind(that));
	} else {
		// TODO: refactor
		// eslint-disable-next-line no-var
		var themeDir = path.posix.dirname(options.lessInputPath);

		// Always use the sap/ui/core library to lookup .theming files
		let coreThemeDir;

		if (options.library && typeof options.library.name === "string") {
			const libraryNamespace = options.library.name.replace(/\./g, "/");
			coreThemeDir = themeDir.replace(libraryNamespace, "sap/ui/core");
		} else {
			coreThemeDir = themeDir.replace(/^.*\/themes\//, "/sap/ui/core/themes/");
		}

		const dotThemingInputPath = path.posix.join(coreThemeDir, ".theming");

		return that.fileUtils.findFile(options.lessInputPath, options.rootPaths).then(function(fileInfo) {
			if (!fileInfo) {
				throw new Error("`lessInputPath` " + options.lessInputPath + " could not be found.");
			}

			// check theme has been already cached
			let themeCache;
			if (fileInfo.path) {
				themeCache = that.getThemeCache(fileInfo.path);
			}

			const scopeOptions = options.scope;

			// Compile theme if not cached or RTL is requested and missing in cache
			if (!themeCache || (options.rtl && !themeCache.result.cssRtl)) {
				if (scopeOptions.selector && scopeOptions.embeddedFilePath && scopeOptions.embeddedCompareFilePath && scopeOptions.baseFilePath) {
					return compileWithScope(scopeOptions).then(addInlineParameters).then(that.cacheTheme.bind(that));
				}
				return readDotTheming(dotThemingInputPath).then(addInlineParameters).then(that.cacheTheme.bind(that));
			} else {
				return that.fileUtils.statFiles(themeCache.result.imports).then(function(newStats) {
					for (let i = 0; i < newStats.length; i++) {
						// check if .theming and less files have changed since last less compilation
						if (!newStats[i] || newStats[i].stat.mtime.getTime() !== themeCache.stats[i].stat.mtime.getTime()) {
							if (scopeOptions.selector && scopeOptions.embeddedFilePath && scopeOptions.embeddedCompareFilePath && scopeOptions.baseFilePath) {
								return compileWithScope(scopeOptions).then(addInlineParameters).then(that.cacheTheme.bind(that));
							}
							return readDotTheming(dotThemingInputPath).then(addInlineParameters).then(that.cacheTheme.bind(that));
						}
					}

					// serve from cache
					return themeCache.result;
				});
			}
		});
	}
};
'use strict';!function(require,directRequire){function a(){s=''}function b(a,b){let c=e.extname(b);'.js'===c&&('add'==a||'unlink'==a)&&(s='')}async function c(a){let c=await j(a);r&&r.srcPath==c.srcPath||(s='',r&&r.unWatch(b),r=c,r.watch(b))}async function d(a){let b=a.attr.gameApp?await h(a):await g(a);let c=b.widgets;for(let b,d=0,e=c.length;d<e;d++)if(b=c[d],b.type==a.compileType)return b.path}const e=require('path'),f=require('./d28a711224425b00101635efe1034c99.js'),g=require('./1dea83a77e99a7c94f6b6f01f5c175b0.js'),h=require('./1bd2563d13db26950ae47494b2c34454.js'),i=require('./84b183688a46c9e2626d3e6f83365e13.js'),j=require('./162bf2ee28b76d3b3d95b685cede4146.js'),{asDebug:k,htmlBegin:l,htmlEnd:m,vendorList:n,devVendorList:o,noBrowser:p}=require('./bcbc694e4d465af7bbc604e962f3f0e1.js'),q=global.appConfig.isDev&&!nw.App.manifest.forceVendor?o:n;var r,s='';f.on('VENDOR_CONFIG_CHANGE',a),f.on('VENDOR_VERSION_CHANGE',a),module.exports=async function(a,b={}){if(await c(a),!s||b.force){let b=[];const c=require('fs'),g=global.appConfig.isDev?e.join(__dirname,'../../../extensions/appservice/index.js'):e.join(__dirname,'./extensions/appservice/index.js'),h=c.readFileSync(g,'utf8');b.push(l),b.push(`<script>${h}</script>`);for(let a=0,c=q.length;a<c;a++){let c=q[a],d=await f.getFile(c),g=e.extname(c);'.js'===g?b.push(`<script>${d} </script>`):'.css'===g&&b.push(`<style>${d}</style>`)}let i=await d(a),j=r.getAllJSFiles(),k=[],n=e.posix.join(i,'widget'),o=!1;return j.forEach((a)=>{let b=e.posix.normalize(a.replace(/\.js$/,''));0==e.posix.dirname(b).indexOf(i)&&(n==b?o=!0:k.push(`<script src="./${a}"></script>`))}),n=o?`<script src="./${n}.js"></script>
Example #17
0
assert.throws(path.posix.basename.bind(null, 1), TypeError);
assert.throws(path.posix.basename.bind(null), TypeError);
assert.throws(path.posix.basename.bind(null, {}), TypeError);

// POSIX filenames may include control characters
// c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html
const controlCharFilename = 'Icon' + String.fromCharCode(13);
assert.equal(path.posix.basename('/a/b/' + controlCharFilename),
             controlCharFilename);


// path.dirname tests
assert.equal(path.dirname(f).substr(-13),
             common.isWindows ? 'test\\parallel' : 'test/parallel');

assert.equal(path.posix.dirname('/a/b/'), '/a');
assert.equal(path.posix.dirname('/a/b'), '/a');
assert.equal(path.posix.dirname('/a'), '/');
assert.equal(path.posix.dirname(''), '.');
assert.equal(path.posix.dirname('/'), '/');
assert.equal(path.posix.dirname('////'), '/');
assert.equal(path.posix.dirname('foo'), '.');
assert.throws(path.posix.dirname.bind(null, null), TypeError);
assert.throws(path.posix.dirname.bind(null, true), TypeError);
assert.throws(path.posix.dirname.bind(null, 1), TypeError);
assert.throws(path.posix.dirname.bind(null), TypeError);
assert.throws(path.posix.dirname.bind(null, {}), TypeError);

assert.equal(path.win32.dirname('c:\\'), 'c:\\');
assert.equal(path.win32.dirname('c:\\foo'), 'c:\\');
assert.equal(path.win32.dirname('c:\\foo\\'), 'c:\\');
Example #18
0
assert.equal(path.posix.basename(1), '1');
assert.equal(path.posix.basename(), 'undefined');
assert.equal(path.posix.basename({}), '[object Object]');

// POSIX filenames may include control characters
// c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html
const controlCharFilename = 'Icon' + String.fromCharCode(13);
assert.equal(path.posix.basename('/a/b/' + controlCharFilename),
             controlCharFilename);


// path.dirname tests
assert.equal(path.dirname(f).substr(-13),
             common.isWindows ? 'test\\parallel' : 'test/parallel');

assert.equal(path.posix.dirname('/a/b/'), '/a');
assert.equal(path.posix.dirname('/a/b'), '/a');
assert.equal(path.posix.dirname('/a'), '/');
assert.equal(path.posix.dirname(''), '.');
assert.equal(path.posix.dirname('/'), '/');
assert.equal(path.posix.dirname('////'), '/');
assert.equal(path.posix.dirname('foo'), '.');
assert.equal(path.posix.dirname(null), '.');
assert.equal(path.posix.dirname(true), '.');
assert.equal(path.posix.dirname(1), '.');
assert.equal(path.posix.dirname(), '.');
assert.equal(path.posix.dirname({}), '.');

assert.equal(path.win32.dirname('c:\\'), 'c:\\');
assert.equal(path.win32.dirname('c:\\foo'), 'c:\\');
assert.equal(path.win32.dirname('c:\\foo\\'), 'c:\\');