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
"use strict";
var fs = require("fs");
var vm = require("vm");
var components = require("./components");
var languagesCatalog = components.languages;
module.exports = {
/**
* Creates a new Prism instance with the given language loaded
*
* @param {string|string[]} languages
* @returns {Prism}
*/
createInstance: function (languages) {
var context = {
loadedLanguages: [],
Prism: this.createEmptyPrism()
};
languages = Array.isArray(languages) ? languages : [languages];
for (var i = 0, l = languages.length; i < l; i++) {
context = this.loadLanguage(languages[i], context);
}
return context.Prism;
},
/**
* Loads the given language (including recursively loading the dependencies) and
* appends the config to the given Prism object
*
* @private
* @param {string} language
* @param {{loadedLanguages: string[], Prism: Prism}} context
* @returns {{loadedLanguages: string[], Prism: Prism}}
*/
loadLanguage: function (language, context) {
if (!languagesCatalog[language]) {
throw new Error("Language '" + language + "' not found.");
}
// the given language was already loaded
if (-1 < context.loadedLanguages.indexOf(language)) {
return context;
}
// if the language has a dependency -> load it first
if (languagesCatalog[language].require) {
context = this.loadLanguage(languagesCatalog[language].require, context);
}
// load the language itself
var languageSource = this.loadFileSource(language);
context.Prism = this.runFileWithContext(languageSource, {Prism: context.Prism}).Prism;
context.loadedLanguages.push(language);
return context;
},
/**
* Creates a new empty prism instance
*
* @private
* @returns {Prism}
*/
createEmptyPrism: function () {
var coreSource = this.loadFileSource("core");
var context = this.runFileWithContext(coreSource);
return context.Prism;
},
/**
* Cached file sources, to prevent massive HDD work
*
* @private
* @type {Object.<string, string>}
*/
fileSourceCache: {},
/**
* Loads the given file source as string
*
* @private
* @param {string} name
* @returns {string}
*/
loadFileSource: function (name) {
return this.fileSourceCache[name] = this.fileSourceCache[name] || fs.readFileSync(__dirname + "/../../components/prism-" + name + ".js", "utf8");
},
/**
* Runs a VM for a given file source with the given context
*
* @private
* @param {string} fileSource
* @param {*} [context]
*
* @returns {*}
*/
runFileWithContext: function (fileSource, context) {
context = context || {};
vm.runInNewContext(fileSource, context);
return context;
}
};