DEV: Remove legacy JS manifests and vendored scripts

Now that we've switched to Ember CLI, these things are no longer used.

- These sprockets manifests are superceded by the assets generated by ember cli
- These vendored scripts are now fetched by ember-auto-import at compile time
This commit is contained in:
David Taylor 2022-06-18 00:52:48 +01:00
parent ba2c7b8f35
commit 1b4692039e
44 changed files with 0 additions and 57600 deletions

View File

@ -1,8 +1,5 @@
app/assets/javascripts/browser-update.js
app/assets/javascripts/discourse-loader.js
app/assets/javascripts/env.js
app/assets/javascripts/main_include_admin.js
app/assets/javascripts/vendor.js
app/assets/javascripts/locales/i18n.js
app/assets/javascripts/ember-addons/
app/assets/javascripts/discourse/lib/autosize.js
@ -13,7 +10,6 @@ lib/pretty_text/
plugins/**/lib/javascripts/locale
public/
vendor/
app/assets/javascripts/discourse/tests/test-boot-rails.js
app/assets/javascripts/discourse/tests/fixtures
node_modules/
spec/

View File

@ -10,9 +10,6 @@ script/import_scripts/**/*.yml
app/assets/javascripts/browser-update.js
app/assets/javascripts/discourse-loader.js
app/assets/javascripts/env.js
app/assets/javascripts/main_include_admin.js
app/assets/javascripts/vendor.js
app/assets/javascripts/locales/i18n.js
app/assets/javascripts/ember-addons/
app/assets/javascripts/discourse/lib/autosize.js
@ -22,7 +19,6 @@ lib/highlight_js/
plugins/**/lib/javascripts/locale
public/
vendor/
app/assets/javascripts/discourse/tests/test-boot-rails.js
app/assets/javascripts/discourse/tests/fixtures
spec/
node_modules/

View File

@ -1,2 +0,0 @@
//= require main_include_admin
//= require admin-plugins

View File

@ -1,27 +0,0 @@
// discourse-skip-module
(function () {
if (window.unsupportedBrowser) {
throw "Unsupported browser detected";
}
let Discourse = requirejs("discourse/app").default.create();
// required for our template compiler
window.__DISCOURSE_RAW_TEMPLATES = requirejs(
"discourse-common/lib/raw-templates"
).__DISCOURSE_RAW_TEMPLATES;
// required for addons to work without Ember CLI
// eslint-disable-next-line no-undef
Object.keys(Ember.TEMPLATES).forEach((k) => {
if (k.indexOf("select-kit") === 0) {
// eslint-disable-next-line no-undef
let template = Ember.TEMPLATES[k];
define(k, () => template);
}
});
// ensure Discourse is added as a global
window.Discourse = Discourse;
})();

View File

@ -1,104 +0,0 @@
//= require_tree ./truth-helpers/addon
//= require_tree ./discourse-common/addon
//= require ./polyfills
//= require_tree ./select-kit/addon
//= require ./discourse/app/app
//= require ./app-boot
// Stuff we need to load first
//= require ./discourse/app/lib/to-markdown
//= require ./discourse/app/lib/utilities
//= require ./discourse/app/lib/user-presence
//= require ./discourse/app/lib/logout
//= require ./discourse/app/mixins/singleton
//= require ./discourse/app/models/rest
//= require ./discourse/app/models/session
//= require ./discourse/app/lib/ajax
//= require ./discourse/app/lib/text
//= require ./discourse/app/lib/hash
//= require ./discourse/app/lib/load-script
//= require ./discourse/app/lib/notification-levels
//= require ./discourse/app/services/app-events
//= require ./discourse/app/lib/offset-calculator
//= require ./discourse/app/lib/lock-on
//= require ./discourse/app/lib/url
//= require ./discourse/app/lib/email-provider-default-settings
//= require ./discourse/app/lib/debounce
//= require ./discourse/app/lib/quote
//= require ./discourse/app/lib/key-value-store
//= require ./discourse/app/lib/computed
//= require ./discourse/app/lib/formatter
//= require ./discourse/app/lib/text-direction
//= require ./discourse/app/lib/eyeline
//= require ./discourse/app/lib/show-modal
//= require ./discourse/app/lib/download-calendar
//= require ./discourse/app/mixins/scrolling
//= require ./discourse/app/lib/ajax-error
//= require ./discourse/app/models/result-set
//= require ./discourse/app/models/store
//= require ./discourse/app/models/action-summary
//= require ./discourse/app/models/permission-type
//= require ./discourse/app/models/category
//= require ./discourse/app/models/topic
//= require ./discourse/app/models/draft
//= require ./discourse/app/models/composer
//= require ./discourse/app/models/badge-grouping
//= require ./discourse/app/models/badge
//= require ./discourse/app/models/permission-type
//= require ./discourse/app/models/user-action-group
//= require ./discourse/app/models/trust-level
//= require ./discourse/app/lib/search
//= require ./discourse/app/lib/user-search
//= require ./discourse/app/lib/export-csv
//= require ./discourse/app/lib/autocomplete
//= require ./discourse/app/lib/after-transition
//= require ./discourse/app/lib/safari-hacks
//= require ./discourse/app/lib/put-cursor-at-end
//= require_tree ./discourse/app/adapters
//= require ./discourse/app/models/post-action-type
//= require ./discourse/app/models/post
//= require ./discourse/app/lib/posts-with-placeholders
//= require ./discourse/app/models/post-stream
//= require ./discourse/app/models/topic-details
//= require ./discourse/app/models/topic
//= require ./discourse/app/models/user-action
//= require ./discourse/app/models/draft
//= require ./discourse/app/models/composer
//= require ./discourse/app/models/user-badge
//= require_tree ./discourse/app/lib
//= require_tree ./discourse/app/mixins
//= require ./discourse/app/models/invite
//= require ./discourse/app/controllers/discovery-sortable
//= require ./discourse/app/controllers/navigation/default
//= require ./discourse/app/components/edit-category-panel
//= require ./discourse/app/lib/link-mentions
//= require ./discourse/app/components/site-header
//= require ./discourse/app/components/d-editor
//= require ./discourse/app/routes/discourse
//= require ./discourse/app/routes/build-topic-route
//= require ./discourse/app/routes/restricted-user
//= require ./discourse/app/routes/user-topic-list
//= require ./discourse/app/routes/user-activity-stream
//= require ./discourse/app/routes/topic-from-params
//= require ./discourse/app/components/text-field
//= require ./discourse/app/components/conditional-loading-spinner
//= require ./discourse/app/helpers/user-avatar
//= require ./discourse/app/helpers/cold-age-class
//= require ./discourse/app/helpers/loading-spinner
//= require ./discourse/app/helpers/category-link
//= require ./discourse/app/lib/export-result
//= require ./discourse/app/mapping-router
//= require_tree ./discourse/app/controllers
//= require_tree ./discourse/app/models
//= require_tree ./discourse/app/components
//= require_tree ./discourse/app/raw-views
//= require_tree ./discourse/app/helpers
//= require_tree ./discourse/app/templates
//= require_tree ./discourse/app/routes
//= require_tree ./discourse/app/pre-initializers
//= require_tree ./discourse/app/initializers
//= require_tree ./discourse/app/services
//= require_tree ./discourse/app/widgets
//= require ./widget-runtime

View File

@ -1,67 +0,0 @@
define("message-bus-client", ["exports"], function (__exports__) {
__exports__.default = window.MessageBus;
});
define("ember-buffered-proxy/proxy", ["exports"], function (__exports__) {
__exports__.default = window.BufferedProxy;
});
define("bootbox", ["exports"], function (__exports__) {
__exports__.default = window.bootbox;
});
define("xss", ["exports"], function (__exports__) {
__exports__.default = window.filterXSS;
});
define("@discourse/itsatrap", ["exports"], function (__exports__) {
__exports__.default = window.ItsATrap;
});
define("@popperjs/core", ["exports"], function (__exports__) {
__exports__.default = window.Popper;
__exports__.createPopper = window.Popper.createPopper;
__exports__.defaultModifiers = window.Popper.defaultModifiers;
__exports__.popperGenerator = window.Popper.popperGenerator;
});
define("tippy.js", ["exports"], function (__exports__) {
__exports__.default = window.tippy;
});
define("@uppy/core", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.Core;
__exports__.BasePlugin = window.Uppy.Core.BasePlugin;
});
define("@uppy/aws-s3", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.AwsS3;
});
define("@uppy/aws-s3-multipart", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.AwsS3Multipart;
});
define("@uppy/xhr-upload", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.XHRUpload;
});
define("@uppy/drop-target", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.DropTarget;
});
define("@uppy/utils/lib/delay", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.Utils.delay;
});
define("@uppy/utils/lib/EventTracker", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.Utils.EventTracker;
});
define("@uppy/utils/lib/AbortController", ["exports"], function (__exports__) {
__exports__.AbortController =
window.Uppy.Utils.AbortControllerLib.AbortController;
__exports__.AbortSignal = window.Uppy.Utils.AbortControllerLib.AbortSignal;
__exports__.createAbortError =
window.Uppy.Utils.AbortControllerLib.createAbortError;
});

View File

@ -1,14 +0,0 @@
// discourse-skip-module
//= require qunit
//= require ember-qunit
//= require fake_xml_http_request
//= require route-recognizer
//= require pretender
//= require sinon
//= require break_string
//= require test-shims
//= require jquery.magnific-popup.min.js
//= require handlebars
//= require ember-template-compiler
//= require markdown-it-bundle

View File

@ -1,6 +0,0 @@
// discourse-skip-module
//= require env
//= require jquery.debug
//= require ember.debug
//= require discourse-loader

View File

@ -1,7 +0,0 @@
<%
if @force_ember_debug || Rails.env.development? || Rails.env.test?
require_asset ("ember.debug.js")
else
require_asset ("ember.prod.js")
end
%>

View File

@ -1,5 +0,0 @@
//= require set-prototype-polyfill
//= require env
//= require jquery
//= require ember_include
//= require discourse-loader

View File

@ -1,3 +0,0 @@
window.ENV = {};
window.EmberENV = window.EmberENV || {};
window.EmberENV.FORCE_JQUERY = true;

View File

@ -1,2 +0,0 @@
//= require discourse/app/lib/export-result
//= require_tree ./admin/addon

View File

@ -1,8 +0,0 @@
/* eslint-disable */
Object.setPrototypeOf =
Object.setPrototypeOf ||
function (obj, proto) {
obj.__proto__ = proto;
return obj;
};
/* eslint-enable */

View File

@ -1,5 +0,0 @@
// discourse-skip-module
(function () {
// eslint-disable-next-line no-undef
Discourse.start();
})();

View File

@ -1,2 +0,0 @@
//= require handlebars.runtime
//= require handlebars-shim

View File

@ -1,64 +0,0 @@
// discourse-skip-module
define("sinon", () => {
return { default: window.sinon };
});
define("qunit", () => {
return {
default: window.QUnit,
test: window.QUnit.test,
skip: window.QUnit.skip,
module: window.QUnit.module,
};
});
define("ember-qunit", () => {
return {
moduleFor: window.moduleFor,
moduleForComponent: window.moduleForComponent,
};
});
define("htmlbars-inline-precompile", () => {
return {
default: function (str) {
// eslint-disable-next-line no-undef
return Ember.HTMLBars.compile(str[0]);
},
};
});
let _app;
define("@ember/test-helpers", () => {
let helpers = {
setApplication(app) {
_app = app;
},
getApplication() {
return _app;
},
async settled() {
// eslint-disable-next-line no-undef, discourse-ember/global-ember
Ember.run(() => {});
},
TestModuleForComponent: window.TestModuleForComponent,
};
[
"click",
"visit",
"currentURL",
"currentRouteName",
"fillIn",
"setResolver",
"triggerEvent",
].forEach((attr) => {
helpers[attr] = function () {
return window[attr](...arguments);
};
});
helpers.triggerKeyEvent = function () {
return window.keyEvent(...arguments);
};
return helpers;
});
define("pretender", () => {
return { default: window.Pretender };
});

View File

@ -1,19 +0,0 @@
//= require logster
//= require template_include.js
//= require message-bus
//= require Markdown.Converter.js
//= require bootbox.js
//= require popper.js
//= require tippy.umd.js
//= require bootstrap-modal.js
//= require caret_position
//= require itsatrap.js
//= require rsvp.js
//= require uppy.js
//= require buffered-proxy
//= require virtual-dom
//= require virtual-dom-amd
//= require discourse-shims
//= require pretty-text-bundle

View File

@ -1,6 +0,0 @@
//= require set-prototype-polyfill
//= require env
//= require jquery
//= require ember.debug.js
//= require discourse-loader
//= require vendor-common

View File

@ -1,2 +0,0 @@
//= require ember_jquery
//= require vendor-common

View File

@ -1,11 +0,0 @@
// discourse-skip-module
(function (context) {
// register widget helpers for compiled `hbs`
context.__widget_helpers = {
avatar: require("discourse/widgets/post").avatarFor,
dateNode: require("discourse/helpers/node").dateNode,
iconNode: require("discourse-common/lib/icon-library").iconNode,
rawHtml: require("discourse/widgets/raw-html").default,
};
})(this);

View File

@ -1,2 +0,0 @@
//= require discourse/app/lib/export-result
//= require_tree ./wizard/addon

View File

@ -28,16 +28,13 @@ Rails.application.config.assets.precompile += %w{
browser-detect.js
browser-update.js
break_string.js
ember_jquery.js
pretty-text-bundle.js
markdown-it-bundle.js
service-worker.js
google-tag-manager.js
google-universal-analytics-v3.js
google-universal-analytics-v4.js
start-discourse.js
print-page.js
omniauth-complete.js
activate-account.js
auto-redirect.js
locales/i18n.js
@ -46,9 +43,7 @@ Rails.application.config.assets.precompile += %w{
confirm-new-email/bootstrap.js
onpopstate-handler.js
embed-application.js
discourse/tests/active-plugins.js
admin-plugins.js
discourse/tests/test_starter.js
}
if EmberCli.enabled?
@ -60,13 +55,6 @@ if EmberCli.enabled?
scripts/discourse-boot
}
Rails.application.config.assets.precompile += EmberCli::ASSETS.map { |name| name.sub('.js', '.map') }
else
Rails.application.config.assets.precompile += %w{
application.js
discourse/tests/test-support-rails.js
discourse/tests/test-helpers-rails.js
vendor-theme-tests.js
}
end
# Precompile all available locales

View File

@ -96,12 +96,8 @@ def dependencies
}, {
source: '@highlightjs/cdn-assets/.',
destination: 'highlightjs'
}, {
source: 'jquery/dist/jquery.js'
}, {
source: 'markdown-it/dist/markdown-it.js'
}, {
source: '@discourse/itsatrap/itsatrap.js'
}, {
source: 'moment/moment.js'
}, {
@ -143,39 +139,6 @@ def dependencies
destination: 'workbox',
skip_versioning: true,
public: true
}, {
source: '@popperjs/core/dist/umd/popper.js'
}, {
source: '@popperjs/core/dist/umd/popper.js.map',
public_root: true
}, {
source: 'tippy.js/dist/tippy.umd.js'
}, {
source: 'tippy.js/dist/tippy.umd.js.map',
public_root: true
}, {
source: 'tippy.js/dist/tippy.css',
destination: '../../../app/assets/stylesheets/vendor'
}, {
source: 'tippy.js/dist/svg-arrow.css',
destination: '../../../app/assets/stylesheets/vendor'
}, {
source: 'route-recognizer/dist/route-recognizer.js'
}, {
source: 'route-recognizer/dist/route-recognizer.js.map',
public_root: true
},
{
source: 'qunit/qunit/qunit.js'
},
{
source: 'pretender/dist/pretender.js'
},
{
source: 'fake-xml-http-request/fake_xml_http_request.js'
},
{
source: 'sinon/pkg/sinon.js'
},
{
source: 'squoosh/codecs/mozjpeg/enc/mozjpeg_enc.js',
@ -200,10 +163,6 @@ def dependencies
destination: 'squoosh',
public: true,
skip_versioning: true
},
{
source: 'custom-uppy-build.js',
destination: 'uppy.js'
}
]
end
@ -331,13 +290,6 @@ task 'javascript:update' => 'clean_up' do
end
end
# we need a custom build of uppy because we cannot import
# their modules easily, using browserify to do so
if src.include? "custom-uppy-build"
puts "Building custom uppy using browserify"
system("yarn run browserify #{vendor_js}/custom-uppy.js -o node_modules/custom-uppy-build.js")
end
unless File.exist?(dest)
STDERR.puts "New dependency added: #{dest}"
end
@ -347,14 +299,6 @@ task 'javascript:update' => 'clean_up' do
else
FileUtils.cp_r(src, dest)
end
# avoids noisy console warnings in dev environment for non-homepage paths
if dest.end_with? "popper.js"
absolute_sourcemap(dest)
end
if dest.end_with? "tippy.umd.js"
absolute_sourcemap(dest)
end
end
write_template("discourse/app/lib/public-js-versions.js", "update", <<~JS)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,49 +0,0 @@
var Markdown;
if (typeof exports === "object" && typeof require === "function") // we're in a CommonJS (e.g. Node.js) module
Markdown = exports;
else
Markdown = {};
/**
This is only included so we have an interface that Pagedown can use.
**/
(function () {
function identity(x) { return x; }
function returnFalse(x) { return false; }
function HookCollection() { }
HookCollection.prototype = {
chain: function (hookname, func) {
var original = this[hookname];
if (!original)
throw new Error("unknown hook " + hookname);
if (original === identity)
this[hookname] = func;
else
this[hookname] = function (text) {
var args = Array.prototype.slice.call(arguments, 0);
args[0] = original.apply(null, args);
return func.apply(null, args);
};
},
set: function (hookname, func) {
if (!this[hookname])
throw new Error("unknown hook " + hookname);
this[hookname] = func;
},
addNoop: function (hookname) {
this[hookname] = identity;
},
addFalse: function (hookname) {
this[hookname] = returnFalse;
}
};
Markdown.HookCollection = HookCollection;
})();

View File

@ -1,169 +0,0 @@
(function (global) {
"use strict";
function aliasMethod(methodName) {
return function() {
return this[methodName].apply(this, arguments);
};
}
function empty(obj) {
var key;
for (key in obj) if (obj.hasOwnProperty(key)) return false;
return true;
}
var Ember = global.Ember,
get = Ember.get, set = Ember.set,
isArray = Ember.isArray, getProperties = Ember.getProperties,
notifyPropertyChange = Ember.notifyPropertyChange,
meta = Ember.meta, defineProperty = Ember.defineProperty;
var hasOwnProp = Object.prototype.hasOwnProperty;
var BufferedProxyMixin = Ember.Mixin.create({
buffer: null,
hasBufferedChanges: false,
hasChanges: Ember.computed.readOnly('hasBufferedChanges'),
applyChanges: function() {
return this.applyBufferedChanges(...arguments);
},
discardChanges: function() {
return this.discardBufferedChanges(...arguments);
},
init: function() {
this.initializeBuffer();
set(this, 'hasBufferedChanges', false);
this._super(...arguments);
},
initializeBuffer: function(onlyTheseKeys) {
if(isArray(onlyTheseKeys) && !empty(onlyTheseKeys)) {
onlyTheseKeys.forEach((key) => delete this.buffer[key]);
}
else {
set(this, 'buffer', Object.create(null));
}
},
unknownProperty: function(key) {
var buffer = get(this, 'buffer');
return (hasOwnProp.call(buffer, key)) ? buffer[key] : this._super(key);
},
setUnknownProperty: function(key, value) {
var m = meta(this);
if (m.proto === this || (m.isInitializing && m.isInitializing())) {
defineProperty(this, key, null, value);
return value;
}
var props = getProperties(this, ['buffer', 'content']),
buffer = props.buffer,
content = props.content,
current,
previous;
if (content != null) {
current = get(content, key);
}
previous = hasOwnProp.call(buffer, key) ? buffer[key] : current;
if (previous === value) {
return;
}
if (current === value) {
delete buffer[key];
if (empty(buffer)) {
set(this, 'hasBufferedChanges', false);
}
} else {
buffer[key] = value;
set(this, 'hasBufferedChanges', true);
}
notifyPropertyChange(content, key);
return value;
},
applyBufferedChanges: function(onlyTheseKeys) {
var props = getProperties(this, ['buffer', 'content']),
buffer = props.buffer,
content = props.content,
key;
Object.keys(buffer).forEach((key) => {
if (isArray(onlyTheseKeys) && onlyTheseKeys.indexOf(key) === -1) {
return;
}
set(content, key, buffer[key]);
});
this.initializeBuffer(onlyTheseKeys);
if (empty(get(this, 'buffer'))) {
set(this, 'hasBufferedChanges', false);
}
},
discardBufferedChanges: function(onlyTheseKeys) {
var props = getProperties(this, ['buffer', 'content']),
buffer = props.buffer,
content = props.content,
key;
this.initializeBuffer(onlyTheseKeys);
Object.keys(buffer).forEach((key) => {
if (isArray(onlyTheseKeys) && onlyTheseKeys.indexOf(key) === -1) {
return;
}
notifyPropertyChange(content, key);
});
if (empty(get(this, 'buffer'))) {
set(this, 'hasBufferedChanges', false);
}
},
hasChanged: function(key) {
var props = getProperties(this, ['buffer', 'content']),
buffer = props.buffer,
content = props.content,
key;
if (typeof key !== 'string' || typeof get(buffer, key) === 'undefined') {
return false;
}
if (get(buffer, key) !== get(content, key)) {
return true;
}
return false;
}
});
var BufferedProxy = Ember.ObjectProxy.extend(BufferedProxyMixin);
// CommonJS module
if (typeof module !== 'undefined' && module.exports) {
module.exports = BufferedProxy;
} else if (typeof define === "function" && define.amd) {
define("ember-buffered-proxy/proxy", function (require, exports, module) {
return BufferedProxy;
});
} else {
global.BufferedProxy = BufferedProxy;
}
}(this));

View File

@ -1,16 +0,0 @@
// We need a custom build of Uppy because we do not use webpack for
// our JS modules/build. The only way to get what you want from Uppy
// is to use the webpack modules or to include the entire Uppy project
// including all plugins in a single JS file. This way we can just
// use the plugins we actually want.
window.Uppy = {}
Uppy.Core = require('@uppy/core')
Uppy.XHRUpload = require('@uppy/xhr-upload')
Uppy.AwsS3 = require('@uppy/aws-s3')
Uppy.AwsS3Multipart = require('@uppy/aws-s3-multipart')
Uppy.DropTarget = require('@uppy/drop-target')
Uppy.Utils = {
delay: require('@uppy/utils/lib/delay'),
EventTracker: require('@uppy/utils/lib/EventTracker'),
AbortControllerLib: require('@uppy/utils/lib/AbortController')
}

File diff suppressed because it is too large Load Diff

View File

@ -1,530 +0,0 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.FakeXMLHttpRequest = factory());
}(this, (function () { 'use strict';
/**
* Minimal Event interface implementation
*
* Original implementation by Sven Fuchs: https://gist.github.com/995028
* Modifications and tests by Christian Johansen.
*
* @author Sven Fuchs (svenfuchs@artweb-design.de)
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2011 Sven Fuchs, Christian Johansen
*/
var _Event = function Event(type, bubbles, cancelable, target) {
this.type = type;
this.bubbles = bubbles;
this.cancelable = cancelable;
this.target = target;
};
_Event.prototype = {
stopPropagation: function () {},
preventDefault: function () {
this.defaultPrevented = true;
}
};
/*
Used to set the statusText property of an xhr object
*/
var httpStatusCodes = {
100: "Continue",
101: "Switching Protocols",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
300: "Multiple Choice",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Request Entity Too Large",
414: "Request-URI Too Long",
415: "Unsupported Media Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
422: "Unprocessable Entity",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported"
};
/*
Cross-browser XML parsing. Used to turn
XML responses into Document objects
Borrowed from JSpec
*/
function parseXML(text) {
var xmlDoc;
if (typeof DOMParser != "undefined") {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
} else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(text);
}
return xmlDoc;
}
/*
Without mocking, the native XMLHttpRequest object will throw
an error when attempting to set these headers. We match this behavior.
*/
var unsafeHeaders = {
"Accept-Charset": true,
"Accept-Encoding": true,
"Connection": true,
"Content-Length": true,
"Cookie": true,
"Cookie2": true,
"Content-Transfer-Encoding": true,
"Date": true,
"Expect": true,
"Host": true,
"Keep-Alive": true,
"Referer": true,
"TE": true,
"Trailer": true,
"Transfer-Encoding": true,
"Upgrade": true,
"User-Agent": true,
"Via": true
};
/*
Adds an "event" onto the fake xhr object
that just calls the same-named method. This is
in case a library adds callbacks for these events.
*/
function _addEventListener(eventName, xhr){
xhr.addEventListener(eventName, function (event) {
var listener = xhr["on" + eventName];
if (listener && typeof listener == "function") {
listener.call(event.target, event);
}
});
}
function EventedObject() {
this._eventListeners = {};
var events = ["loadstart", "progress", "load", "abort", "loadend"];
for (var i = events.length - 1; i >= 0; i--) {
_addEventListener(events[i], this);
}
}
EventedObject.prototype = {
/*
Duplicates the behavior of native XMLHttpRequest's addEventListener function
*/
addEventListener: function addEventListener(event, listener) {
this._eventListeners[event] = this._eventListeners[event] || [];
this._eventListeners[event].push(listener);
},
/*
Duplicates the behavior of native XMLHttpRequest's removeEventListener function
*/
removeEventListener: function removeEventListener(event, listener) {
var listeners = this._eventListeners[event] || [];
for (var i = 0, l = listeners.length; i < l; ++i) {
if (listeners[i] == listener) {
return listeners.splice(i, 1);
}
}
},
/*
Duplicates the behavior of native XMLHttpRequest's dispatchEvent function
*/
dispatchEvent: function dispatchEvent(event) {
var type = event.type;
var listeners = this._eventListeners[type] || [];
for (var i = 0; i < listeners.length; i++) {
if (typeof listeners[i] == "function") {
listeners[i].call(this, event);
} else {
listeners[i].handleEvent(event);
}
}
return !!event.defaultPrevented;
},
/*
Triggers an `onprogress` event with the given parameters.
*/
_progress: function _progress(lengthComputable, loaded, total) {
var event = new _Event('progress');
event.target = this;
event.lengthComputable = lengthComputable;
event.loaded = loaded;
event.total = total;
this.dispatchEvent(event);
}
};
/*
Constructor for a fake window.XMLHttpRequest
*/
function FakeXMLHttpRequest() {
EventedObject.call(this);
this.readyState = FakeXMLHttpRequest.UNSENT;
this.requestHeaders = {};
this.requestBody = null;
this.status = 0;
this.statusText = "";
this.upload = new EventedObject();
this.onabort= null;
this.onerror= null;
this.onload= null;
this.onloadend= null;
this.onloadstart= null;
this.onprogress= null;
this.onreadystatechange= null;
this.ontimeout= null;
}
FakeXMLHttpRequest.prototype = new EventedObject();
// These status codes are available on the native XMLHttpRequest
// object, so we match that here in case a library is relying on them.
FakeXMLHttpRequest.UNSENT = 0;
FakeXMLHttpRequest.OPENED = 1;
FakeXMLHttpRequest.HEADERS_RECEIVED = 2;
FakeXMLHttpRequest.LOADING = 3;
FakeXMLHttpRequest.DONE = 4;
var FakeXMLHttpRequestProto = {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4,
async: true,
withCredentials: false,
/*
Duplicates the behavior of native XMLHttpRequest's open function
*/
open: function open(method, url, async, username, password) {
this.method = method;
this.url = url;
this.async = typeof async == "boolean" ? async : true;
this.username = username;
this.password = password;
this.responseText = null;
this.response = this.responseText;
this.responseXML = null;
this.responseURL = url;
this.requestHeaders = {};
this.sendFlag = false;
this._readyStateChange(FakeXMLHttpRequest.OPENED);
},
/*
Duplicates the behavior of native XMLHttpRequest's setRequestHeader function
*/
setRequestHeader: function setRequestHeader(header, value) {
verifyState(this);
if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
throw new Error("Refused to set unsafe header \"" + header + "\"");
}
if (this.requestHeaders[header]) {
this.requestHeaders[header] += "," + value;
} else {
this.requestHeaders[header] = value;
}
},
/*
Duplicates the behavior of native XMLHttpRequest's send function
*/
send: function send(data) {
verifyState(this);
if (!/^(get|head)$/i.test(this.method)) {
var hasContentTypeHeader = false;
Object.keys(this.requestHeaders).forEach(function (key) {
if (key.toLowerCase() === 'content-type') {
hasContentTypeHeader = true;
}
});
if (!hasContentTypeHeader && !(data || '').toString().match('FormData')) {
this.requestHeaders["Content-Type"] = "text/plain;charset=UTF-8";
}
this.requestBody = data;
}
this.errorFlag = false;
this.sendFlag = this.async;
this._readyStateChange(FakeXMLHttpRequest.OPENED);
if (typeof this.onSend == "function") {
this.onSend(this);
}
this.dispatchEvent(new _Event("loadstart", false, false, this));
},
/*
Duplicates the behavior of native XMLHttpRequest's abort function
*/
abort: function abort() {
this.aborted = true;
this.responseText = null;
this.response = this.responseText;
this.errorFlag = true;
this.requestHeaders = {};
this.dispatchEvent(new _Event("abort", false, false, this));
if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) {
this._readyStateChange(FakeXMLHttpRequest.UNSENT);
this.sendFlag = false;
}
if (typeof this.onerror === "function") {
this.onerror();
}
},
/*
Duplicates the behavior of native XMLHttpRequest's getResponseHeader function
*/
getResponseHeader: function getResponseHeader(header) {
if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
return null;
}
if (/^Set-Cookie2?$/i.test(header)) {
return null;
}
header = header.toLowerCase();
for (var h in this.responseHeaders) {
if (h.toLowerCase() == header) {
return this.responseHeaders[h];
}
}
return null;
},
/*
Duplicates the behavior of native XMLHttpRequest's getAllResponseHeaders function
*/
getAllResponseHeaders: function getAllResponseHeaders() {
if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
return "";
}
var headers = "";
for (var header in this.responseHeaders) {
if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) {
headers += header + ": " + this.responseHeaders[header] + "\r\n";
}
}
return headers;
},
/*
Duplicates the behavior of native XMLHttpRequest's overrideMimeType function
*/
overrideMimeType: function overrideMimeType(mimeType) {
if (typeof mimeType === "string") {
this.forceMimeType = mimeType.toLowerCase();
}
},
/*
Places a FakeXMLHttpRequest object into the passed
state.
*/
_readyStateChange: function _readyStateChange(state) {
this.readyState = state;
if (typeof this.onreadystatechange == "function") {
this.onreadystatechange(new _Event("readystatechange"));
}
this.dispatchEvent(new _Event("readystatechange"));
if (this.readyState == FakeXMLHttpRequest.DONE) {
this.dispatchEvent(new _Event("load", false, false, this));
}
if (this.readyState == FakeXMLHttpRequest.UNSENT || this.readyState == FakeXMLHttpRequest.DONE) {
this.dispatchEvent(new _Event("loadend", false, false, this));
}
},
/*
Sets the FakeXMLHttpRequest object's response headers and
places the object into readyState 2
*/
_setResponseHeaders: function _setResponseHeaders(headers) {
this.responseHeaders = {};
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
this.responseHeaders[header] = headers[header];
}
}
if (this.forceMimeType) {
this.responseHeaders['Content-Type'] = this.forceMimeType;
}
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
} else {
this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
}
},
/*
Sets the FakeXMLHttpRequest object's response body and
if body text is XML, sets responseXML to parsed document
object
*/
_setResponseBody: function _setResponseBody(body) {
verifyRequestSent(this);
verifyHeadersReceived(this);
verifyResponseBodyType(body);
var chunkSize = this.chunkSize || 10;
var index = 0;
this.responseText = "";
this.response = this.responseText;
do {
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.LOADING);
}
this.responseText += body.substring(index, index + chunkSize);
this.response = this.responseText;
index += chunkSize;
} while (index < body.length);
var type = this.getResponseHeader("Content-Type");
if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
try {
this.responseXML = parseXML(this.responseText);
} catch (e) {
// Unable to parse XML - no biggie
}
}
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.DONE);
} else {
this.readyState = FakeXMLHttpRequest.DONE;
}
},
/*
Forces a response on to the FakeXMLHttpRequest object.
This is the public API for faking responses. This function
takes a number status, headers object, and string body:
```
xhr.respond(404, {Content-Type: 'text/plain'}, "Sorry. This object was not found.")
```
*/
respond: function respond(status, headers, body) {
this._setResponseHeaders(headers || {});
this.status = typeof status == "number" ? status : 200;
this.statusText = httpStatusCodes[this.status];
this._setResponseBody(body || "");
}
};
for (var property in FakeXMLHttpRequestProto) {
FakeXMLHttpRequest.prototype[property] = FakeXMLHttpRequestProto[property];
}
function verifyState(xhr) {
if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
throw new Error("INVALID_STATE_ERR");
}
if (xhr.sendFlag) {
throw new Error("INVALID_STATE_ERR");
}
}
function verifyRequestSent(xhr) {
if (xhr.readyState == FakeXMLHttpRequest.DONE) {
throw new Error("Request done");
}
}
function verifyHeadersReceived(xhr) {
if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
throw new Error("No headers received");
}
}
function verifyResponseBodyType(body) {
if (typeof body != "string") {
var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
body + ", which is not a string.");
error.name = "InvalidBodyException";
throw error;
}
}
return FakeXMLHttpRequest;
})));
//# sourceMappingURL=fake_xml_http_request.js.map

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,693 +0,0 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define('route-recognizer', factory) :
(global.RouteRecognizer = factory());
}(this, (function () { 'use strict';
var createObject = Object.create;
function createMap() {
var map = createObject(null);
map["__"] = undefined;
delete map["__"];
return map;
}
var Target = function Target(path, matcher, delegate) {
this.path = path;
this.matcher = matcher;
this.delegate = delegate;
};
Target.prototype.to = function to (target, callback) {
var delegate = this.delegate;
if (delegate && delegate.willAddRoute) {
target = delegate.willAddRoute(this.matcher.target, target);
}
this.matcher.add(this.path, target);
if (callback) {
if (callback.length === 0) {
throw new Error("You must have an argument in the function passed to `to`");
}
this.matcher.addChild(this.path, target, callback, this.delegate);
}
};
var Matcher = function Matcher(target) {
this.routes = createMap();
this.children = createMap();
this.target = target;
};
Matcher.prototype.add = function add (path, target) {
this.routes[path] = target;
};
Matcher.prototype.addChild = function addChild (path, target, callback, delegate) {
var matcher = new Matcher(target);
this.children[path] = matcher;
var match = generateMatch(path, matcher, delegate);
if (delegate && delegate.contextEntered) {
delegate.contextEntered(target, match);
}
callback(match);
};
function generateMatch(startingPath, matcher, delegate) {
function match(path, callback) {
var fullPath = startingPath + path;
if (callback) {
callback(generateMatch(fullPath, matcher, delegate));
}
else {
return new Target(fullPath, matcher, delegate);
}
}
return match;
}
function addRoute(routeArray, path, handler) {
var len = 0;
for (var i = 0; i < routeArray.length; i++) {
len += routeArray[i].path.length;
}
path = path.substr(len);
var route = { path: path, handler: handler };
routeArray.push(route);
}
function eachRoute(baseRoute, matcher, callback, binding) {
var routes = matcher.routes;
var paths = Object.keys(routes);
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
var routeArray = baseRoute.slice();
addRoute(routeArray, path, routes[path]);
var nested = matcher.children[path];
if (nested) {
eachRoute(routeArray, nested, callback, binding);
}
else {
callback.call(binding, routeArray);
}
}
}
var map = function (callback, addRouteCallback) {
var matcher = new Matcher();
callback(generateMatch("", matcher, this.delegate));
eachRoute([], matcher, function (routes) {
if (addRouteCallback) {
addRouteCallback(this, routes);
}
else {
this.add(routes);
}
}, this);
};
// Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
// values that are not reserved (i.e., unicode characters, emoji, etc). The reserved
// chars are "/" and "%".
// Safe to call multiple times on the same path.
// Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
function normalizePath(path) {
return path.split("/")
.map(normalizeSegment)
.join("/");
}
// We want to ensure the characters "%" and "/" remain in percent-encoded
// form when normalizing paths, so replace them with their encoded form after
// decoding the rest of the path
var SEGMENT_RESERVED_CHARS = /%|\//g;
function normalizeSegment(segment) {
if (segment.length < 3 || segment.indexOf("%") === -1)
{ return segment; }
return decodeURIComponent(segment).replace(SEGMENT_RESERVED_CHARS, encodeURIComponent);
}
// We do not want to encode these characters when generating dynamic path segments
// See https://tools.ietf.org/html/rfc3986#section-3.3
// sub-delims: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
// others allowed by RFC 3986: ":", "@"
//
// First encode the entire path segment, then decode any of the encoded special chars.
//
// The chars "!", "'", "(", ")", "*" do not get changed by `encodeURIComponent`,
// so the possible encoded chars are:
// ['%24', '%26', '%2B', '%2C', '%3B', '%3D', '%3A', '%40'].
var PATH_SEGMENT_ENCODINGS = /%(?:2(?:4|6|B|C)|3(?:B|D|A)|40)/g;
function encodePathSegment(str) {
return encodeURIComponent(str).replace(PATH_SEGMENT_ENCODINGS, decodeURIComponent);
}
var escapeRegex = /(\/|\.|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g;
var isArray = Array.isArray;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function getParam(params, key) {
if (typeof params !== "object" || params === null) {
throw new Error("You must pass an object as the second argument to `generate`.");
}
if (!hasOwnProperty.call(params, key)) {
throw new Error("You must provide param `" + key + "` to `generate`.");
}
var value = params[key];
var str = typeof value === "string" ? value : "" + value;
if (str.length === 0) {
throw new Error("You must provide a param `" + key + "`.");
}
return str;
}
var eachChar = [];
eachChar[0 /* Static */] = function (segment, currentState) {
var state = currentState;
var value = segment.value;
for (var i = 0; i < value.length; i++) {
var ch = value.charCodeAt(i);
state = state.put(ch, false, false);
}
return state;
};
eachChar[1 /* Dynamic */] = function (_, currentState) {
return currentState.put(47 /* SLASH */, true, true);
};
eachChar[2 /* Star */] = function (_, currentState) {
return currentState.put(-1 /* ANY */, false, true);
};
eachChar[4 /* Epsilon */] = function (_, currentState) {
return currentState;
};
var regex = [];
regex[0 /* Static */] = function (segment) {
return segment.value.replace(escapeRegex, "\\$1");
};
regex[1 /* Dynamic */] = function () {
return "([^/]+)";
};
regex[2 /* Star */] = function () {
return "(.+)";
};
regex[4 /* Epsilon */] = function () {
return "";
};
var generate = [];
generate[0 /* Static */] = function (segment) {
return segment.value;
};
generate[1 /* Dynamic */] = function (segment, params) {
var value = getParam(params, segment.value);
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
return encodePathSegment(value);
}
else {
return value;
}
};
generate[2 /* Star */] = function (segment, params) {
return getParam(params, segment.value);
};
generate[4 /* Epsilon */] = function () {
return "";
};
var EmptyObject = Object.freeze({});
var EmptyArray = Object.freeze([]);
// The `names` will be populated with the paramter name for each dynamic/star
// segment. `shouldDecodes` will be populated with a boolean for each dyanamic/star
// segment, indicating whether it should be decoded during recognition.
function parse(segments, route, types) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.length > 0 && route.charCodeAt(0) === 47 /* SLASH */) {
route = route.substr(1);
}
var parts = route.split("/");
var names = undefined;
var shouldDecodes = undefined;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
var flags = 0;
var type = 0;
if (part === "") {
type = 4 /* Epsilon */;
}
else if (part.charCodeAt(0) === 58 /* COLON */) {
type = 1 /* Dynamic */;
}
else if (part.charCodeAt(0) === 42 /* STAR */) {
type = 2 /* Star */;
}
else {
type = 0 /* Static */;
}
flags = 2 << type;
if (flags & 12 /* Named */) {
part = part.slice(1);
names = names || [];
names.push(part);
shouldDecodes = shouldDecodes || [];
shouldDecodes.push((flags & 4 /* Decoded */) !== 0);
}
if (flags & 14 /* Counted */) {
types[type]++;
}
segments.push({
type: type,
value: normalizeSegment(part)
});
}
return {
names: names || EmptyArray,
shouldDecodes: shouldDecodes || EmptyArray,
};
}
function isEqualCharSpec(spec, char, negate) {
return spec.char === char && spec.negate === negate;
}
// A State has a character specification and (`charSpec`) and a list of possible
// subsequent states (`nextStates`).
//
// If a State is an accepting state, it will also have several additional
// properties:
//
// * `regex`: A regular expression that is used to extract parameters from paths
// that reached this accepting state.
// * `handlers`: Information on how to convert the list of captures into calls
// to registered handlers with the specified parameters
// * `types`: How many static, dynamic or star segments in this route. Used to
// decide which route to use if multiple registered routes match a path.
//
// Currently, State is implemented naively by looping over `nextStates` and
// comparing a character specification against a character. A more efficient
// implementation would use a hash of keys pointing at one or more next states.
var State = function State(states, id, char, negate, repeat) {
this.states = states;
this.id = id;
this.char = char;
this.negate = negate;
this.nextStates = repeat ? id : null;
this.pattern = "";
this._regex = undefined;
this.handlers = undefined;
this.types = undefined;
};
State.prototype.regex = function regex$1 () {
if (!this._regex) {
this._regex = new RegExp(this.pattern);
}
return this._regex;
};
State.prototype.get = function get (char, negate) {
var this$1 = this;
var nextStates = this.nextStates;
if (nextStates === null)
{ return; }
if (isArray(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1.states[nextStates[i]];
if (isEqualCharSpec(child, char, negate)) {
return child;
}
}
}
else {
var child$1 = this.states[nextStates];
if (isEqualCharSpec(child$1, char, negate)) {
return child$1;
}
}
};
State.prototype.put = function put (char, negate, repeat) {
var state;
// If the character specification already exists in a child of the current
// state, just return that state.
if (state = this.get(char, negate)) {
return state;
}
// Make a new state for the character spec
var states = this.states;
state = new State(states, states.length, char, negate, repeat);
states[states.length] = state;
// Insert the new state as a child of the current state
if (this.nextStates == null) {
this.nextStates = state.id;
}
else if (isArray(this.nextStates)) {
this.nextStates.push(state.id);
}
else {
this.nextStates = [this.nextStates, state.id];
}
// Return the new state
return state;
};
// Find a list of child states matching the next character
State.prototype.match = function match (ch) {
var this$1 = this;
var nextStates = this.nextStates;
if (!nextStates)
{ return []; }
var returned = [];
if (isArray(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1.states[nextStates[i]];
if (isMatch(child, ch)) {
returned.push(child);
}
}
}
else {
var child$1 = this.states[nextStates];
if (isMatch(child$1, ch)) {
returned.push(child$1);
}
}
return returned;
};
function isMatch(spec, char) {
return spec.negate ? spec.char !== char && spec.char !== -1 /* ANY */ : spec.char === char || spec.char === -1 /* ANY */;
}
// This is a somewhat naive strategy, but should work in a lot of cases
// A better strategy would properly resolve /posts/:id/new and /posts/edit/:id.
//
// This strategy generally prefers more static and less dynamic matching.
// Specifically, it
//
// * prefers fewer stars to more, then
// * prefers using stars for less of the match to more, then
// * prefers fewer dynamic segments to more, then
// * prefers more static segments to more
function sortSolutions(states) {
return states.sort(function (a, b) {
var ref = a.types || [0, 0, 0];
var astatics = ref[0];
var adynamics = ref[1];
var astars = ref[2];
var ref$1 = b.types || [0, 0, 0];
var bstatics = ref$1[0];
var bdynamics = ref$1[1];
var bstars = ref$1[2];
if (astars !== bstars) {
return astars - bstars;
}
if (astars) {
if (astatics !== bstatics) {
return bstatics - astatics;
}
if (adynamics !== bdynamics) {
return bdynamics - adynamics;
}
}
if (adynamics !== bdynamics) {
return adynamics - bdynamics;
}
if (astatics !== bstatics) {
return bstatics - astatics;
}
return 0;
});
}
function recognizeChar(states, ch) {
var nextStates = [];
for (var i = 0, l = states.length; i < l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
var RecognizeResults = function RecognizeResults(queryParams) {
this.length = 0;
this.queryParams = queryParams || {};
};
RecognizeResults.prototype.splice = Array.prototype.splice;
RecognizeResults.prototype.slice = Array.prototype.slice;
RecognizeResults.prototype.push = Array.prototype.push;
function findHandler(state, originalPath, queryParams) {
var handlers = state.handlers;
var regex = state.regex();
if (!regex || !handlers)
{ throw new Error("state not initialized"); }
var captures = originalPath.match(regex);
var currentCapture = 1;
var result = new RecognizeResults(queryParams);
result.length = handlers.length;
for (var i = 0; i < handlers.length; i++) {
var handler = handlers[i];
var names = handler.names;
var shouldDecodes = handler.shouldDecodes;
var params = EmptyObject;
var isDynamic = false;
if (names !== EmptyArray && shouldDecodes !== EmptyArray) {
for (var j = 0; j < names.length; j++) {
isDynamic = true;
var name = names[j];
var capture = captures && captures[currentCapture++];
if (params === EmptyObject) {
params = {};
}
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS && shouldDecodes[j]) {
params[name] = capture && decodeURIComponent(capture);
}
else {
params[name] = capture;
}
}
}
result[i] = {
handler: handler.handler,
params: params,
isDynamic: isDynamic
};
}
return result;
}
function decodeQueryParamPart(part) {
// http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
part = part.replace(/\+/gm, "%20");
var result;
try {
result = decodeURIComponent(part);
}
catch (error) {
result = "";
}
return result;
}
var RouteRecognizer = function RouteRecognizer() {
this.names = createMap();
var states = [];
var state = new State(states, 0, -1 /* ANY */, true, false);
states[0] = state;
this.states = states;
this.rootState = state;
};
RouteRecognizer.prototype.add = function add (routes, options) {
var currentState = this.rootState;
var pattern = "^";
var types = [0, 0, 0];
var handlers = new Array(routes.length);
var allSegments = [];
var isEmpty = true;
var j = 0;
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = parse(allSegments, route.path, types);
var names = ref.names;
var shouldDecodes = ref.shouldDecodes;
// preserve j so it points to the start of newly added segments
for (; j < allSegments.length; j++) {
var segment = allSegments[j];
if (segment.type === 4 /* Epsilon */) {
continue;
}
isEmpty = false;
// Add a "/" for the new segment
currentState = currentState.put(47 /* SLASH */, false, false);
pattern += "/";
// Add a representation of the segment to the NFA and regex
currentState = eachChar[segment.type](segment, currentState);
pattern += regex[segment.type](segment);
}
handlers[i] = {
handler: route.handler,
names: names,
shouldDecodes: shouldDecodes
};
}
if (isEmpty) {
currentState = currentState.put(47 /* SLASH */, false, false);
pattern += "/";
}
currentState.handlers = handlers;
currentState.pattern = pattern + "$";
currentState.types = types;
var name;
if (typeof options === "object" && options !== null && options.as) {
name = options.as;
}
if (name) {
// if (this.names[name]) {
// throw new Error("You may not add a duplicate route named `" + name + "`.");
// }
this.names[name] = {
segments: allSegments,
handlers: handlers
};
}
};
RouteRecognizer.prototype.handlersFor = function handlersFor (name) {
var route = this.names[name];
if (!route) {
throw new Error("There is no route named " + name);
}
var result = new Array(route.handlers.length);
for (var i = 0; i < route.handlers.length; i++) {
var handler = route.handlers[i];
result[i] = handler;
}
return result;
};
RouteRecognizer.prototype.hasRoute = function hasRoute (name) {
return !!this.names[name];
};
RouteRecognizer.prototype.generate = function generate$1 (name, params) {
var route = this.names[name];
var output = "";
if (!route) {
throw new Error("There is no route named " + name);
}
var segments = route.segments;
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (segment.type === 4 /* Epsilon */) {
continue;
}
output += "/";
output += generate[segment.type](segment, params);
}
if (output.charAt(0) !== "/") {
output = "/" + output;
}
if (params && params.queryParams) {
output += this.generateQueryString(params.queryParams);
}
return output;
};
RouteRecognizer.prototype.generateQueryString = function generateQueryString (params) {
var pairs = [];
var keys = Object.keys(params);
keys.sort();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = params[key];
if (value == null) {
continue;
}
var pair = encodeURIComponent(key);
if (isArray(value)) {
for (var j = 0; j < value.length; j++) {
var arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
}
else {
pair += "=" + encodeURIComponent(value);
pairs.push(pair);
}
}
if (pairs.length === 0) {
return "";
}
return "?" + pairs.join("&");
};
RouteRecognizer.prototype.parseQueryString = function parseQueryString (queryString) {
var pairs = queryString.split("&");
var queryParams = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("="), key = decodeQueryParamPart(pair[0]), keyLength = key.length, isArray = false, value = (void 0);
if (pair.length === 1) {
value = "true";
}
else {
// Handle arrays
if (keyLength > 2 && key.slice(keyLength - 2) === "[]") {
isArray = true;
key = key.slice(0, keyLength - 2);
if (!queryParams[key]) {
queryParams[key] = [];
}
}
value = pair[1] ? decodeQueryParamPart(pair[1]) : "";
}
if (isArray) {
queryParams[key].push(value);
}
else {
queryParams[key] = value;
}
}
return queryParams;
};
RouteRecognizer.prototype.recognize = function recognize (path) {
var results;
var states = [this.rootState];
var queryParams = {};
var isSlashDropped = false;
var hashStart = path.indexOf("#");
if (hashStart !== -1) {
path = path.substr(0, hashStart);
}
var queryStart = path.indexOf("?");
if (queryStart !== -1) {
var queryString = path.substr(queryStart + 1, path.length);
path = path.substr(0, queryStart);
queryParams = this.parseQueryString(queryString);
}
if (path.charAt(0) !== "/") {
path = "/" + path;
}
var originalPath = path;
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
path = normalizePath(path);
}
else {
path = decodeURI(path);
originalPath = decodeURI(originalPath);
}
var pathLen = path.length;
if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
path = path.substr(0, pathLen - 1);
originalPath = originalPath.substr(0, originalPath.length - 1);
isSlashDropped = true;
}
for (var i = 0; i < path.length; i++) {
states = recognizeChar(states, path.charCodeAt(i));
if (!states.length) {
break;
}
}
var solutions = [];
for (var i$1 = 0; i$1 < states.length; i$1++) {
if (states[i$1].handlers) {
solutions.push(states[i$1]);
}
}
states = sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
// if a trailing slash was dropped and a star segment is the last segment
// specified, put the trailing slash back
if (isSlashDropped && state.pattern && state.pattern.slice(-5) === "(.+)$") {
originalPath = originalPath + "/";
}
results = findHandler(state, originalPath, queryParams);
}
return results;
};
RouteRecognizer.VERSION = "0.3.4";
// Set to false to opt-out of encoding and decoding path segments.
// See https://github.com/tildeio/route-recognizer/pull/55
RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS = true;
RouteRecognizer.Normalizer = {
normalizeSegment: normalizeSegment, normalizePath: normalizePath, encodePathSegment: encodePathSegment
};
RouteRecognizer.prototype.map = map;
return RouteRecognizer;
})));
//# sourceMappingURL=route-recognizer.js.map

View File

@ -1,289 +0,0 @@
(function(exports) {
"use strict";
var config = {};
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var MutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var RSVP;
if (typeof process !== 'undefined' &&
{}.toString.call(process) === '[object process]') {
config.async = function(callback, binding) {
process.nextTick(function() {
callback.call(binding);
});
};
} else if (MutationObserver) {
var queue = [];
var observer = new MutationObserver(function() {
var toProcess = queue.slice();
queue = [];
toProcess.forEach(function(tuple) {
var callback = tuple[0], binding = tuple[1];
callback.call(binding);
});
});
var element = document.createElement('div');
observer.observe(element, { attributes: true });
// Chrome Memory Leak: https://bugs.webkit.org/show_bug.cgi?id=93661
window.addEventListener('unload', function(){
observer.disconnect();
observer = null;
});
config.async = function(callback, binding) {
queue.push([callback, binding]);
element.setAttribute('drainQueue', 'drainQueue');
};
} else {
config.async = function(callback, binding) {
setTimeout(function() {
callback.call(binding);
}, 1);
};
}
var Event = function(type, options) {
this.type = type;
for (var option in options) {
if (!options.hasOwnProperty(option)) { continue; }
this[option] = options[option];
}
};
var indexOf = function(callbacks, callback) {
for (var i=0, l=callbacks.length; i<l; i++) {
if (callbacks[i][0] === callback) { return i; }
}
return -1;
};
var callbacksFor = function(object) {
var callbacks = object._promiseCallbacks;
if (!callbacks) {
callbacks = object._promiseCallbacks = {};
}
return callbacks;
};
var EventTarget = {
mixin: function(object) {
object.on = this.on;
object.off = this.off;
object.trigger = this.trigger;
return object;
},
on: function(eventNames, callback, binding) {
var allCallbacks = callbacksFor(this), callbacks, eventName;
eventNames = eventNames.split(/\s+/);
binding = binding || this;
while (eventName = eventNames.shift()) {
callbacks = allCallbacks[eventName];
if (!callbacks) {
callbacks = allCallbacks[eventName] = [];
}
if (indexOf(callbacks, callback) === -1) {
callbacks.push([callback, binding]);
}
}
},
off: function(eventNames, callback) {
var allCallbacks = callbacksFor(this), callbacks, eventName, index;
eventNames = eventNames.split(/\s+/);
while (eventName = eventNames.shift()) {
if (!callback) {
allCallbacks[eventName] = [];
continue;
}
callbacks = allCallbacks[eventName];
index = indexOf(callbacks, callback);
if (index !== -1) { callbacks.splice(index, 1); }
}
},
trigger: function(eventName, options) {
var allCallbacks = callbacksFor(this),
callbacks, callbackTuple, callback, binding, event;
if (callbacks = allCallbacks[eventName]) {
for (var i=0, l=callbacks.length; i<l; i++) {
callbackTuple = callbacks[i];
callback = callbackTuple[0];
binding = callbackTuple[1];
if (typeof options !== 'object') {
options = { detail: options };
}
event = new Event(eventName, options);
callback.call(binding, event);
}
}
}
};
var Promise = function() {
this.on('promise:resolved', function(event) {
this.trigger('success', { detail: event.detail });
}, this);
this.on('promise:failed', function(event) {
this.trigger('error', { detail: event.detail });
}, this);
};
var noop = function() {};
var invokeCallback = function(type, promise, callback, event) {
var hasCallback = typeof callback === 'function',
value, error, succeeded, failed;
if (hasCallback) {
try {
value = callback(event.detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = event.detail;
succeeded = true;
}
if (value && typeof value.then === 'function') {
value.then(function(value) {
promise.resolve(value);
}, function(error) {
promise.reject(error);
});
} else if (hasCallback && succeeded) {
promise.resolve(value);
} else if (failed) {
promise.reject(error);
} else {
promise[type](value);
}
};
Promise.prototype = {
then: function(done, fail) {
var thenPromise = new Promise();
if (this.isResolved) {
config.async(function() {
invokeCallback('resolve', thenPromise, done, { detail: this.resolvedValue });
}, this);
}
if (this.isRejected) {
config.async(function() {
invokeCallback('reject', thenPromise, fail, { detail: this.rejectedValue });
}, this);
}
this.on('promise:resolved', function(event) {
invokeCallback('resolve', thenPromise, done, event);
});
this.on('promise:failed', function(event) {
invokeCallback('reject', thenPromise, fail, event);
});
return thenPromise;
},
resolve: function(value) {
resolve(this, value);
this.resolve = noop;
this.reject = noop;
},
reject: function(value) {
reject(this, value);
this.resolve = noop;
this.reject = noop;
}
};
function resolve(promise, value) {
config.async(function() {
promise.trigger('promise:resolved', { detail: value });
promise.isResolved = true;
promise.resolvedValue = value;
});
}
function reject(promise, value) {
config.async(function() {
promise.trigger('promise:failed', { detail: value });
promise.isRejected = true;
promise.rejectedValue = value;
});
}
function all(promises) {
var i, results = [];
var allPromise = new Promise();
var remaining = promises.length;
if (remaining === 0) {
allPromise.resolve([]);
}
var resolver = function(index) {
return function(value) {
resolve(index, value);
};
};
var resolve = function(index, value) {
results[index] = value;
if (--remaining === 0) {
allPromise.resolve(results);
}
};
var reject = function(error) {
allPromise.reject(error);
};
for (i = 0; i < remaining; i++) {
promises[i].then(resolver(i), reject);
}
return allPromise;
}
EventTarget.mixin(Promise.prototype);
function configure(name, value) {
config[name] = value;
}
exports.Promise = Promise;
exports.Event = Event;
exports.EventTarget = EventTarget;
exports.all = all;
exports.configure = configure;
})(window.RSVP = {});

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,4 +0,0 @@
// Just a wrapper from the standalone browserified virtual-dom
define("virtual-dom", [], function() {
return virtualDom;
});

File diff suppressed because it is too large Load Diff