/*\ title: $:/core/boot.js type: application/javascript The main boot kernel for TiddlyWiki. This single file creates a barebones TW environment that is just sufficient to bootstrap the modules containing the main logic of the application. On the server this file is executed directly to boot TiddlyWiki. In the browser, this file is packed into a single HTML file along with other elements: # bootprefix.js # # boot.js The module definitions on the browser look like this: $tw.defineModule("MyModule","moduletype",function(module,exports,require) { // Module code inserted here return exports; }); In practice, each module is wrapped in a separate script block. \*/ (function() { /*jslint node: true, browser: true */ /*global modules: false, $tw: false */ "use strict"; /////////////////////////// Setting up $tw // Set up $tw global for the server if(typeof(window) === "undefined") { global.$tw = global.$tw || {}; // No `browser` member for the server exports.$tw = $tw; // Export $tw for when boot.js is required directly in node.js } // Include bootprefix if we're on the server if(!$tw.browser) { require("./bootprefix.js"); } // Boot information $tw.boot = {}; // Plugin state $tw.plugins = {}; // Modules store registers all the modules the system has seen $tw.modules = $tw.modules || {}; $tw.modules.titles = $tw.modules.titles || {}; // hashmap by module title of {fn:, exports:, moduleType:} $tw.modules.types = $tw.modules.types || {}; // hashmap by module type of hashmap of exports // Config object $tw.config = $tw.config || {}; // Constants $tw.config.pluginsPath = "../plugins/"; $tw.config.wikiInfo = $tw.config.wikiInfo || "./tiddlywiki.info"; $tw.config.wikiPluginsSubDir = $tw.config.wikiPluginsSubDir || "./plugins"; $tw.config.wikiShadowsSubDir = $tw.config.wikiShadowsSubDir || "./wiki"; $tw.config.wikiTiddlersSubDir = $tw.config.wikiTiddlersSubDir || "./tiddlers"; $tw.config.jsModuleHeaderRegExpString = "^\\/\\*\\\\\\n((?:^[^\\n]*\\n)+?)(^\\\\\\*\\/$\\n?)"; // File extension mappings $tw.config.fileExtensionInfo = { ".tid": {type: "application/x-tiddler"}, ".tiddler": {type: "application/x-tiddler-html-div"}, ".recipe": {type: "application/x-tiddlywiki-recipe"}, ".txt": {type: "text/plain"}, ".css": {type: "text/css"}, ".html": {type: "text/html"}, ".js": {type: "application/javascript"}, ".json": {type: "application/json"}, ".pdf": {type: "application/pdf"}, ".jpg": {type: "image/jpeg"}, ".jpeg": {type: "image/jpeg"}, ".png": {type: "image/png"}, ".gif": {type: "image/gif"}, ".svg": {type: "image/svg+xml"} }; // Content type mappings $tw.config.contentTypeInfo = { "text/x-tiddlywiki": {encoding: "utf8", extension: ".tid"}, "application/x-tiddler": {encoding: "utf8", extension: ".tid"}, "application/x-tiddler-html-div": {encoding: "utf8", extension: ".tiddler"}, "application/x-tiddlywiki-recipe": {encoding: "utf8", extension: ".recipe"}, "text/plain": {encoding: "utf8", extension: ".txt"}, "text/css": {encoding: "utf8", extension: ".css"}, "text/html": {encoding: "utf8", extension: ".html"}, "application/javascript": {encoding: "utf8", extension: ".js"}, "application/json": {encoding: "utf8", extension: ".json"}, "application/pdf": {encoding: "base64", extension: ".pdf"}, "image/jpeg": {encoding: "base64", extension: ".jpg"}, "image/png": {encoding: "base64", extension: ".png"}, "image/gif": {encoding: "base64", extension: ".gif"}, "image/svg+xml": {encoding: "utf8", extension: ".svg"} }; /////////////////////////// Utility functions $tw.utils = $tw.utils || {}; /* Check if an object has a property */ $tw.utils.hop = function(object,property) { return Object.prototype.hasOwnProperty.call(object,property); }; /* Iterate through all the own properties of an object. Callback is invoked with (element,title,object) */ $tw.utils.each = function(object,callback) { if(object) { for(var f in object) { if($tw.utils.hop(object,f)) { callback(object[f],f,object); } } } } /* Determine if a value is an array */ $tw.utils.isArray = function(value) { return Object.prototype.toString.call(value) == "[object Array]"; }; /* Convert "&" to &, "<" to <, ">" to > and """ to " */ $tw.utils.htmlDecode = function(s) { return s.toString().replace(/</mg,"<").replace(/>/mg,">").replace(/"/mg,"\"").replace(/&/mg,"&"); }; /* Pad a string to a given length with "0"s. Length defaults to 2 */ $tw.utils.pad = function(value,length) { length = length || 2; var s = value.toString(); if(s.length < length) { s = "000000000000000000000000000".substr(0,length - s.length) + s; } return s; }; // Convert a date into YYYYMMDDHHMM format $tw.utils.stringifyDate = function(value) { return value.getUTCFullYear() + $tw.utils.pad(value.getUTCMonth() + 1) + $tw.utils.pad(value.getUTCDate()) + $tw.utils.pad(value.getUTCHours()) + $tw.utils.pad(value.getUTCMinutes()); }; // Parse a date from a YYYYMMDDHHMMSSMMM format string $tw.utils.parseDate = function(value) { if(typeof value === "string") { return new Date(Date.UTC(parseInt(value.substr(0,4),10), parseInt(value.substr(4,2),10)-1, parseInt(value.substr(6,2),10), parseInt(value.substr(8,2)||"00",10), parseInt(value.substr(10,2)||"00",10), parseInt(value.substr(12,2)||"00",10), parseInt(value.substr(14,3)||"000",10))); } else if (value instanceof Date) { return value; } else { return null; } }; // Parse a string array from a bracketted list. For example "OneTiddler [[Another Tiddler]] LastOne" $tw.utils.parseStringArray = function(value) { if(typeof value === "string") { var memberRegExp = /(?:\[\[([^\]]+)\]\])|([^\s]+)/mg, results = [], match; do { match = memberRegExp.exec(value); if(match) { results.push(match[1] || match[2]); } } while(match); return results; } else if ($tw.utils.isArray(value)) { return value; } else { return null; } }; // Parse a block of name:value fields. The `fields` object is used as the basis for the return value $tw.utils.parseFields = function(text,fields) { text.split(/\r?\n/mg).forEach(function(line) { var p = line.indexOf(":"); if(p !== -1) { var field = line.substr(0, p).trim(), value = line.substr(p+1).trim(); fields[field] = value; } }); return fields; }; /* Resolves a source filepath delimited with `/` relative to a specified absolute root filepath. In relative paths, the special folder name `..` refers to immediate parent directory, and the name `.` refers to the current directory */ $tw.utils.resolvePath = function(sourcepath,rootpath) { // If the source path starts with ./ or ../ then it is relative to the root if(sourcepath.substr(0,2) === "./" || sourcepath.substr(0,3) === "../" ) { var src = sourcepath.split("/"), root = rootpath.split("/"); // Remove the filename part of the root root.splice(root.length-1,1); // Process the source path bit by bit onto the end of the root path while(src.length > 0) { var c = src.shift(); if(c === "..") { // Slice off the last root entry for a double dot if(root.length > 0) { root.splice(root.length-1,1); } } else if(c !== ".") { // Ignore dots root.push(c); // Copy other elements across } } return root.join("/"); } else { // If it isn't relative, just return the path return sourcepath; } }; /* Returns true if the `actual` version is greater than or equal to the `required` version. Both are in `x.y.z` format. */ $tw.utils.checkVersions = function(required,actual) { var targetVersion = required.split("."), currVersion = actual.split("."), diff = [parseInt(targetVersion[0],10) - parseInt(currVersion[0],10), parseInt(targetVersion[1],10) - parseInt(currVersion[1],10), parseInt(targetVersion[2],10) - parseInt(currVersion[2],10)]; return (diff[0] > 0) || (diff[0] === 0 && diff[1] > 0) || (diff[0] === 0 && diff[1] === 0 && diff[2] > 0); }; /* Creates a PasswordPrompt object */ $tw.utils.PasswordPrompt = function() { // Store of pending password prompts this.passwordPrompts = []; // Create the wrapper this.promptWrapper = document.createElement("div"); this.promptWrapper.className = "tw-password-wrapper"; document.body.appendChild(this.promptWrapper); // Hide the empty wrapper this.setWrapperDisplay(); }; /* Hides or shows the wrapper depending on whether there are any outstanding prompts */ $tw.utils.PasswordPrompt.prototype.setWrapperDisplay = function() { if(this.passwordPrompts.length) { this.promptWrapper.style.display = "block"; } else { this.promptWrapper.style.display = "none"; } }; /* Adds a new password prompt */ $tw.utils.PasswordPrompt.prototype.createPrompt = function(options) { // Create and add the prompt to the DOM var submitText = options.submitText || "Login", form = document.createElement("form"), html = ["

" + options.serviceName + "

"]; if(!options.noUserName) { html.push(""); } html.push("", ""); form.className = "form-inline"; form.innerHTML = html.join("\n"); this.promptWrapper.appendChild(form); window.setTimeout(function() { form.elements[0].focus(); },10); // Add a submit event handler var self = this; form.addEventListener("submit",function(event) { // Collect the form data var data = {},t; for(t=0; t 1) { fields = $tw.utils.parseFields(split[0],fields); fields.text = split.slice(1).join("\n\n"); } else { fields.text = text; } return [fields]; } }); $tw.modules.define("$:/boot/tiddlerdeserializer/txt","tiddlerdeserializer",{ "text/plain": function(text,fields) { fields.text = text; fields.type = "text/plain"; return [fields]; } }); $tw.modules.define("$:/boot/tiddlerdeserializer/html","tiddlerdeserializer",{ "text/html": function(text,fields) { fields.text = text; fields.type = "text/html"; return [fields]; } }); $tw.modules.define("$:/boot/tiddlerdeserializer/json","tiddlerdeserializer",{ "application/json": function(text,fields) { var tiddlers = JSON.parse(text); return tiddlers; } }); /////////////////////////// Intermediate initialisation /* Create the wiki store for the app */ $tw.wiki = new $tw.Wiki(); /////////////////////////// Browser definitions if($tw.browser) { /* Get any encrypted tiddlers */ $tw.boot.decryptEncryptedTiddlers = function(callback) { var encryptedArea = document.getElementById("encryptedArea"), encryptedTiddlers = []; if(encryptedArea) { for(var t = 0; t =0; t--) { var decrypted = $tw.crypto.decrypt(encryptedTiddlers[t]); if(decrypted) { var json = JSON.parse(decrypted); for(var title in json) { $tw.preloadTiddler(json[title]); } encryptedTiddlers.splice(t,1); } } // Check if we're all done if(encryptedTiddlers.length === 0) { // Call the callback callback(); // Exit and remove the password prompt return true; } else { // We didn't decrypt everything, so continue to prompt for password return false; } } }); } else { // Just invoke the callback straight away if there wasn't any encrypted tiddlers callback(); } }; /* Execute the module named 'moduleName'. The name can optionally be relative to the module named 'moduleRoot' */ $tw.modules.execute = function(moduleName,moduleRoot) { /*jslint evil: true */ var name = moduleRoot ? $tw.utils.resolvePath(moduleName,moduleRoot) : moduleName, require = function(modRequire) { return $tw.modules.execute(modRequire,name); }, exports = {}, moduleInfo = $tw.modules.titles[name]; if(!moduleInfo) { throw new Error("Cannot find module named '" + moduleName + "' required by module '" + moduleRoot + "', resolved to " + name); } if(!moduleInfo.exports) { if(typeof moduleInfo.definition === "string") { // String moduleInfo.definition = window["eval"]("(function(module,exports,require) {" + moduleInfo.definition + "})"); moduleInfo.exports = {}; moduleInfo.definition(moduleInfo,moduleInfo.exports,require); } else if(typeof moduleInfo.definition === "function") { // Function moduleInfo.exports = {}; moduleInfo.definition(moduleInfo,moduleInfo.exports,require); } else { // Object moduleInfo.exports = moduleInfo.definition; } } return moduleInfo.exports; }; /* Register a deserializer that can extract tiddlers from the DOM */ $tw.modules.define("$:/boot/tiddlerdeserializer/dom","tiddlerdeserializer",{ "(DOM)": function(node) { var extractTextTiddlers = function(node) { var e = node.firstChild; while(e && e.nodeName.toLowerCase() !== "pre") { e = e.nextSibling; } var title = node.getAttribute ? node.getAttribute("title") : null; if(e && title) { var attrs = node.attributes, tiddler = { text: $tw.utils.htmlDecode(e.innerHTML) }; for(var i=attrs.length-1; i >= 0; i--) { tiddler[attrs[i].name] = attrs[i].value; } return [tiddler]; } else { return null; } }, extractModuleTiddlers = function(node) { if(node.hasAttribute && node.hasAttribute("data-tiddler-title")) { var text = node.innerHTML, s = text.indexOf("{"), e = text.lastIndexOf("}"); if(node.hasAttribute("data-module") && s !== -1 && e !== -1) { text = text.substring(s+1,e); } var fields = {text: text}, attributes = node.attributes; for(var a=0; a titlePrefix.length) { bundleInfo.tiddlers[bundleTiddlers[t].title.substr(titlePrefix.length)] = bundleTiddlers[t]; } else { console.log("Error extracting plugin bundle: The bundle '" + bundleInfo.title + "' cannot contain a tiddler titled '" + bundleTiddlers[t].title + "'"); } } } } // Save the bundle tiddler return bundleInfo ? { title: bundleInfo.title, type: "application/json", bundle: "yes", text: JSON.stringify(bundleInfo) } : null; }; /* Execute the module named 'moduleName'. The name can optionally be relative to the module named 'moduleRoot' */ $tw.modules.execute = function(moduleName,moduleRoot) { var name = moduleRoot ? $tw.utils.resolvePath(moduleName,moduleRoot) : moduleName, moduleInfo = $tw.modules.titles[name], tiddler = $tw.wiki.getTiddler(name), sandbox = { module: moduleInfo, exports: {}, console: console, process: process, $tw: $tw, require: function(title) { return $tw.modules.execute(title,name); } }; if(!moduleInfo) { // If we don't have a module with that name, let node.js try to find it return require(moduleName); } // Execute the module if we haven't already done so if(!moduleInfo.exports) { try { // Check the type of the definition if(typeof moduleInfo.definition === "string") { // String vm.runInNewContext(moduleInfo.definition,sandbox,tiddler.fields.title); moduleInfo.exports = sandbox.exports; } else if(typeof moduleInfo.definition === "function") { // Function moduleInfo.exports = moduleInfo.definition(moduleInfo,sandbox.require,moduleInfo.exports); } else { // Object moduleInfo.exports = moduleInfo.definition; } } catch(e) { throw "Error executing boot module " + name + ":\n" + e; } } // Return the exports of the module return moduleInfo.exports; }; $tw.loadTiddlers = function() { // On the server, we load tiddlers from specified folders var folders = [ $tw.boot.bootPath, path.resolve($tw.boot.wikiPath,$tw.config.wikiShadowsSubDir), path.resolve($tw.boot.wikiPath,$tw.config.wikiTiddlersSubDir) ]; for(var t=0; t