From 16f0c94dcb963a8db15685d4c1f5f77b62a4ce0c Mon Sep 17 00:00:00 2001 From: Robert Waggott Date: Tue, 4 Sep 2018 20:34:45 +0100 Subject: [PATCH 01/76] -- adding aurelia skeleton --- content/app/.babelrc | 5 + content/app/.babelrc.js | 27 ++++ content/app/.editorconfig | 12 ++ content/app/.eslintrc.json | 3 + content/app/.gitignore | 31 +++++ content/app/.vscode/extensions.json | 10 ++ content/app/.vscode/launch.json | 19 +++ content/app/.vscode/settings.json | 6 + content/app/aurelia_project/aurelia.json | 78 ++++++++++++ .../app/aurelia_project/environments/dev.js | 4 + .../app/aurelia_project/environments/prod.js | 4 + .../app/aurelia_project/environments/stage.js | 4 + .../aurelia_project/generators/attribute.js | 44 +++++++ .../aurelia_project/generators/attribute.json | 4 + .../generators/binding-behavior.js | 41 ++++++ .../generators/binding-behavior.json | 4 + .../aurelia_project/generators/component.js | 51 ++++++++ .../aurelia_project/generators/component.json | 4 + .../app/aurelia_project/generators/element.js | 48 +++++++ .../aurelia_project/generators/element.json | 4 + .../aurelia_project/generators/generator.js | 73 +++++++++++ .../aurelia_project/generators/generator.json | 4 + .../app/aurelia_project/generators/task.js | 41 ++++++ .../app/aurelia_project/generators/task.json | 4 + .../generators/value-converter.js | 41 ++++++ .../generators/value-converter.json | 4 + content/app/aurelia_project/tasks/build.js | 58 +++++++++ content/app/aurelia_project/tasks/build.json | 16 +++ .../app/aurelia_project/tasks/environment.js | 24 ++++ content/app/aurelia_project/tasks/jest.js | 23 ++++ content/app/aurelia_project/tasks/jest.json | 11 ++ content/app/aurelia_project/tasks/karma.js | 16 +++ content/app/aurelia_project/tasks/karma.json | 11 ++ content/app/aurelia_project/tasks/run.js | 46 +++++++ content/app/aurelia_project/tasks/run.json | 21 ++++ content/app/favicon.ico | Bin 0 -> 15086 bytes content/app/index.ejs | 16 +++ content/app/jsconfig.json | 11 ++ content/app/package-scripts.js | 79 ++++++++++++ content/app/package.json | 119 ++++++++++++++++++ content/app/src/app.html | 7 ++ content/app/src/app.js | 16 +++ content/app/src/environment.js | 4 + content/app/src/main.js | 30 +++++ content/app/src/resources/index.js | 3 + content/app/src/welcome/welcome.html | 5 + content/app/src/welcome/welcome.js | 5 + content/app/static/favicon.ico | Bin 0 -> 15086 bytes content/app/test/jest-pretest.js | 6 + content/app/test/karma-bundle.js | 80 ++++++++++++ content/app/test/karma.conf.js | 82 ++++++++++++ content/app/test/unit/.eslintrc | 5 + content/app/test/unit/app.spec.js | 7 ++ content/app/webpack.config.js | 116 +++++++++++++++++ 54 files changed, 1387 insertions(+) create mode 100644 content/app/.babelrc create mode 100644 content/app/.babelrc.js create mode 100644 content/app/.editorconfig create mode 100644 content/app/.eslintrc.json create mode 100644 content/app/.gitignore create mode 100644 content/app/.vscode/extensions.json create mode 100644 content/app/.vscode/launch.json create mode 100644 content/app/.vscode/settings.json create mode 100644 content/app/aurelia_project/aurelia.json create mode 100644 content/app/aurelia_project/environments/dev.js create mode 100644 content/app/aurelia_project/environments/prod.js create mode 100644 content/app/aurelia_project/environments/stage.js create mode 100644 content/app/aurelia_project/generators/attribute.js create mode 100644 content/app/aurelia_project/generators/attribute.json create mode 100644 content/app/aurelia_project/generators/binding-behavior.js create mode 100644 content/app/aurelia_project/generators/binding-behavior.json create mode 100644 content/app/aurelia_project/generators/component.js create mode 100644 content/app/aurelia_project/generators/component.json create mode 100644 content/app/aurelia_project/generators/element.js create mode 100644 content/app/aurelia_project/generators/element.json create mode 100644 content/app/aurelia_project/generators/generator.js create mode 100644 content/app/aurelia_project/generators/generator.json create mode 100644 content/app/aurelia_project/generators/task.js create mode 100644 content/app/aurelia_project/generators/task.json create mode 100644 content/app/aurelia_project/generators/value-converter.js create mode 100644 content/app/aurelia_project/generators/value-converter.json create mode 100644 content/app/aurelia_project/tasks/build.js create mode 100644 content/app/aurelia_project/tasks/build.json create mode 100644 content/app/aurelia_project/tasks/environment.js create mode 100644 content/app/aurelia_project/tasks/jest.js create mode 100644 content/app/aurelia_project/tasks/jest.json create mode 100644 content/app/aurelia_project/tasks/karma.js create mode 100644 content/app/aurelia_project/tasks/karma.json create mode 100644 content/app/aurelia_project/tasks/run.js create mode 100644 content/app/aurelia_project/tasks/run.json create mode 100644 content/app/favicon.ico create mode 100644 content/app/index.ejs create mode 100644 content/app/jsconfig.json create mode 100644 content/app/package-scripts.js create mode 100644 content/app/package.json create mode 100644 content/app/src/app.html create mode 100644 content/app/src/app.js create mode 100644 content/app/src/environment.js create mode 100644 content/app/src/main.js create mode 100644 content/app/src/resources/index.js create mode 100644 content/app/src/welcome/welcome.html create mode 100644 content/app/src/welcome/welcome.js create mode 100644 content/app/static/favicon.ico create mode 100644 content/app/test/jest-pretest.js create mode 100644 content/app/test/karma-bundle.js create mode 100644 content/app/test/karma.conf.js create mode 100644 content/app/test/unit/.eslintrc create mode 100644 content/app/test/unit/app.spec.js create mode 100644 content/app/webpack.config.js diff --git a/content/app/.babelrc b/content/app/.babelrc new file mode 100644 index 0000000..87316ba --- /dev/null +++ b/content/app/.babelrc @@ -0,0 +1,5 @@ +{ + "presets": [ + "./.babelrc.js" + ] +} \ No newline at end of file diff --git a/content/app/.babelrc.js b/content/app/.babelrc.js new file mode 100644 index 0000000..4d2bde9 --- /dev/null +++ b/content/app/.babelrc.js @@ -0,0 +1,27 @@ +// this file will be used by default by babel@7 once it is released +module.exports = () => { + return { + "plugins": [ + "transform-decorators-legacy", + "transform-class-properties" + ], + "presets": [ + [ + "env", { + "targets": process.env.BABEL_TARGET === 'node' ? { + "node": process.env.IN_PROTRACTOR ? '6' : 'current' + } : { + "browsers": [ + "last 2 versions", + "not ie <= 11" + ], + "uglify": process.env.NODE_ENV === 'production', + }, + "loose": true, + "modules": process.env.BABEL_TARGET === 'node' ? 'commonjs' : false, + "useBuiltIns": true + } + ] + ] + } +} \ No newline at end of file diff --git a/content/app/.editorconfig b/content/app/.editorconfig new file mode 100644 index 0000000..26692da --- /dev/null +++ b/content/app/.editorconfig @@ -0,0 +1,12 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +# 2 space indentation +indent_style = space +indent_size = 2 diff --git a/content/app/.eslintrc.json b/content/app/.eslintrc.json new file mode 100644 index 0000000..6cbb37d --- /dev/null +++ b/content/app/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "./node_modules/aurelia-tools/.eslintrc.json" +} diff --git a/content/app/.gitignore b/content/app/.gitignore new file mode 100644 index 0000000..2ebf2f7 --- /dev/null +++ b/content/app/.gitignore @@ -0,0 +1,31 @@ +# You may want to customise this file depending on your Operating System +# and the editor that you use. +# +# We recommend that you use a Global Gitignore for files that are not related +# to the project. (https://help.github.com/articles/ignoring-files/#create-a-global-gitignore) + +# OS +# +# Ref: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# Ref: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Ref: https://github.com/github/gitignore/blob/master/Global/Linux.gitignore +.DS_STORE +Thumbs.db + +# Editors +# +# Ref: https://github.com/github/gitignore/blob/master/Global +# Ref: https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore +# Ref: https://github.com/github/gitignore/blob/master/Global/VisualStudioCode.gitignore +.idea +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# Dependencies +node_modules + +# Compiled files +scripts diff --git a/content/app/.vscode/extensions.json b/content/app/.vscode/extensions.json new file mode 100644 index 0000000..c8227c3 --- /dev/null +++ b/content/app/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + "recommendations": [ + "AureliaEffect.aurelia", + "msjsdiag.debugger-for-chrome", + "steoates.autoimport", + "EditorConfig.EditorConfig", + "christian-kohler.path-intellisense", + "behzad88.Aurelia" + ] +} \ No newline at end of file diff --git a/content/app/.vscode/launch.json b/content/app/.vscode/launch.json new file mode 100644 index 0000000..3a5f9b4 --- /dev/null +++ b/content/app/.vscode/launch.json @@ -0,0 +1,19 @@ +{ + // Use IntelliSense to find out which attributes exist for node debugging + // Use hover for the description of the existing attributes + // For further information visit https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Chrome", + "type": "chrome", + "request": "launch", + "url": "http://localhost:8080", + "webRoot": "${workspaceRoot}/src", + "userDataDir": "${workspaceRoot}/.chrome", + "sourceMapPathOverrides": { + "webpack:///./src/*": "${webRoot}/*" + } + } + ] +} \ No newline at end of file diff --git a/content/app/.vscode/settings.json b/content/app/.vscode/settings.json new file mode 100644 index 0000000..7857ad3 --- /dev/null +++ b/content/app/.vscode/settings.json @@ -0,0 +1,6 @@ +// Place your settings in this file to overwrite default and user settings. +{ + "typescript.tsdk": "node_modules/typescript/lib", + "html.suggest.angular1": false, + "html.suggest.ionic": false +} diff --git a/content/app/aurelia_project/aurelia.json b/content/app/aurelia_project/aurelia.json new file mode 100644 index 0000000..772ffac --- /dev/null +++ b/content/app/aurelia_project/aurelia.json @@ -0,0 +1,78 @@ +{ + "name": "app", + "type": "project:application", + "bundler": { + "id": "webpack", + "displayName": "Webpack" + }, + "build": { + "options": { + "server": "dev", + "extractCss": "prod", + "coverage": false + } + }, + "platform": { + "id": "web", + "displayName": "Web", + "hmr": false, + "open": false, + "port": 8080, + "output": "dist" + }, + "loader": { + "id": "none", + "displayName": "None" + }, + "transpiler": { + "id": "babel", + "displayName": "Babel", + "fileExtension": ".js", + "options": { + "plugins": [ + "transform-es2015-modules-amd" + ] + } + }, + "markupProcessor": { + "id": "minimum", + "displayName": "Minimal Minification", + "fileExtension": ".html" + }, + "cssProcessor": { + "id": "none", + "displayName": "None", + "fileExtension": ".css" + }, + "editor": { + "id": "vscode", + "displayName": "Visual Studio Code" + }, + "unitTestRunners": [ + { + "id": "jest", + "displayName": "Jest" + }, + { + "id": "karma", + "displayName": "Karma" + } + ], + "integrationTestRunner": { + "id": "none", + "displayName": "None" + }, + "paths": { + "root": "src", + "resources": "resources", + "elements": "resources/elements", + "attributes": "resources/attributes", + "valueConverters": "resources/value-converters", + "bindingBehaviors": "resources/binding-behaviors" + }, + "testFramework": { + "id": "jasmine", + "displayName": "Jasmine" + }, + "packageManager": "npm" +} \ No newline at end of file diff --git a/content/app/aurelia_project/environments/dev.js b/content/app/aurelia_project/environments/dev.js new file mode 100644 index 0000000..3495e9a --- /dev/null +++ b/content/app/aurelia_project/environments/dev.js @@ -0,0 +1,4 @@ +export default { + debug: true, + testing: true +}; diff --git a/content/app/aurelia_project/environments/prod.js b/content/app/aurelia_project/environments/prod.js new file mode 100644 index 0000000..da32a4b --- /dev/null +++ b/content/app/aurelia_project/environments/prod.js @@ -0,0 +1,4 @@ +export default { + debug: false, + testing: false +}; diff --git a/content/app/aurelia_project/environments/stage.js b/content/app/aurelia_project/environments/stage.js new file mode 100644 index 0000000..dafe69b --- /dev/null +++ b/content/app/aurelia_project/environments/stage.js @@ -0,0 +1,4 @@ +export default { + debug: true, + testing: false +}; diff --git a/content/app/aurelia_project/generators/attribute.js b/content/app/aurelia_project/generators/attribute.js new file mode 100644 index 0000000..7be5039 --- /dev/null +++ b/content/app/aurelia_project/generators/attribute.js @@ -0,0 +1,44 @@ +import {inject} from 'aurelia-dependency-injection'; +import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli'; + +@inject(Project, CLIOptions, UI) +export default class AttributeGenerator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the custom attribute?') + .then(name => { + let fileName = this.project.makeFileName(name); + let className = this.project.makeClassName(name); + + this.project.attributes.add( + ProjectItem.text(`${fileName}.js`, this.generateSource(className)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(`Created ${fileName}.`)); + }); + } + + generateSource(className) { + return `import {inject} from 'aurelia-framework'; + +@inject(Element) +export class ${className}CustomAttribute { + constructor(element) { + this.element = element; + } + + valueChanged(newValue, oldValue) { + + } +} + +`; + } +} diff --git a/content/app/aurelia_project/generators/attribute.json b/content/app/aurelia_project/generators/attribute.json new file mode 100644 index 0000000..ddf940c --- /dev/null +++ b/content/app/aurelia_project/generators/attribute.json @@ -0,0 +1,4 @@ +{ + "name": "attribute", + "description": "Creates a custom attribute class and places it in the project resources." +} diff --git a/content/app/aurelia_project/generators/binding-behavior.js b/content/app/aurelia_project/generators/binding-behavior.js new file mode 100644 index 0000000..8726a10 --- /dev/null +++ b/content/app/aurelia_project/generators/binding-behavior.js @@ -0,0 +1,41 @@ +import {inject} from 'aurelia-dependency-injection'; +import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli'; + +@inject(Project, CLIOptions, UI) +export default class BindingBehaviorGenerator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the binding behavior?') + .then(name => { + let fileName = this.project.makeFileName(name); + let className = this.project.makeClassName(name); + + this.project.bindingBehaviors.add( + ProjectItem.text(`${fileName}.js`, this.generateSource(className)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(`Created ${fileName}.`)); + }); + } + + generateSource(className) { + return `export class ${className}BindingBehavior { + bind(binding, source) { + + } + + unbind(binding, source) { + + } +} + +` + } +} diff --git a/content/app/aurelia_project/generators/binding-behavior.json b/content/app/aurelia_project/generators/binding-behavior.json new file mode 100644 index 0000000..60906a1 --- /dev/null +++ b/content/app/aurelia_project/generators/binding-behavior.json @@ -0,0 +1,4 @@ +{ + "name": "binding-behavior", + "description": "Creates a binding behavior class and places it in the project resources." +} diff --git a/content/app/aurelia_project/generators/component.js b/content/app/aurelia_project/generators/component.js new file mode 100644 index 0000000..8f381c7 --- /dev/null +++ b/content/app/aurelia_project/generators/component.js @@ -0,0 +1,51 @@ +import { inject } from 'aurelia-dependency-injection'; +import { Project, ProjectItem, CLIOptions, UI } from 'aurelia-cli'; + +var path = require('path'); + +@inject(Project, CLIOptions, UI) +export default class ElementGenerator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + let self = this; + + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the component?') + .then(name => { + + return self.ui.ensureAnswer(this.options.args[1], 'What sub-folder would you like to add it to?\nIf it doesn\'t exist it will be created for you.\n\nDefault folder is the source folder (src).', ".") + .then(subFolders => { + + let fileName = this.project.makeFileName(name); + let className = this.project.makeClassName(name); + + self.project.root.add( + ProjectItem.text(path.join(subFolders, fileName + ".js"), this.generateJSSource(className)), + ProjectItem.text(path.join(subFolders, fileName + ".html"), this.generateHTMLSource(className)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(`Created ${name} in the '${path.join(self.project.root.name, subFolders)}' folder`)); + }); + }); + } + + generateJSSource(className) { + return `export class ${className} { + constructor() { + this.message = 'Hello world'; + } +}` + } + + generateHTMLSource(className) { + return `` + } +} \ No newline at end of file diff --git a/content/app/aurelia_project/generators/component.json b/content/app/aurelia_project/generators/component.json new file mode 100644 index 0000000..ec39075 --- /dev/null +++ b/content/app/aurelia_project/generators/component.json @@ -0,0 +1,4 @@ +{ + "name": "component", + "description": "Creates a custom component class and template (view model and view), placing them in the project source folder (or optionally in sub folders)." +} \ No newline at end of file diff --git a/content/app/aurelia_project/generators/element.js b/content/app/aurelia_project/generators/element.js new file mode 100644 index 0000000..a1b48b9 --- /dev/null +++ b/content/app/aurelia_project/generators/element.js @@ -0,0 +1,48 @@ +import {inject} from 'aurelia-dependency-injection'; +import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli'; + +@inject(Project, CLIOptions, UI) +export default class ElementGenerator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the custom element?') + .then(name => { + let fileName = this.project.makeFileName(name); + let className = this.project.makeClassName(name); + + this.project.elements.add( + ProjectItem.text(`${fileName}.js`, this.generateJSSource(className)), + ProjectItem.text(`${fileName}.html`, this.generateHTMLSource(className)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(`Created ${fileName}.`)); + }); + } + + generateJSSource(className) { + return `import {bindable} from 'aurelia-framework'; + +export class ${className} { + @bindable value; + + valueChanged(newValue, oldValue) { + + } +} + +`; + } + + generateHTMLSource(className) { + return ``; + } +} diff --git a/content/app/aurelia_project/generators/element.json b/content/app/aurelia_project/generators/element.json new file mode 100644 index 0000000..68d8c54 --- /dev/null +++ b/content/app/aurelia_project/generators/element.json @@ -0,0 +1,4 @@ +{ + "name": "element", + "description": "Creates a custom element class and template, placing them in the project resources." +} diff --git a/content/app/aurelia_project/generators/generator.js b/content/app/aurelia_project/generators/generator.js new file mode 100644 index 0000000..4162842 --- /dev/null +++ b/content/app/aurelia_project/generators/generator.js @@ -0,0 +1,73 @@ +import {inject} from 'aurelia-dependency-injection'; +import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli'; + +@inject(Project, CLIOptions, UI) +export default class GeneratorGenerator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the generator?') + .then(name => { + let fileName = this.project.makeFileName(name); + let className = this.project.makeClassName(name); + + this.project.generators.add( + ProjectItem.text(`${fileName}.js`, this.generateSource(className)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(`Created ${fileName}.`)); + }); + } + + generateSource(className) { + return `import {inject} from 'aurelia-dependency-injection'; +import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli'; + +@inject(Project, CLIOptions, UI) +export default class ${className}Generator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the new item?') + .then(name => { + let fileName = this.project.makeFileName(name); + let className = this.project.makeClassName(name); + + this.project.elements.add( + ProjectItem.text(\`\${fileName}.js\`, this.generateSource(className)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(\`Created \${fileName}.\`)); + }); + } + + generateSource(className) { +return \`import {bindable} from 'aurelia-framework'; + +export class \${className} { + @bindable value; + + valueChanged(newValue, oldValue) { + + } +} + +\` + } +} + +`; + } +} diff --git a/content/app/aurelia_project/generators/generator.json b/content/app/aurelia_project/generators/generator.json new file mode 100644 index 0000000..be946a5 --- /dev/null +++ b/content/app/aurelia_project/generators/generator.json @@ -0,0 +1,4 @@ +{ + "name": "generator", + "description": "Creates a generator class and places it in the project generators folder." +} diff --git a/content/app/aurelia_project/generators/task.js b/content/app/aurelia_project/generators/task.js new file mode 100644 index 0000000..a70f10b --- /dev/null +++ b/content/app/aurelia_project/generators/task.js @@ -0,0 +1,41 @@ +import {inject} from 'aurelia-dependency-injection'; +import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli'; + +@inject(Project, CLIOptions, UI) +export default class TaskGenerator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the task?') + .then(name => { + let fileName = this.project.makeFileName(name); + let functionName = this.project.makeFunctionName(name); + + this.project.tasks.add( + ProjectItem.text(`${fileName}.js`, this.generateSource(functionName)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(`Created ${fileName}.`)); + }); + } + + generateSource(functionName) { + return `import gulp from 'gulp'; +import changed from 'gulp-changed'; +import project from '../aurelia.json'; + +export default function ${functionName}() { + return gulp.src(project.paths.???) + .pipe(changed(project.paths.output, {extension: '.???'})) + .pipe(gulp.dest(project.paths.output)); +} + +`; + } +} diff --git a/content/app/aurelia_project/generators/task.json b/content/app/aurelia_project/generators/task.json new file mode 100644 index 0000000..fd15bc6 --- /dev/null +++ b/content/app/aurelia_project/generators/task.json @@ -0,0 +1,4 @@ +{ + "name": "task", + "description": "Creates a task and places it in the project tasks folder." +} diff --git a/content/app/aurelia_project/generators/value-converter.js b/content/app/aurelia_project/generators/value-converter.js new file mode 100644 index 0000000..df79971 --- /dev/null +++ b/content/app/aurelia_project/generators/value-converter.js @@ -0,0 +1,41 @@ +import {inject} from 'aurelia-dependency-injection'; +import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli'; + +@inject(Project, CLIOptions, UI) +export default class ValueConverterGenerator { + constructor(project, options, ui) { + this.project = project; + this.options = options; + this.ui = ui; + } + + execute() { + return this.ui + .ensureAnswer(this.options.args[0], 'What would you like to call the value converter?') + .then(name => { + let fileName = this.project.makeFileName(name); + let className = this.project.makeClassName(name); + + this.project.valueConverters.add( + ProjectItem.text(`${fileName}.js`, this.generateSource(className)) + ); + + return this.project.commitChanges() + .then(() => this.ui.log(`Created ${fileName}.`)); + }); + } + + generateSource(className) { + return `export class ${className}ValueConverter { + toView(value) { + + } + + fromView(value) { + + } +} + +`; + } +} diff --git a/content/app/aurelia_project/generators/value-converter.json b/content/app/aurelia_project/generators/value-converter.json new file mode 100644 index 0000000..1108122 --- /dev/null +++ b/content/app/aurelia_project/generators/value-converter.json @@ -0,0 +1,4 @@ +{ + "name": "value-converter", + "description": "Creates a value converter class and places it in the project resources." +} diff --git a/content/app/aurelia_project/tasks/build.js b/content/app/aurelia_project/tasks/build.js new file mode 100644 index 0000000..7028d32 --- /dev/null +++ b/content/app/aurelia_project/tasks/build.js @@ -0,0 +1,58 @@ +import webpackConfig from '../../webpack.config'; +import webpack from 'webpack'; +import project from '../aurelia.json'; +import {CLIOptions, Configuration} from 'aurelia-cli'; +import gulp from 'gulp'; +import configureEnvironment from './environment'; +import del from 'del'; + +const analyze = CLIOptions.hasFlag('analyze'); +const buildOptions = new Configuration(project.build.options); +const production = CLIOptions.getEnvironment() === 'prod'; +const server = buildOptions.isApplicable('server'); +const extractCss = buildOptions.isApplicable('extractCss'); +const coverage = buildOptions.isApplicable('coverage'); + +const config = webpackConfig({ + production, server, extractCss, coverage, analyze +}); +const compiler = webpack(config); + +function buildWebpack(done) { + if (CLIOptions.hasFlag('watch')) { + compiler.watch({}, onBuild); + } else { + compiler.run(onBuild); + compiler.plugin('done', () => done()); + } +} + +function onBuild(err, stats) { + if (!CLIOptions.hasFlag('watch') && err) { + console.error(err.stack || err); + if (err.details) console.error(err.details); + process.exit(1); + } else { + process.stdout.write(stats.toString({ colors: require('supports-color') }) + '\n'); + + if (!CLIOptions.hasFlag('watch') && stats.hasErrors()) { + process.exit(1); + } + } +} + +function clearDist() { + return del([config.output.path]); +} + +const build = gulp.series( + clearDist, + configureEnvironment, + buildWebpack +); + +export { + config, + buildWebpack, + build as default +}; diff --git a/content/app/aurelia_project/tasks/build.json b/content/app/aurelia_project/tasks/build.json new file mode 100644 index 0000000..ada5ca4 --- /dev/null +++ b/content/app/aurelia_project/tasks/build.json @@ -0,0 +1,16 @@ +{ + "name": "build", + "description": "Builds and processes all application assets.", + "flags": [ + { + "name": "env", + "description": "Sets the build environment.", + "type": "string" + }, + { + "name": "watch", + "description": "Watches source files for changes and refreshes the bundles automatically.", + "type": "boolean" + } + ] +} diff --git a/content/app/aurelia_project/tasks/environment.js b/content/app/aurelia_project/tasks/environment.js new file mode 100644 index 0000000..4902dfd --- /dev/null +++ b/content/app/aurelia_project/tasks/environment.js @@ -0,0 +1,24 @@ +import project from '../aurelia.json'; +import rename from 'gulp-rename'; +import {CLIOptions} from 'aurelia-cli'; +import gulp from 'gulp'; +import fs from 'fs'; +import path from 'path'; +import through from 'through2'; + +function configureEnvironment() { + let env = CLIOptions.getEnvironment(); + + return gulp.src(`aurelia_project/environments/${env}${project.transpiler.fileExtension}`) + .pipe(rename(`environment${project.transpiler.fileExtension}`)) + .pipe(gulp.dest(project.paths.root)) + .pipe(through.obj(function (file, enc, cb) { + // https://github.com/webpack/watchpack/issues/25#issuecomment-287789288 + var now = Date.now() / 1000; + var then = now - 10; + fs.utimes(file.path, then, then, function (err) { if (err) throw err }); + cb(null, file); + })); +} + +export default configureEnvironment; \ No newline at end of file diff --git a/content/app/aurelia_project/tasks/jest.js b/content/app/aurelia_project/tasks/jest.js new file mode 100644 index 0000000..3df63f9 --- /dev/null +++ b/content/app/aurelia_project/tasks/jest.js @@ -0,0 +1,23 @@ +import jest from 'jest-cli'; +import PluginError from 'plugin-error'; +import path from 'path'; +import packageJson from '../../package.json'; +import {CLIOptions} from 'aurelia-cli'; + +export default (cb) => { + let options = packageJson.jest; + + if (CLIOptions.hasFlag('watch')) { + Object.assign(options, { watch: true}); + } + + process.env.BABEL_TARGET = 'node'; + + jest.runCLI(options, [path.resolve(__dirname, '../../')]).then((result) => { + if (result.numFailedTests || result.numFailedTestSuites) { + cb(new PluginError('gulp-jest', { message: 'Tests Failed' })); + } else { + cb(); + } + }); +}; diff --git a/content/app/aurelia_project/tasks/jest.json b/content/app/aurelia_project/tasks/jest.json new file mode 100644 index 0000000..c11176c --- /dev/null +++ b/content/app/aurelia_project/tasks/jest.json @@ -0,0 +1,11 @@ +{ + "name": "jest", + "description": "Runs Jest and reports the results.", + "parameters": [ + { + "name": "watch", + "description": "Watches test files for changes and re-runs the tests automatically.", + "type": "boolean" + } + ] +} diff --git a/content/app/aurelia_project/tasks/karma.js b/content/app/aurelia_project/tasks/karma.js new file mode 100644 index 0000000..f5a63bb --- /dev/null +++ b/content/app/aurelia_project/tasks/karma.js @@ -0,0 +1,16 @@ +import {Server as Karma} from 'karma'; +import {CLIOptions} from 'aurelia-cli'; +import path from 'path'; + +let karma = done => { + new Karma({ + configFile: path.join(__dirname, '/../../test/karma.conf.js'), + singleRun: !CLIOptions.hasFlag('watch'), + autoWatch: CLIOptions.hasFlag('watch') + }, function(exitCode) { + console.log('Karma has exited with ' + exitCode) + process.exit(exitCode) + }).start(); +}; + +export { karma as default }; diff --git a/content/app/aurelia_project/tasks/karma.json b/content/app/aurelia_project/tasks/karma.json new file mode 100644 index 0000000..9ff49da --- /dev/null +++ b/content/app/aurelia_project/tasks/karma.json @@ -0,0 +1,11 @@ +{ + "name": "karma", + "description": "Runs Karma and reports the results.", + "flags": [ + { + "name": "watch", + "description": "Watches test files for changes and re-runs the tests automatically.", + "type": "boolean" + } + ] +} diff --git a/content/app/aurelia_project/tasks/run.js b/content/app/aurelia_project/tasks/run.js new file mode 100644 index 0000000..f07b383 --- /dev/null +++ b/content/app/aurelia_project/tasks/run.js @@ -0,0 +1,46 @@ +import {config} from './build'; +import configureEnvironment from './environment'; +import webpack from 'webpack'; +import Server from 'webpack-dev-server'; +import project from '../aurelia.json'; +import {CLIOptions, reportWebpackReadiness} from 'aurelia-cli'; +import gulp from 'gulp'; + +function runWebpack(done) { + // https://webpack.github.io/docs/webpack-dev-server.html + let opts = { + host: 'localhost', + publicPath: config.output.publicPath, + filename: config.output.filename, + hot: project.platform.hmr || CLIOptions.hasFlag('hmr'), + port: project.platform.port, + contentBase: config.output.path, + historyApiFallback: true, + open: project.platform.open, + stats: { + colors: require('supports-color') + } + }; + + if (project.platform.hmr || CLIOptions.hasFlag('hmr')) { + config.plugins.push(new webpack.HotModuleReplacementPlugin()); + config.entry.app.unshift(`webpack-dev-server/client?http://${opts.host}:${opts.port}/`, 'webpack/hot/dev-server'); + } + + const compiler = webpack(config); + let server = new Server(compiler, opts); + + server.listen(opts.port, opts.host, function(err) { + if (err) throw err; + + reportWebpackReadiness(opts); + done(); + }); +} + +const run = gulp.series( + configureEnvironment, + runWebpack +); + +export { run as default }; diff --git a/content/app/aurelia_project/tasks/run.json b/content/app/aurelia_project/tasks/run.json new file mode 100644 index 0000000..7ddfcfb --- /dev/null +++ b/content/app/aurelia_project/tasks/run.json @@ -0,0 +1,21 @@ +{ + "name": "run", + "description": "Builds the application and serves up the assets via a local web server, watching files for changes as you work.", + "flags": [ + { + "name": "analyze", + "description": "Enable Webpack Bundle Analyzer. Typically paired with --env prod", + "type": "boolean" + }, + { + "name": "env", + "description": "Sets the build environment.", + "type": "string" + }, + { + "name": "hmr", + "description": "Enable Hot Module Reload", + "type": "boolean" + } + ] +} diff --git a/content/app/favicon.ico b/content/app/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..330515e9c1d77fdfe88d7989060380932ca13e99 GIT binary patch literal 15086 zcmdU$3s{v^*2iB&MJ)y8rl5$Lrg=*<(=2f+Q&TiWEh}#|Up1A23Y>G`00#uQh@v2< zs0f0opk^0GO-stu@-k+ZvFWR%>86&7*`sD~_V-)wxp48wFw@iX%y*t=x#94>d#}rX zueJADOHFgr+_gLJ)EI-c&D}L^u%>Cj!S>(1H0>+C^J0|0Ki^c-7V$t&p5Ya379`*6 zpWAH1f7`zWkIr%XZ{w-4{H%N={Fc?@=0@a?n>+OXqZ}(nMa;|_6Ml8|*zoU=A#zRV zT#)p~eTu^@?$8s^{gBh{8>S?-*)YWddK>>)`oR32%O09{D(B${l{Y#m-scd9efeheDfv0bgVZraQ#kvV|nqX5Cw#{MgAmIaETS8kQWv4xiUhp4RJSEYJ z3{~*IXTxO6unm*ro7{|d`9AsH$eF44MP5lCzCdLn!%}2eK60MQ8HFvzAVV!%tQ$Yq zY3GLKto=81@F#R}4t%Pthvxll@re14W<6-|D4A?|0G{82et_;To|-(oc{u^T)`8z!2S+fc-H2x zp`Urj7c9OlbBIpF#^~wi5APu*QHDmfE&WgFyd?jX}Ntp*3RKnnBl{h3yfhXM- zf+w*Bdt0}K4Nnn^*N>DBpnYL%_{hkzH&lbBS&iGQX@9dzV4Q3^4r+580-E@trnJ zOYXROY-DcU=y{hR^fh0t9dA@clM|3bWJoB0S_=QBUWn6l;BBhk!H7r;0f#=Mvs9G`5PMH-3Q$4t%nfP$RLDFf~im04?Sc}W4Bc;O+A(unR+f!raRJ=sZX-veSI$Q zqy$f*A8f4Kg1xQMLl#_QZ;x$=XUE@4CchxKiLJrSyc*n~7tvAdK+$~+YsRs5f-?0@ zf{&C-=yZ8>k0k;5q2Zn2JrDW?x{57kI_5WaT|3LzZRJ%{_Z(%qJxiH-WhhhcMa+>X zx)7TxGq#m=L|0;OFq;AY&b{N9%hibP?`OaN;J{6$Yuv!QS+~8cD>~G9xFg+a>Xmui z*dr@6W0*y3F_rz0v~tXXRytucFO;UvCBGT?6z8&y5}OpGGxf){WN3%Pv}GJ zDmsd@;ps4YyRo=w2X6K_aRcsT9|;yk7h>C5xY6w{YodFw!1}!wD;*cNFS~?(ml?XQ z3jF?+0NrQ5=(p^a7yOoPdeMKWiU`P4hR(>)b&WFKmZwZTvUzW*9ZxBCJeiTfcmb?F z;!4l;zbkvREfWG;s!tPZ{P;rb96pLr#e0a>zxa&#-QS3 z#!fGX&g+oh0vW>K|09t>$Yu*<)$z0v8FDUQ$423%HjX&|`4IEsiGSzxICX=+sf`=i zvku&_|D3p40skv)`V`)S*Teq?W$d(389Q#eWC$!>W(?R7@E5;Khb?~5Z6W(2Fjqwf zvnRT(&R{?2{-$tJtQT}g;l$Vm&ruFJh<8oE%?RS){)E9%)it;gUr(%QEN;4jiQocw zFH**!68L{v83MN`L%>$6p~LoLhW4+Gi||`7wwMgnw#EC=o!2^XQy6BBE)0wP1{n-c zTL+*2Y9yBXf*T9|=A1oFHRNx^<~QOdxDeip?YiF#|7GyMO&QwnPzL|kFB$xHX2tmJ z#TJXj7OSztw~V0<-U=s~hZcp!eODA_R><%h{O^K>LXEP8X<$?n_Us7uY&rg>+7_o8 zgB#Jk9XCNbZs5Jt#(RfX;QuxFe?uAl{%SS)?LKDm-8(MaZyo-1Nk9CQhwz^}D%^Y3 zBlCB!n_%KR7zc?A(4^RJp%D%l|JC@_@|{f#eat?@sYFwsg+JQkl-<`m{Eg_|?r&V+ z#@JEEjRH6D{;KF6-giQ~l*xAw^yVd#&%P|P&$|H*esV`eL?c7B+{f00M%R|%F#LCP zJlD`zHe*$LD0}P7m7`aTNpEWGoic(r^$u~W+8(F=6Wl0pBf3{c-`&Eyf_D|;^OiNn zd;if`?{~(>wmaA?Z*=&0`2QGEYsMQm2gZvG7oaf>@$C59)|qRYY@N9}aqG-g)|aPc zUnrcEo>4M2-9NH>hPSC_W)lA9CtIAV?Qd%1hCSPHlN~o((S04<)YAQ4;a$aezpY}u z%T;WkGZmRV-CBD0!zi9++?7Dv&{^8yG9r!<>%W0$Me)@5DV)6vk)ctz**0sf-?mw6_QSs_oxVyHPhBefJLn=mXOuja=5Oeh z=SQ4cNZk2JKa(}=Z@_(h+&FZ<-_HBH@cy1Mw>_ld+P<&iygs-T=Xq?Y`PP#GyW+<; z>fW+#_WCC9p9oozL2aG6MwQK2tu{@|cG$sTi?<5H(gQ|mWp11i9>U)oAWl{5zWzVM z4Z0WJ4?>59cj%~!_dI4z@H%lc!TY07i|?n+9QeN3xP5lPgWG1WI|u*DM#!Mcfi0fO zt8I%SaHZd;WG+*eLSKA+GI8p>4LA6D7yia*^EWrcjh%PV{So0^#e4ltCA9lcS$saO zO!WWz(xeWb-4sLHXRp5n{$GO>GQhu($WbGM-4>s)5A^#~MC;Pl;jK3(LXSlHZfR!h zxcNci)O*CKYFnHVU;l68#;*J0DxvKOc>hQx`hBXB+Mlu}1%7^XVW%%clY=X6um$|P zL!t106tdn#hF{nh(;W7L?`OkXZ~7Iw$j|BFw{Gz>cHHKRzga|_I&Y6tH~JeNr@y%w zZWOpt3En4_#rG4H*#4AC3iyXw*zpUM-1)1@lrCQ{U3A;GE^UDf9pOILKFPLE=>Pjks~_S>4~*_Ns72kru`cTV{gKq3XU3)V{;5uGP;`q7&EUVr7B(z>1fKNlJA11Y zR4h1+@jRd++q?$pUHo>FK2{Q;?xC`&%g9HH^YqrHwxUSQ-=)jJqY>=dK(%JInS&3 zu~zuA67g%uVe@hLIfoqtPcCfnQ$*`6_sRV8+&^@WX?tK4aq2K}%4&~Ob#deE^fwLR zM!|bdM&Ao{un(`dK-(dFs7`M%-s+GIKlThVTuo?qQuhzFWdKihIgT*a*aF@cN3GnzKQqhXJ zO2mhWUc?_uOp(|k>(-aSZj1BicC=&u4O13}6g;}w;(iyMn0Cxxe}s2uy#Sx}41V{T_}_({zR>3v9f__i zz8~xULbpY&J%J3V=C()l^DcJ?pVH~MdpABVXTem?!s%-BliAiSPh}t2GJW~&6E)QY zn~ue{AD|zrJx&zF(yqVa#QsR^oH@AzwId>Y~ z>-b8UzoAchp9{C(r#7YHYsKe^@0Iw$`9qI|H{uCfwEOUUyw{0Qj(NEQ4d)(r1{pZZ z=5Zz$%7s>3D4m{jL!JlSH$_L|Smy}qS?##F3Lnop=4|XpZ196#0drMpy^sM6ivO*# zMSVQ|-3ks;@k@5xYSfe94TS}bz8Q#~Ud*^w#vHZ(( z@ZT1S=Kb%9*T`^2rFO>_;8NnD#B}i!c3Zp$hIQP?yPTEAKo^lgmDQEu5d1rFBhR|} zuvRm0^8ow@yZU=$zf13X!3`OPBEv4``b}bYY7cB-$CF@{y?q|rJ8>g(%UKT!gHGr& z*lchCJKTVq#`5xep0nG+P}>%EJXx{DBKDq3Jivc2{O3ZK!4bI0bNSrw;jOXnX7s!0 zu*Gg{`O;lz!rx!@gJtbPz`@HtoS{t@5lw&?wn0X%)o-mZh2KVrQBC)m_Gj!&Z&aI&@)`mY``>p4v4ngwaDY z%6QGq5+UDLY84goT%|TZA1ky@dl@S=txXW) zHBEEBFNF1IU%J+r^%26zSY57ZL-_vMEKR#r#vz*Kk-&SLG-aI%4<6J~2s!Cx^(=J!Q0^`>eu)y<|%iS($RQ{F4{eaBF zm{=~O=8;&z{8r7={aS*IZQQFEl_khSDaP^;PkpQm$N7*=SNK+XE~Hi|{X5bt zAvH{7x(*Me=%T&j`T8TedW1Uv1$jq$PN;SM$eam@_rwHjd^}}hVOYY?`QxHFZ=3Bs z6qc*3pLoD%ax?Zx_M)z`(|ngv?>BJt;K)4EYa%sZ=6(wvyz8$kzw>>7U`C!3z86vB zrd}pB=W6Or`xEX;9GyST@EH9AC#9ET4ZR$NVewb6!%TUf8bTCx@2Z&o3A|&{Ywgm1 zBDHdz6R=a)QZj-??{cyyg&Aym181S z!pD_WV*?YeC-hG)8FYebG`0Q?*cV{d0+ZRutzn$D(0d|t}%$-N1>bZ4!w*0 zq~AfWFG~-EUL#DAdc4$0-ZJ-EI*LAoP_Wwd&t6$=BLZ@F>2=E6sC!GjSb8X=4}^E6 z2ZXuyVvn2YUGV;{Q}6VL2+#7KUgwj#d>?uWq_!&k1X5S+zT%vr>*_dT@CGmHbEBwp zRo2ve^YxmsUeBSAgI<&~^oF?9yVwD}N2B-ab@WdEkls&X(>rU^4thDtZH-?8yoWEP4_;s2ch?LaC)%;z1wQ=dM!WK zUdNX@IJMYL8_yX#mYT!;^Y4KNspbEo>mrDHdAC(>8oOtEZ+zU?iW-@-mR28s$lesc zF$TTAkKU~}*E@B+Zc@vZ+6?tbsijJ7AfT+;&|$~EX#ZCqw(H^(`Z~^n3tjKjxaLx8 zJOK~WAc>?dKe2a32bk_OrGxj2dTrFT-tBcEsi8{^nmVYS*ME(i^3HQ6zddGZpZC7t zmpR5u+v7&h%-!oI7{AtQonhuHtiKo{NZ%}?fai|wB{4*VX*c2*rnuJw-W zQpc3~vD7f7{;Jn6tEr#uBd2$NM&H7w)ccl8%@Q7@-d7DDaqA{TyTk+M;BlqXSDq@F zy2O}vZ)zW7&&BCrs8a8NaIJS+9Z#>HO8rr4r;^jvbLr>EDJEnNS~7Ii*oalsuCGw9 z+Y1ja_aS-kK<*UpZ+ap}>Oob|o`OfyL#Qc+Qj`0Deh{mz9_Lc;$Zo5B+G>a7!rMvh z>R>hbs(lu}_eSEU!-}VxUFHhN%QPjAy;$lZQV)6g@#WN|(}j<-g<)xb2FHQ;xJ>X~ zY3rMCsdrlq$J>^Nch=3QJCXM|8}E5CHqP^Nm$H+`9Y<}W(pj6K&bQ^MTw=_UtLrDF z;op^8gy-hY;C(!J{{Xzx^FaO7sdtgxsdr?j20-1*mJ6lkMQ+vNeX@#s^xH`RpNDWa zt&^)Fw?7dcPTT4$HT5Cxb?f#TEX}B)+(#YaLvr7yNWU$84FTITsijof>dr3p&iYbw zBai7t%}4508I0G4?+P&5fy=Q^0;-+Hf3F?HHU)tW8hut%r?DC{|IY?)1M0BwmU6j2w_m<7xue=cDk=kQN?^v(HSyCgGT&u0lcZ1&b90@s} zFOa>ztRo-R^nm6=2cZG-9l2=(^}#B^jpWvC`CRIsHM;mA#`E3#>?<$zE zcm!)t51rb9nb>J?|>@wHm$Wqj%?-RpzMufj4ik zxm(YL@t)*WrPh_$UUI5>E>d){C$`mzwy*rpiZa`c* zMHD`ws#XqhFFDXUK8_qxXXeQzKlU~AI%^O0*LD1E&mWA0j|1$HYT;XQzLFCpPhL$f zTi5%x*{fR+FIL0DZ}vPU`Pe*{=PcH4L0+hjtGcFR-TEUo@`r~M-aD`7SS7F5x)edbZ+ zp6PMT-P7}$hv)jLHl3B#bH7sSZ7cVLc~M+2{cjx~TwCDeOL>Es^4CPM!XYSLw--+&TaHp?7BYPx0;*W&C%$=~$`iV9F--mlr z7w+{(xXF&gw+))b=b9Rk45Z0_@yUV*=vLtlm$>o;YNk(^ETZkUb4NyxeX;aaos_smPewI9BQA5`FV6EOzIYz7uv+S# zQnO8H_fhGF@g>9X-4(>He-c0YCitEXhVONpQ?}uE>co@uK0kHFCub8EE_04NZSnuI z|MsWz`ccm+Cl0;jur)HbWbHcdI{t=VZH`Pc@Tt!@zQcd|Ku)|lzITjzZu79Fy?=n% pn#%bIlKg3TAURl8N#j + + + + <%- htmlWebpackPlugin.options.metadata.title %> + + + + + + <% if (htmlWebpackPlugin.options.metadata.server) { %> + + + <% } %> + + diff --git a/content/app/jsconfig.json b/content/app/jsconfig.json new file mode 100644 index 0000000..dd9df72 --- /dev/null +++ b/content/app/jsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es2015", + "lib": ["es2017", "dom"], + "experimentalDecorators": true + }, + "exclude": [ + "node_modules", + "dist" + ] +} diff --git a/content/app/package-scripts.js b/content/app/package-scripts.js new file mode 100644 index 0000000..e31b0b2 --- /dev/null +++ b/content/app/package-scripts.js @@ -0,0 +1,79 @@ +const {series, crossEnv, concurrent, rimraf} = require('nps-utils') + +module.exports = { + scripts: { + default: 'nps webpack', + test: { + default: 'nps test.jest', + jest: { + default: series( + rimraf('test/coverage-jest'), + crossEnv('BABEL_TARGET=node jest') + ), + accept: crossEnv('BABEL_TARGET=node jest -u'), + watch: crossEnv('BABEL_TARGET=node jest --watch'), + }, + + karma: { + default: series( + rimraf('test/coverage-karma'), + 'karma start test/karma.conf.js' + ), + watch: 'karma start test/karma.conf.js --auto-watch --no-single-run', + debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug' + }, + + lint: { + default: 'eslint src', + fix: 'eslint src --fix' + }, + all: concurrent({ + browser: series.nps('test.karma'), + jest: 'nps test.jest', + lint: 'nps test.lint' + }) + }, + build: 'nps webpack.build', + webpack: { + default: 'nps webpack.server', + build: { + before: rimraf('dist'), + default: 'nps webpack.build.production', + development: { + default: series( + 'nps webpack.build.before', + 'webpack --progress -d' + ), + extractCss: series( + 'nps webpack.build.before', + 'webpack --progress -d --env.extractCss' + ), + serve: series.nps( + 'webpack.build.development', + 'serve' + ), + }, + production: { + inlineCss: series( + 'nps webpack.build.before', + crossEnv('NODE_ENV=production webpack --progress -p --env.production') + ), + default: series( + 'nps webpack.build.before', + crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss') + ), + serve: series.nps( + 'webpack.build.production', + 'serve' + ), + } + }, + server: { + default: `webpack-dev-server -d --devtool '#source-map' --inline --env.server`, + extractCss: `webpack-dev-server -d --devtool '#source-map' --inline --env.server --env.extractCss`, + hmr: `webpack-dev-server -d --devtool '#source-map' --inline --hot --env.server` + }, + }, + serve: 'http-server dist --cors', + }, +} \ No newline at end of file diff --git a/content/app/package.json b/content/app/package.json new file mode 100644 index 0000000..a69e82e --- /dev/null +++ b/content/app/package.json @@ -0,0 +1,119 @@ +{ + "name": "app", + "description": "An Aurelia client application.", + "version": "0.1.0", + "repository": { + "type": "???", + "url": "???" + }, + "license": "MIT", + "dependencies": { + "aurelia-bootstrapper": "^2.2.0", + "aurelia-animator-css": "^1.0.4", + "bluebird": "^3.5.1", + "aurelia-polyfills": "^1.3.0" + }, + "peerDependencies": {}, + "devDependencies": { + "aurelia-cli": "^0.34.0", + "aurelia-testing": "^1.0.0-beta.4.0.0", + "aurelia-tools": "^2.0.0", + "gulp": "^4.0.0", + "minimatch": "^3.0.4", + "through2": "^2.0.3", + "vinyl-fs": "^3.0.2", + "babel-eslint": "7.2.3", + "eslint": "3.19.0", + "babel-loader": "^7.1.4", + "babel-core": "^6.26.0", + "babel-plugin-syntax-flow": "^6.18.0", + "babel-plugin-transform-class-properties": "^6.24.1", + "babel-plugin-transform-decorators-legacy": "^1.3.4", + "babel-plugin-transform-flow-strip-types": "^6.22.0", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "^1.6.1", + "babel-preset-es2015": "^6.24.1", + "babel-preset-stage-1": "^6.24.1", + "babel-register": "^6.26.0", + "babel-plugin-istanbul": "^4.1.5", + "jest": "^22.4.2", + "jest-cli": "^23.0.0-alpha.0", + "plugin-error": "^1.0.1", + "aurelia-loader-nodejs": "^1.0.1", + "aurelia-pal-nodejs": "^1.0.0-beta.3.2.0", + "babel-jest": "^23.0.0-alpha.0", + "jasmine-core": "^3.1.0", + "karma": "^2.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-coverage": "latest", + "karma-jasmine": "^1.1.1", + "karma-mocha-reporter": "latest", + "karma-webpack": "^v4.0.0-beta.0", + "karma-coverage-istanbul-reporter": "^1.4.2", + "jest-jasmine2": "^23.0.0-alpha.0", + "jest-matchers": "^20.0.3", + "karma-babel-preprocessor": "^7.0.0", + "gulp-rename": "^1.2.2", + "html-webpack-plugin": "^3.0.6", + "copy-webpack-plugin": "^4.5.1", + "mini-css-extract-plugin": "^0.4.1", + "aurelia-webpack-plugin": "^3.0.0-rc.1", + "duplicate-package-checker-webpack-plugin": "^3.0.0", + "webpack": "^4.1.1", + "webpack-cli": "^2.0.12", + "webpack-dev-server": "^3.1.1", + "expose-loader": "^0.7.5", + "style-loader": "^0.20.3", + "url-loader": "^1.0.1", + "del": "^3.0.0", + "css-loader": "^0.28.11", + "nps": "^5.8.2", + "nps-utils": "^1.5.0", + "file-loader": "^1.1.11", + "json-loader": "^0.5.7", + "html-loader": "^0.5.5", + "istanbul-instrumenter-loader": "^3.0.0", + "opn": "^5.3.0", + "webpack-bundle-analyzer": "latest" + }, + "jest": { + "modulePaths": [ + "/src", + "/node_modules" + ], + "moduleFileExtensions": [ + "js", + "json" + ], + "transform": { + "^.+\\.jsx?$": "babel-jest" + }, + "testRegex": "\\.spec\\.(ts|js)x?$", + "setupFiles": [ + "/test/jest-pretest.js" + ], + "testEnvironment": "node", + "collectCoverage": true, + "collectCoverageFrom": [ + "src/**/*.{js,ts}", + "!**/*.spec.{js,ts}", + "!**/node_modules/**", + "!**/test/**" + ], + "coverageDirectory": "/test/coverage-jest", + "coverageReporters": [ + "json", + "lcov", + "text", + "html" + ] + }, + "engines": { + "node": ">= 6.0.0" + }, + "scripts": { + "start": "nps", + "test": "nps test" + }, + "main": "dist/app.bundle.js" +} diff --git a/content/app/src/app.html b/content/app/src/app.html new file mode 100644 index 0000000..668958d --- /dev/null +++ b/content/app/src/app.html @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/content/app/src/app.js b/content/app/src/app.js new file mode 100644 index 0000000..ef76597 --- /dev/null +++ b/content/app/src/app.js @@ -0,0 +1,16 @@ +import { PLATFORM } from 'aurelia-pal'; + +export class App { + configureRouter(config, router) { + config.title = 'PayRun Demo'; + config.map([ + { + route: '', + moduleId: PLATFORM.moduleName('welcome/welcome'), + title: 'Welcome' + } + ]); + + this.router = router; + } +} \ No newline at end of file diff --git a/content/app/src/environment.js b/content/app/src/environment.js new file mode 100644 index 0000000..3495e9a --- /dev/null +++ b/content/app/src/environment.js @@ -0,0 +1,4 @@ +export default { + debug: true, + testing: true +}; diff --git a/content/app/src/main.js b/content/app/src/main.js new file mode 100644 index 0000000..c783449 --- /dev/null +++ b/content/app/src/main.js @@ -0,0 +1,30 @@ +import environment from './environment'; +import {PLATFORM} from 'aurelia-pal'; +import 'babel-polyfill'; +import * as Bluebird from 'bluebird'; + +// remove out if you don't want a Promise polyfill (remove also from webpack.config.js) +Bluebird.config({ warnings: { wForgottenReturn: false } }); + +export function configure(aurelia) { + aurelia.use + .standardConfiguration() + .feature(PLATFORM.moduleName('resources/index')); + + // Uncomment the line below to enable animation. + // aurelia.use.plugin(PLATFORM.moduleName('aurelia-animator-css')); + // if the css animator is enabled, add swap-order="after" to all router-view elements + + // Anyone wanting to use HTMLImports to load views, will need to install the following plugin. + // aurelia.use.plugin(PLATFORM.moduleName('aurelia-html-import-template-loader')); + + if (environment.debug) { + aurelia.use.developmentLogging(); + } + + if (environment.testing) { + aurelia.use.plugin(PLATFORM.moduleName('aurelia-testing')); + } + + return aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app'))); +} diff --git a/content/app/src/resources/index.js b/content/app/src/resources/index.js new file mode 100644 index 0000000..5e2bb3b --- /dev/null +++ b/content/app/src/resources/index.js @@ -0,0 +1,3 @@ +export function configure(config) { + //config.globalResources([]); +} diff --git a/content/app/src/welcome/welcome.html b/content/app/src/welcome/welcome.html new file mode 100644 index 0000000..4717d89 --- /dev/null +++ b/content/app/src/welcome/welcome.html @@ -0,0 +1,5 @@ + \ No newline at end of file diff --git a/content/app/src/welcome/welcome.js b/content/app/src/welcome/welcome.js new file mode 100644 index 0000000..682deb8 --- /dev/null +++ b/content/app/src/welcome/welcome.js @@ -0,0 +1,5 @@ +export class Welcome { + constructor() { + this.message = "Please Select a Contact."; + } +} diff --git a/content/app/static/favicon.ico b/content/app/static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..330515e9c1d77fdfe88d7989060380932ca13e99 GIT binary patch literal 15086 zcmdU$3s{v^*2iB&MJ)y8rl5$Lrg=*<(=2f+Q&TiWEh}#|Up1A23Y>G`00#uQh@v2< zs0f0opk^0GO-stu@-k+ZvFWR%>86&7*`sD~_V-)wxp48wFw@iX%y*t=x#94>d#}rX zueJADOHFgr+_gLJ)EI-c&D}L^u%>Cj!S>(1H0>+C^J0|0Ki^c-7V$t&p5Ya379`*6 zpWAH1f7`zWkIr%XZ{w-4{H%N={Fc?@=0@a?n>+OXqZ}(nMa;|_6Ml8|*zoU=A#zRV zT#)p~eTu^@?$8s^{gBh{8>S?-*)YWddK>>)`oR32%O09{D(B${l{Y#m-scd9efeheDfv0bgVZraQ#kvV|nqX5Cw#{MgAmIaETS8kQWv4xiUhp4RJSEYJ z3{~*IXTxO6unm*ro7{|d`9AsH$eF44MP5lCzCdLn!%}2eK60MQ8HFvzAVV!%tQ$Yq zY3GLKto=81@F#R}4t%Pthvxll@re14W<6-|D4A?|0G{82et_;To|-(oc{u^T)`8z!2S+fc-H2x zp`Urj7c9OlbBIpF#^~wi5APu*QHDmfE&WgFyd?jX}Ntp*3RKnnBl{h3yfhXM- zf+w*Bdt0}K4Nnn^*N>DBpnYL%_{hkzH&lbBS&iGQX@9dzV4Q3^4r+580-E@trnJ zOYXROY-DcU=y{hR^fh0t9dA@clM|3bWJoB0S_=QBUWn6l;BBhk!H7r;0f#=Mvs9G`5PMH-3Q$4t%nfP$RLDFf~im04?Sc}W4Bc;O+A(unR+f!raRJ=sZX-veSI$Q zqy$f*A8f4Kg1xQMLl#_QZ;x$=XUE@4CchxKiLJrSyc*n~7tvAdK+$~+YsRs5f-?0@ zf{&C-=yZ8>k0k;5q2Zn2JrDW?x{57kI_5WaT|3LzZRJ%{_Z(%qJxiH-WhhhcMa+>X zx)7TxGq#m=L|0;OFq;AY&b{N9%hibP?`OaN;J{6$Yuv!QS+~8cD>~G9xFg+a>Xmui z*dr@6W0*y3F_rz0v~tXXRytucFO;UvCBGT?6z8&y5}OpGGxf){WN3%Pv}GJ zDmsd@;ps4YyRo=w2X6K_aRcsT9|;yk7h>C5xY6w{YodFw!1}!wD;*cNFS~?(ml?XQ z3jF?+0NrQ5=(p^a7yOoPdeMKWiU`P4hR(>)b&WFKmZwZTvUzW*9ZxBCJeiTfcmb?F z;!4l;zbkvREfWG;s!tPZ{P;rb96pLr#e0a>zxa&#-QS3 z#!fGX&g+oh0vW>K|09t>$Yu*<)$z0v8FDUQ$423%HjX&|`4IEsiGSzxICX=+sf`=i zvku&_|D3p40skv)`V`)S*Teq?W$d(389Q#eWC$!>W(?R7@E5;Khb?~5Z6W(2Fjqwf zvnRT(&R{?2{-$tJtQT}g;l$Vm&ruFJh<8oE%?RS){)E9%)it;gUr(%QEN;4jiQocw zFH**!68L{v83MN`L%>$6p~LoLhW4+Gi||`7wwMgnw#EC=o!2^XQy6BBE)0wP1{n-c zTL+*2Y9yBXf*T9|=A1oFHRNx^<~QOdxDeip?YiF#|7GyMO&QwnPzL|kFB$xHX2tmJ z#TJXj7OSztw~V0<-U=s~hZcp!eODA_R><%h{O^K>LXEP8X<$?n_Us7uY&rg>+7_o8 zgB#Jk9XCNbZs5Jt#(RfX;QuxFe?uAl{%SS)?LKDm-8(MaZyo-1Nk9CQhwz^}D%^Y3 zBlCB!n_%KR7zc?A(4^RJp%D%l|JC@_@|{f#eat?@sYFwsg+JQkl-<`m{Eg_|?r&V+ z#@JEEjRH6D{;KF6-giQ~l*xAw^yVd#&%P|P&$|H*esV`eL?c7B+{f00M%R|%F#LCP zJlD`zHe*$LD0}P7m7`aTNpEWGoic(r^$u~W+8(F=6Wl0pBf3{c-`&Eyf_D|;^OiNn zd;if`?{~(>wmaA?Z*=&0`2QGEYsMQm2gZvG7oaf>@$C59)|qRYY@N9}aqG-g)|aPc zUnrcEo>4M2-9NH>hPSC_W)lA9CtIAV?Qd%1hCSPHlN~o((S04<)YAQ4;a$aezpY}u z%T;WkGZmRV-CBD0!zi9++?7Dv&{^8yG9r!<>%W0$Me)@5DV)6vk)ctz**0sf-?mw6_QSs_oxVyHPhBefJLn=mXOuja=5Oeh z=SQ4cNZk2JKa(}=Z@_(h+&FZ<-_HBH@cy1Mw>_ld+P<&iygs-T=Xq?Y`PP#GyW+<; z>fW+#_WCC9p9oozL2aG6MwQK2tu{@|cG$sTi?<5H(gQ|mWp11i9>U)oAWl{5zWzVM z4Z0WJ4?>59cj%~!_dI4z@H%lc!TY07i|?n+9QeN3xP5lPgWG1WI|u*DM#!Mcfi0fO zt8I%SaHZd;WG+*eLSKA+GI8p>4LA6D7yia*^EWrcjh%PV{So0^#e4ltCA9lcS$saO zO!WWz(xeWb-4sLHXRp5n{$GO>GQhu($WbGM-4>s)5A^#~MC;Pl;jK3(LXSlHZfR!h zxcNci)O*CKYFnHVU;l68#;*J0DxvKOc>hQx`hBXB+Mlu}1%7^XVW%%clY=X6um$|P zL!t106tdn#hF{nh(;W7L?`OkXZ~7Iw$j|BFw{Gz>cHHKRzga|_I&Y6tH~JeNr@y%w zZWOpt3En4_#rG4H*#4AC3iyXw*zpUM-1)1@lrCQ{U3A;GE^UDf9pOILKFPLE=>Pjks~_S>4~*_Ns72kru`cTV{gKq3XU3)V{;5uGP;`q7&EUVr7B(z>1fKNlJA11Y zR4h1+@jRd++q?$pUHo>FK2{Q;?xC`&%g9HH^YqrHwxUSQ-=)jJqY>=dK(%JInS&3 zu~zuA67g%uVe@hLIfoqtPcCfnQ$*`6_sRV8+&^@WX?tK4aq2K}%4&~Ob#deE^fwLR zM!|bdM&Ao{un(`dK-(dFs7`M%-s+GIKlThVTuo?qQuhzFWdKihIgT*a*aF@cN3GnzKQqhXJ zO2mhWUc?_uOp(|k>(-aSZj1BicC=&u4O13}6g;}w;(iyMn0Cxxe}s2uy#Sx}41V{T_}_({zR>3v9f__i zz8~xULbpY&J%J3V=C()l^DcJ?pVH~MdpABVXTem?!s%-BliAiSPh}t2GJW~&6E)QY zn~ue{AD|zrJx&zF(yqVa#QsR^oH@AzwId>Y~ z>-b8UzoAchp9{C(r#7YHYsKe^@0Iw$`9qI|H{uCfwEOUUyw{0Qj(NEQ4d)(r1{pZZ z=5Zz$%7s>3D4m{jL!JlSH$_L|Smy}qS?##F3Lnop=4|XpZ196#0drMpy^sM6ivO*# zMSVQ|-3ks;@k@5xYSfe94TS}bz8Q#~Ud*^w#vHZ(( z@ZT1S=Kb%9*T`^2rFO>_;8NnD#B}i!c3Zp$hIQP?yPTEAKo^lgmDQEu5d1rFBhR|} zuvRm0^8ow@yZU=$zf13X!3`OPBEv4``b}bYY7cB-$CF@{y?q|rJ8>g(%UKT!gHGr& z*lchCJKTVq#`5xep0nG+P}>%EJXx{DBKDq3Jivc2{O3ZK!4bI0bNSrw;jOXnX7s!0 zu*Gg{`O;lz!rx!@gJtbPz`@HtoS{t@5lw&?wn0X%)o-mZh2KVrQBC)m_Gj!&Z&aI&@)`mY``>p4v4ngwaDY z%6QGq5+UDLY84goT%|TZA1ky@dl@S=txXW) zHBEEBFNF1IU%J+r^%26zSY57ZL-_vMEKR#r#vz*Kk-&SLG-aI%4<6J~2s!Cx^(=J!Q0^`>eu)y<|%iS($RQ{F4{eaBF zm{=~O=8;&z{8r7={aS*IZQQFEl_khSDaP^;PkpQm$N7*=SNK+XE~Hi|{X5bt zAvH{7x(*Me=%T&j`T8TedW1Uv1$jq$PN;SM$eam@_rwHjd^}}hVOYY?`QxHFZ=3Bs z6qc*3pLoD%ax?Zx_M)z`(|ngv?>BJt;K)4EYa%sZ=6(wvyz8$kzw>>7U`C!3z86vB zrd}pB=W6Or`xEX;9GyST@EH9AC#9ET4ZR$NVewb6!%TUf8bTCx@2Z&o3A|&{Ywgm1 zBDHdz6R=a)QZj-??{cyyg&Aym181S z!pD_WV*?YeC-hG)8FYebG`0Q?*cV{d0+ZRutzn$D(0d|t}%$-N1>bZ4!w*0 zq~AfWFG~-EUL#DAdc4$0-ZJ-EI*LAoP_Wwd&t6$=BLZ@F>2=E6sC!GjSb8X=4}^E6 z2ZXuyVvn2YUGV;{Q}6VL2+#7KUgwj#d>?uWq_!&k1X5S+zT%vr>*_dT@CGmHbEBwp zRo2ve^YxmsUeBSAgI<&~^oF?9yVwD}N2B-ab@WdEkls&X(>rU^4thDtZH-?8yoWEP4_;s2ch?LaC)%;z1wQ=dM!WK zUdNX@IJMYL8_yX#mYT!;^Y4KNspbEo>mrDHdAC(>8oOtEZ+zU?iW-@-mR28s$lesc zF$TTAkKU~}*E@B+Zc@vZ+6?tbsijJ7AfT+;&|$~EX#ZCqw(H^(`Z~^n3tjKjxaLx8 zJOK~WAc>?dKe2a32bk_OrGxj2dTrFT-tBcEsi8{^nmVYS*ME(i^3HQ6zddGZpZC7t zmpR5u+v7&h%-!oI7{AtQonhuHtiKo{NZ%}?fai|wB{4*VX*c2*rnuJw-W zQpc3~vD7f7{;Jn6tEr#uBd2$NM&H7w)ccl8%@Q7@-d7DDaqA{TyTk+M;BlqXSDq@F zy2O}vZ)zW7&&BCrs8a8NaIJS+9Z#>HO8rr4r;^jvbLr>EDJEnNS~7Ii*oalsuCGw9 z+Y1ja_aS-kK<*UpZ+ap}>Oob|o`OfyL#Qc+Qj`0Deh{mz9_Lc;$Zo5B+G>a7!rMvh z>R>hbs(lu}_eSEU!-}VxUFHhN%QPjAy;$lZQV)6g@#WN|(}j<-g<)xb2FHQ;xJ>X~ zY3rMCsdrlq$J>^Nch=3QJCXM|8}E5CHqP^Nm$H+`9Y<}W(pj6K&bQ^MTw=_UtLrDF z;op^8gy-hY;C(!J{{Xzx^FaO7sdtgxsdr?j20-1*mJ6lkMQ+vNeX@#s^xH`RpNDWa zt&^)Fw?7dcPTT4$HT5Cxb?f#TEX}B)+(#YaLvr7yNWU$84FTITsijof>dr3p&iYbw zBai7t%}4508I0G4?+P&5fy=Q^0;-+Hf3F?HHU)tW8hut%r?DC{|IY?)1M0BwmU6j2w_m<7xue=cDk=kQN?^v(HSyCgGT&u0lcZ1&b90@s} zFOa>ztRo-R^nm6=2cZG-9l2=(^}#B^jpWvC`CRIsHM;mA#`E3#>?<$zE zcm!)t51rb9nb>J?|>@wHm$Wqj%?-RpzMufj4ik zxm(YL@t)*WrPh_$UUI5>E>d){C$`mzwy*rpiZa`c* zMHD`ws#XqhFFDXUK8_qxXXeQzKlU~AI%^O0*LD1E&mWA0j|1$HYT;XQzLFCpPhL$f zTi5%x*{fR+FIL0DZ}vPU`Pe*{=PcH4L0+hjtGcFR-TEUo@`r~M-aD`7SS7F5x)edbZ+ zp6PMT-P7}$hv)jLHl3B#bH7sSZ7cVLc~M+2{cjx~TwCDeOL>Es^4CPM!XYSLw--+&TaHp?7BYPx0;*W&C%$=~$`iV9F--mlr z7w+{(xXF&gw+))b=b9Rk45Z0_@yUV*=vLtlm$>o;YNk(^ETZkUb4NyxeX;aaos_smPewI9BQA5`FV6EOzIYz7uv+S# zQnO8H_fhGF@g>9X-4(>He-c0YCitEXhVONpQ?}uE>co@uK0kHFCub8EE_04NZSnuI z|MsWz`ccm+Cl0;jur)HbWbHcdI{t=VZH`Pc@Tt!@zQcd|Ku)|lzITjzZu79Fy?=n% pn#%bIlKg3TAURl8N#j { + const jestMatchersObject = Object.create(null); + Object.keys(jasmineMatchersObject).forEach(name => { + jestMatchersObject[name] = function() { + const result = jasmineMatchersObject[name](jasmine.matchersUtil, null); + // if there is no 'negativeCompare', both should be handled by `compare` + const negativeCompare = result.negativeCompare || result.compare; + + return this.isNot + ? negativeCompare.apply(null, arguments) + : result.compare.apply(null, arguments); + }; + }); + + const expect = global.expect; + expect.extend(jestMatchersObject); + }; +} \ No newline at end of file diff --git a/content/app/test/karma.conf.js b/content/app/test/karma.conf.js new file mode 100644 index 0000000..4fd9bea --- /dev/null +++ b/content/app/test/karma.conf.js @@ -0,0 +1,82 @@ +'use strict'; +const path = require('path'); + +module.exports = function (config) { + config.set({ + /** + * base path that will be used to resolve all patterns (e.g. files, exclude) + */ + basePath: path.dirname(__dirname), + + /** + * Frameworks to use + * + * available frameworks: https://npmjs.org/browse/keyword/karma-adapter + */ + frameworks: [ 'jasmine' ], + + /** + * list of files / patterns to load in the browser + * we are building the test environment in ./spec-bundle.js + */ + files: [ + { pattern: 'test/karma-bundle.js', watched: false } + ], + + /* + * preprocess matching files before serving them to the browser + * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + */ + preprocessors: { + 'test/karma-bundle.js': [ 'webpack' ] + }, + + webpack: require('../webpack.config')({ coverage: true, karma: true }), + + /* + * test results reporter to use + * + * possible values: 'dots', 'progress' + * available reporters: https://npmjs.org/browse/keyword/karma-reporter + */ + reporters: [ 'mocha', 'progress', 'coverage' ], + + coverageReporter: { + reporters: [ { type: 'html' }, { type: 'lcovonly' }, { type: 'text-summary' } ], + dir: path.resolve(__dirname, 'coverage-karma'), + subdir: '.', + }, + + // Webpack please don't spam the console when running in karma! + webpackServer: { noInfo: true }, + + // web server port + port: 9876, + + // enable / disable colors in the output (reporters and logs) + colors: true, + + /* + * level of logging + * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + */ + logLevel: config.LOG_INFO, + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + /* + * start these browsers + * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + */ + browsers: [ + 'Chrome', + ], + + /* + * Continuous Integration mode + * if true, Karma captures browsers, runs the tests and exits + */ + singleRun: true + }) +} \ No newline at end of file diff --git a/content/app/test/unit/.eslintrc b/content/app/test/unit/.eslintrc new file mode 100644 index 0000000..9262967 --- /dev/null +++ b/content/app/test/unit/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "no-var": 0 + } +} diff --git a/content/app/test/unit/app.spec.js b/content/app/test/unit/app.spec.js new file mode 100644 index 0000000..500fdb5 --- /dev/null +++ b/content/app/test/unit/app.spec.js @@ -0,0 +1,7 @@ +import {App} from '../../src/app'; + +describe('the app', () => { + it('says hello', () => { + expect(new App().message).toBe('Hello World!'); + }); +}); diff --git a/content/app/webpack.config.js b/content/app/webpack.config.js new file mode 100644 index 0000000..484fe20 --- /dev/null +++ b/content/app/webpack.config.js @@ -0,0 +1,116 @@ +const path = require('path'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const CopyWebpackPlugin = require('copy-webpack-plugin'); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); +const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin'); +const project = require('./aurelia_project/aurelia.json'); +const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin'); +const { ProvidePlugin } = require('webpack'); +const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); + +// config helpers: +const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []; +const when = (condition, config, negativeConfig) => + condition ? ensureArray(config) : ensureArray(negativeConfig); + +// primary config: +const title = 'Aurelia Navigation Skeleton'; +const outDir = path.resolve(__dirname, project.platform.output); +const srcDir = path.resolve(__dirname, 'src'); +const nodeModulesDir = path.resolve(__dirname, 'node_modules'); +const baseUrl = '/'; + +const cssRules = [ + { loader: 'css-loader' }, +]; + +module.exports = ({production, server, extractCss, coverage, analyze, karma} = {}) => ({ + resolve: { + extensions: ['.js'], + modules: [srcDir, 'node_modules'], + // Enforce single aurelia-binding, to avoid v1/v2 duplication due to + // out-of-date dependencies on 3rd party aurelia plugins + alias: { 'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding') } + }, + entry: { + app: ['aurelia-bootstrapper'], + vendor: ['bluebird'], + }, + mode: production ? 'production' : 'development', + output: { + path: outDir, + publicPath: baseUrl, + filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js', + sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map', + chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js' + }, + performance: { hints: false }, + devServer: { + contentBase: outDir, + // serve index.html for all 404 (required for push-state) + historyApiFallback: true + }, + devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map', + module: { + rules: [ + // CSS required in JS/TS files should use the style-loader that auto-injects it into the website + // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates + { + test: /\.css$/i, + issuer: [{ not: [{ test: /\.html$/i }] }], + use: extractCss ? [{ + loader: MiniCssExtractPlugin.loader + }, + 'css-loader' + ] : ['style-loader', ...cssRules] + }, + { + test: /\.css$/i, + issuer: [{ test: /\.html$/i }], + // CSS required in templates cannot be extracted safely + // because Aurelia would try to require it again in runtime + use: cssRules + }, + { test: /\.html$/i, loader: 'html-loader' }, + { test: /\.js$/i, loader: 'babel-loader', exclude: nodeModulesDir, + options: coverage ? { sourceMap: 'inline', plugins: [ 'istanbul' ] } : {}, + }, + // use Bluebird as the global Promise implementation: + { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' }, + // embed small images and fonts as Data Urls and larger ones as files: + { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } }, + { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } }, + { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } }, + // load these fonts normally, as files: + { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' }, + ] + }, + plugins: [ + ...when(!karma, new DuplicatePackageCheckerPlugin()), + new AureliaPlugin(), + new ProvidePlugin({ + 'Promise': 'bluebird' + }), + new ModuleDependenciesPlugin({ + 'aurelia-testing': [ './compile-spy', './view-spy' ] + }), + new HtmlWebpackPlugin({ + template: 'index.ejs', + minify: production ? { + removeComments: true, + collapseWhitespace: true + } : undefined, + metadata: { + // available in index.ejs // + title, server, baseUrl + } + }), + ...when(extractCss, new MiniCssExtractPlugin({ + filename: production ? '[contenthash].css' : '[id].css', + allChunks: true + })), + ...when(production || server, new CopyWebpackPlugin([ + { from: 'static', to: outDir }])), + ...when(analyze, new BundleAnalyzerPlugin()) + ] +}); From b8644b9ad2777b6a9295a28de760d55a53d92851 Mon Sep 17 00:00:00 2001 From: Robert Waggott Date: Tue, 4 Sep 2018 22:01:18 +0100 Subject: [PATCH 02/76] -- initial setup --- .babelrc | 17 + app.js | 10 +- aurelia_project/aurelia.json | 154 + .../environments/dev.js | 0 .../environments/prod.js | 0 .../environments/stage.js | 0 .../generators/attribute.js | 0 .../generators/attribute.json | 0 .../generators/binding-behavior.js | 0 .../generators/binding-behavior.json | 0 .../generators/component.js | 0 .../generators/component.json | 0 .../generators/element.js | 0 .../generators/element.json | 0 .../generators/generator.js | 0 .../generators/generator.json | 0 .../generators/task.js | 0 .../generators/task.json | 0 .../generators/value-converter.js | 0 .../generators/value-converter.json | 0 aurelia_project/tasks/build.js | 40 + .../tasks/build.json | 0 aurelia_project/tasks/copy-files.js | 45 + aurelia_project/tasks/lint.js | 10 + aurelia_project/tasks/process-css.js | 10 + aurelia_project/tasks/process-markup.js | 10 + aurelia_project/tasks/run.js | 48 + .../tasks/run.json | 9 +- aurelia_project/tasks/transpile.js | 32 + aurelia_project/tasks/watch.js | 128 + content/app/.babelrc | 5 - content/app/.babelrc.js | 27 - content/app/.editorconfig | 12 - content/app/.eslintrc.json | 3 - content/app/.gitignore | 31 - content/app/.vscode/extensions.json | 10 - content/app/.vscode/launch.json | 19 - content/app/.vscode/settings.json | 6 - content/app/aurelia_project/aurelia.json | 78 - content/app/aurelia_project/tasks/build.js | 58 - .../app/aurelia_project/tasks/environment.js | 24 - content/app/aurelia_project/tasks/jest.js | 23 - content/app/aurelia_project/tasks/jest.json | 11 - content/app/aurelia_project/tasks/karma.js | 16 - content/app/aurelia_project/tasks/karma.json | 11 - content/app/aurelia_project/tasks/run.js | 46 - content/app/favicon.ico | Bin 15086 -> 0 bytes content/app/index.ejs | 16 - content/app/jsconfig.json | 11 - content/app/package-scripts.js | 79 - content/app/package.json | 119 - content/app/src/app.html | 7 - content/app/src/main.js | 30 - content/app/static/favicon.ico | Bin 15086 -> 0 bytes content/app/test/jest-pretest.js | 6 - content/app/test/karma-bundle.js | 80 - content/app/test/karma.conf.js | 82 - content/app/test/unit/.eslintrc | 5 - content/app/test/unit/app.spec.js | 7 - content/app/webpack.config.js | 116 - content/dist/app-bundle.js | 107 + content/dist/app-bundle.js.map | 1 + content/dist/vendor-bundle.js | 28489 ++++++++++++++++ package.json | 38 +- routes.js | 100 +- src/app.html | 7 + {content/app/src => src}/app.js | 8 +- {content/app/src => src}/environment.js | 0 src/main.js | 17 + {content/app/src => src}/resources/index.js | 0 {content/app/src => src}/welcome/welcome.html | 0 {content/app/src => src}/welcome/welcome.js | 4 +- views/aurelia.hbs | 12 + 73 files changed, 29229 insertions(+), 1005 deletions(-) create mode 100644 .babelrc create mode 100644 aurelia_project/aurelia.json rename {content/app/aurelia_project => aurelia_project}/environments/dev.js (100%) rename {content/app/aurelia_project => aurelia_project}/environments/prod.js (100%) rename {content/app/aurelia_project => aurelia_project}/environments/stage.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/attribute.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/attribute.json (100%) rename {content/app/aurelia_project => aurelia_project}/generators/binding-behavior.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/binding-behavior.json (100%) rename {content/app/aurelia_project => aurelia_project}/generators/component.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/component.json (100%) rename {content/app/aurelia_project => aurelia_project}/generators/element.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/element.json (100%) rename {content/app/aurelia_project => aurelia_project}/generators/generator.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/generator.json (100%) rename {content/app/aurelia_project => aurelia_project}/generators/task.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/task.json (100%) rename {content/app/aurelia_project => aurelia_project}/generators/value-converter.js (100%) rename {content/app/aurelia_project => aurelia_project}/generators/value-converter.json (100%) create mode 100644 aurelia_project/tasks/build.js rename {content/app/aurelia_project => aurelia_project}/tasks/build.json (100%) create mode 100644 aurelia_project/tasks/copy-files.js create mode 100644 aurelia_project/tasks/lint.js create mode 100644 aurelia_project/tasks/process-css.js create mode 100644 aurelia_project/tasks/process-markup.js create mode 100644 aurelia_project/tasks/run.js rename {content/app/aurelia_project => aurelia_project}/tasks/run.json (58%) create mode 100644 aurelia_project/tasks/transpile.js create mode 100644 aurelia_project/tasks/watch.js delete mode 100644 content/app/.babelrc delete mode 100644 content/app/.babelrc.js delete mode 100644 content/app/.editorconfig delete mode 100644 content/app/.eslintrc.json delete mode 100644 content/app/.gitignore delete mode 100644 content/app/.vscode/extensions.json delete mode 100644 content/app/.vscode/launch.json delete mode 100644 content/app/.vscode/settings.json delete mode 100644 content/app/aurelia_project/aurelia.json delete mode 100644 content/app/aurelia_project/tasks/build.js delete mode 100644 content/app/aurelia_project/tasks/environment.js delete mode 100644 content/app/aurelia_project/tasks/jest.js delete mode 100644 content/app/aurelia_project/tasks/jest.json delete mode 100644 content/app/aurelia_project/tasks/karma.js delete mode 100644 content/app/aurelia_project/tasks/karma.json delete mode 100644 content/app/aurelia_project/tasks/run.js delete mode 100644 content/app/favicon.ico delete mode 100644 content/app/index.ejs delete mode 100644 content/app/jsconfig.json delete mode 100644 content/app/package-scripts.js delete mode 100644 content/app/package.json delete mode 100644 content/app/src/app.html delete mode 100644 content/app/src/main.js delete mode 100644 content/app/static/favicon.ico delete mode 100644 content/app/test/jest-pretest.js delete mode 100644 content/app/test/karma-bundle.js delete mode 100644 content/app/test/karma.conf.js delete mode 100644 content/app/test/unit/.eslintrc delete mode 100644 content/app/test/unit/app.spec.js delete mode 100644 content/app/webpack.config.js create mode 100644 content/dist/app-bundle.js create mode 100644 content/dist/app-bundle.js.map create mode 100644 content/dist/vendor-bundle.js create mode 100644 src/app.html rename {content/app/src => src}/app.js (69%) rename {content/app/src => src}/environment.js (100%) create mode 100644 src/main.js rename {content/app/src => src}/resources/index.js (100%) rename {content/app/src => src}/welcome/welcome.html (100%) rename {content/app/src => src}/welcome/welcome.js (73%) create mode 100644 views/aurelia.hbs diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..2b0041b --- /dev/null +++ b/.babelrc @@ -0,0 +1,17 @@ +{ + "sourceMap": true, + "sourceRoot": "src", + "moduleIds": false, + "comments": false, + "compact": false, + "code": true, + "presets": [ + ["es2015", {"loose": true}], + "stage-1" + ], + "plugins": [ + "syntax-flow", + "transform-decorators-legacy", + "transform-flow-strip-types" + ] +} diff --git a/app.js b/app.js index 9675d55..da00a68 100644 --- a/app.js +++ b/app.js @@ -2,6 +2,7 @@ const Koa = require("koa"); const Router = require("koa-router"); const Helmet = require("koa-helmet"); const Serve = require("koa-static"); +const Mount = require("koa-mount"); const HandlebarsRenderer = require("koa-hbs-renderer"); const Handlebars = require("handlebars"); const BodyParser = require("koa-bodyparser"); @@ -82,14 +83,15 @@ app hbs: Handlebars, paths: { views: path.join(__dirname, "views"), - layouts: path.join(__dirname, "views", "layouts"), - helpers: path.join(__dirname, "helpers"), - partials: path.join(__dirname, "views", "partials") + //layouts: path.join(__dirname, "views", "layouts"), + //helpers: path.join(__dirname, "helpers"), + //partials: path.join(__dirname, "views", "partials") } })) .use(Helmet()) .use(BodyParser()) - .use(Serve("./content")) + .use(Mount("/content", Serve("./content"))) + //.use(Serve("./content")) .use(router.routes()) .use(router.allowedMethods()); diff --git a/aurelia_project/aurelia.json b/aurelia_project/aurelia.json new file mode 100644 index 0000000..28d87df --- /dev/null +++ b/aurelia_project/aurelia.json @@ -0,0 +1,154 @@ +{ + "name": "aurelia-app", + "type": "project:application", + "bundler": { + "id": "cli", + "displayName": "Aurelia-CLI" + }, + "build": { + "targets": [ + { + "id": "web", + "displayName": "Web", + "port": 9000, + "baseDir": ".", + "output": "content/dist" + } + ], + "options": { + "minify": "stage & prod", + "sourcemaps": "dev & stage" + }, + "bundles": [ + { + "name": "app-bundle.js", + "source": [ + "[**/*.js]", + "**/*.{css,html}" + ] + }, + { + "name": "vendor-bundle.js", + "prepend": [ + "node_modules/bluebird/js/browser/bluebird.core.js", + { + "path": "node_modules/aurelia-cli/lib/resources/scripts/configure-bluebird-no-long-stacktraces.js", + "env": "stage & prod" + }, + { + "path": "node_modules/aurelia-cli/lib/resources/scripts/configure-bluebird.js", + "env": "dev" + }, + "node_modules/requirejs/require.js" + ], + "dependencies": [ + "aurelia-binding", + "aurelia-bootstrapper", + "aurelia-dependency-injection", + "aurelia-event-aggregator", + "aurelia-framework", + "aurelia-history", + "aurelia-history-browser", + "aurelia-loader", + "aurelia-loader-default", + "aurelia-logging", + "aurelia-logging-console", + "aurelia-metadata", + "aurelia-pal", + "aurelia-pal-browser", + "aurelia-path", + "aurelia-polyfills", + "aurelia-route-recognizer", + "aurelia-router", + "aurelia-task-queue", + "aurelia-templating", + "aurelia-templating-binding", + { + "name": "aurelia-templating-resources", + "path": "../node_modules/aurelia-templating-resources/dist/amd", + "main": "aurelia-templating-resources" + }, + { + "name": "aurelia-templating-router", + "path": "../node_modules/aurelia-templating-router/dist/amd", + "main": "aurelia-templating-router" + }, + { + "name": "aurelia-testing", + "path": "../node_modules/aurelia-testing/dist/amd", + "main": "aurelia-testing", + "env": "dev" + }, + "text" + ] + } + ], + "loader": { + "type": "require", + "configTarget": "vendor-bundle.js", + "includeBundleMetadataInConfig": "auto", + "plugins": [ + { + "name": "text", + "extensions": [ + ".html", + ".css" + ], + "stub": true + } + ] + } + }, + "platform": { + "id": "web", + "displayName": "Web", + "port": 9000, + "baseDir": ".", + "output": "content/dist" + }, + "transpiler": { + "id": "babel", + "displayName": "Babel", + "fileExtension": ".js", + "options": { + "plugins": [ + "transform-es2015-modules-amd" + ] + }, + "source": "src/**/*.js" + }, + "markupProcessor": { + "id": "none", + "displayName": "None", + "fileExtension": ".html", + "source": "src/**/*.html" + }, + "cssProcessor": { + "id": "none", + "displayName": "None", + "fileExtension": ".css", + "source": "src/**/*.css" + }, + "editor": { + "id": "none", + "displayName": "None" + }, + "unitTestRunners": [ + { + "id": "none", + "displayName": "None" + } + ], + "integrationTestRunner": { + "id": "none", + "displayName": "None" + }, + "paths": { + "root": "src", + "resources": "resources", + "elements": "resources/elements", + "attributes": "resources/attributes", + "valueConverters": "resources/value-converters", + "bindingBehaviors": "resources/binding-behaviors" + } +} \ No newline at end of file diff --git a/content/app/aurelia_project/environments/dev.js b/aurelia_project/environments/dev.js similarity index 100% rename from content/app/aurelia_project/environments/dev.js rename to aurelia_project/environments/dev.js diff --git a/content/app/aurelia_project/environments/prod.js b/aurelia_project/environments/prod.js similarity index 100% rename from content/app/aurelia_project/environments/prod.js rename to aurelia_project/environments/prod.js diff --git a/content/app/aurelia_project/environments/stage.js b/aurelia_project/environments/stage.js similarity index 100% rename from content/app/aurelia_project/environments/stage.js rename to aurelia_project/environments/stage.js diff --git a/content/app/aurelia_project/generators/attribute.js b/aurelia_project/generators/attribute.js similarity index 100% rename from content/app/aurelia_project/generators/attribute.js rename to aurelia_project/generators/attribute.js diff --git a/content/app/aurelia_project/generators/attribute.json b/aurelia_project/generators/attribute.json similarity index 100% rename from content/app/aurelia_project/generators/attribute.json rename to aurelia_project/generators/attribute.json diff --git a/content/app/aurelia_project/generators/binding-behavior.js b/aurelia_project/generators/binding-behavior.js similarity index 100% rename from content/app/aurelia_project/generators/binding-behavior.js rename to aurelia_project/generators/binding-behavior.js diff --git a/content/app/aurelia_project/generators/binding-behavior.json b/aurelia_project/generators/binding-behavior.json similarity index 100% rename from content/app/aurelia_project/generators/binding-behavior.json rename to aurelia_project/generators/binding-behavior.json diff --git a/content/app/aurelia_project/generators/component.js b/aurelia_project/generators/component.js similarity index 100% rename from content/app/aurelia_project/generators/component.js rename to aurelia_project/generators/component.js diff --git a/content/app/aurelia_project/generators/component.json b/aurelia_project/generators/component.json similarity index 100% rename from content/app/aurelia_project/generators/component.json rename to aurelia_project/generators/component.json diff --git a/content/app/aurelia_project/generators/element.js b/aurelia_project/generators/element.js similarity index 100% rename from content/app/aurelia_project/generators/element.js rename to aurelia_project/generators/element.js diff --git a/content/app/aurelia_project/generators/element.json b/aurelia_project/generators/element.json similarity index 100% rename from content/app/aurelia_project/generators/element.json rename to aurelia_project/generators/element.json diff --git a/content/app/aurelia_project/generators/generator.js b/aurelia_project/generators/generator.js similarity index 100% rename from content/app/aurelia_project/generators/generator.js rename to aurelia_project/generators/generator.js diff --git a/content/app/aurelia_project/generators/generator.json b/aurelia_project/generators/generator.json similarity index 100% rename from content/app/aurelia_project/generators/generator.json rename to aurelia_project/generators/generator.json diff --git a/content/app/aurelia_project/generators/task.js b/aurelia_project/generators/task.js similarity index 100% rename from content/app/aurelia_project/generators/task.js rename to aurelia_project/generators/task.js diff --git a/content/app/aurelia_project/generators/task.json b/aurelia_project/generators/task.json similarity index 100% rename from content/app/aurelia_project/generators/task.json rename to aurelia_project/generators/task.json diff --git a/content/app/aurelia_project/generators/value-converter.js b/aurelia_project/generators/value-converter.js similarity index 100% rename from content/app/aurelia_project/generators/value-converter.js rename to aurelia_project/generators/value-converter.js diff --git a/content/app/aurelia_project/generators/value-converter.json b/aurelia_project/generators/value-converter.json similarity index 100% rename from content/app/aurelia_project/generators/value-converter.json rename to aurelia_project/generators/value-converter.json diff --git a/aurelia_project/tasks/build.js b/aurelia_project/tasks/build.js new file mode 100644 index 0000000..a1ea539 --- /dev/null +++ b/aurelia_project/tasks/build.js @@ -0,0 +1,40 @@ +import gulp from 'gulp'; +import {CLIOptions, build as buildCLI} from 'aurelia-cli'; +import transpile from './transpile'; +import processMarkup from './process-markup'; +import processCSS from './process-css'; +import copyFiles from './copy-files'; +import watch from './watch'; +import project from '../aurelia.json'; + +let build = gulp.series( + readProjectConfiguration, + gulp.parallel( + transpile, + processMarkup, + processCSS, + copyFiles + ), + writeBundles +); + +let main; + +if (CLIOptions.taskName() === 'build' && CLIOptions.hasFlag('watch')) { + main = gulp.series( + build, + (done) => { watch(); done(); } + ); +} else { + main = build; +} + +function readProjectConfiguration() { + return buildCLI.src(project); +} + +function writeBundles() { + return buildCLI.dest(); +} + +export { main as default }; diff --git a/content/app/aurelia_project/tasks/build.json b/aurelia_project/tasks/build.json similarity index 100% rename from content/app/aurelia_project/tasks/build.json rename to aurelia_project/tasks/build.json diff --git a/aurelia_project/tasks/copy-files.js b/aurelia_project/tasks/copy-files.js new file mode 100644 index 0000000..61a24d1 --- /dev/null +++ b/aurelia_project/tasks/copy-files.js @@ -0,0 +1,45 @@ +import gulp from 'gulp'; +import path from 'path'; +import minimatch from 'minimatch'; +import changedInPlace from 'gulp-changed-in-place'; +import project from '../aurelia.json'; + +export default function copyFiles(done) { + if (typeof project.build.copyFiles !== 'object') { + done(); + return; + } + + const instruction = getNormalizedInstruction(); + const files = Object.keys(instruction); + + return gulp.src(files) + .pipe(changedInPlace({ firstPass: true })) + .pipe(gulp.dest(x => { + const filePath = prepareFilePath(x.path); + const key = files.find(f => minimatch(filePath, f)); + return instruction[key]; + })); +} + +function getNormalizedInstruction() { + const files = project.build.copyFiles; + let normalizedInstruction = {}; + + for (let key in files) { + normalizedInstruction[path.posix.normalize(key)] = files[key]; + } + + return normalizedInstruction; +} + +function prepareFilePath(filePath) { + let preparedPath = filePath.replace(process.cwd(), '').substring(1); + + //if we are running on windows we have to fix the path + if (/^win/.test(process.platform)) { + preparedPath = preparedPath.replace(/\\/g, '/'); + } + + return preparedPath; +} diff --git a/aurelia_project/tasks/lint.js b/aurelia_project/tasks/lint.js new file mode 100644 index 0000000..e5d5f9d --- /dev/null +++ b/aurelia_project/tasks/lint.js @@ -0,0 +1,10 @@ +import gulp from 'gulp'; +import eslint from 'gulp-eslint'; +import project from '../aurelia.json'; + +export default function lint() { + return gulp.src([project.transpiler.source]) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +} diff --git a/aurelia_project/tasks/process-css.js b/aurelia_project/tasks/process-css.js new file mode 100644 index 0000000..5557344 --- /dev/null +++ b/aurelia_project/tasks/process-css.js @@ -0,0 +1,10 @@ +import gulp from 'gulp'; +import changedInPlace from 'gulp-changed-in-place'; +import project from '../aurelia.json'; +import {build} from 'aurelia-cli'; + +export default function processCSS() { + return gulp.src(project.cssProcessor.source) + .pipe(changedInPlace({firstPass: true})) + .pipe(build.bundle()); +} diff --git a/aurelia_project/tasks/process-markup.js b/aurelia_project/tasks/process-markup.js new file mode 100644 index 0000000..ad4f2ac --- /dev/null +++ b/aurelia_project/tasks/process-markup.js @@ -0,0 +1,10 @@ +import gulp from 'gulp'; +import changedInPlace from 'gulp-changed-in-place'; +import project from '../aurelia.json'; +import {build} from 'aurelia-cli'; + +export default function processMarkup() { + return gulp.src(project.markupProcessor.source) + .pipe(changedInPlace({firstPass: true})) + .pipe(build.bundle()); +} diff --git a/aurelia_project/tasks/run.js b/aurelia_project/tasks/run.js new file mode 100644 index 0000000..269b071 --- /dev/null +++ b/aurelia_project/tasks/run.js @@ -0,0 +1,48 @@ +import gulp from 'gulp'; +import browserSync from 'browser-sync'; +import historyApiFallback from 'connect-history-api-fallback/lib'; +import {CLIOptions} from 'aurelia-cli'; +import project from '../aurelia.json'; +import build from './build'; +import watch from './watch'; + +let serve = gulp.series( + build, + done => { + browserSync({ + online: false, + open: CLIOptions.hasFlag('open'), + port: project.platform.port, + logLevel: 'silent', + server: { + baseDir: [project.platform.baseDir], + middleware: [historyApiFallback(), function(req, res, next) { + res.setHeader('Access-Control-Allow-Origin', '*'); + next(); + }] + } + }, function (err, bs) { + if (err) return done(err); + let urls = bs.options.get('urls').toJS(); + log(`Application Available At: ${urls.local}`); + log(`BrowserSync Available At: ${urls.ui}`); + done(); + }); + } +); + +function log(message) { + console.log(message); //eslint-disable-line no-console +} + +function reload() { + log('Refreshing the browser'); + browserSync.reload(); +} + +let run = gulp.series( + serve, + done => { watch(reload); done(); } +); + +export default run; diff --git a/content/app/aurelia_project/tasks/run.json b/aurelia_project/tasks/run.json similarity index 58% rename from content/app/aurelia_project/tasks/run.json rename to aurelia_project/tasks/run.json index 7ddfcfb..2539235 100644 --- a/content/app/aurelia_project/tasks/run.json +++ b/aurelia_project/tasks/run.json @@ -2,19 +2,14 @@ "name": "run", "description": "Builds the application and serves up the assets via a local web server, watching files for changes as you work.", "flags": [ - { - "name": "analyze", - "description": "Enable Webpack Bundle Analyzer. Typically paired with --env prod", - "type": "boolean" - }, { "name": "env", "description": "Sets the build environment.", "type": "string" }, { - "name": "hmr", - "description": "Enable Hot Module Reload", + "name": "open", + "description": "Open the default browser at the application location.", "type": "boolean" } ] diff --git a/aurelia_project/tasks/transpile.js b/aurelia_project/tasks/transpile.js new file mode 100644 index 0000000..3c5df73 --- /dev/null +++ b/aurelia_project/tasks/transpile.js @@ -0,0 +1,32 @@ +import gulp from 'gulp'; +import changedInPlace from 'gulp-changed-in-place'; +import plumber from 'gulp-plumber'; +import babel from 'gulp-babel'; +import sourcemaps from 'gulp-sourcemaps'; +import notify from 'gulp-notify'; +import rename from 'gulp-rename'; +import project from '../aurelia.json'; +import {CLIOptions, build} from 'aurelia-cli'; + +function configureEnvironment() { + let env = CLIOptions.getEnvironment(); + + return gulp.src(`aurelia_project/environments/${env}.js`) + .pipe(changedInPlace({firstPass: true})) + .pipe(rename('environment.js')) + .pipe(gulp.dest(project.paths.root)); +} + +function buildJavaScript() { + return gulp.src(project.transpiler.source) + .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) + .pipe(changedInPlace({firstPass: true})) + .pipe(sourcemaps.init()) + .pipe(babel(project.transpiler.options)) + .pipe(build.bundle()); +} + +export default gulp.series( + configureEnvironment, + buildJavaScript +); diff --git a/aurelia_project/tasks/watch.js b/aurelia_project/tasks/watch.js new file mode 100644 index 0000000..9df9516 --- /dev/null +++ b/aurelia_project/tasks/watch.js @@ -0,0 +1,128 @@ +import gulp from 'gulp'; +import minimatch from 'minimatch'; +import gulpWatch from 'gulp-watch'; +import debounce from 'debounce'; +import { build } from 'aurelia-cli'; +import project from '../aurelia.json'; +import transpile from './transpile'; +import processMarkup from './process-markup'; +import processCSS from './process-css'; +import copyFiles from './copy-files'; + +const debounceWaitTime = 100; +let isBuilding = false; +let pendingRefreshPaths = []; +let watchCallback = () => { }; +let watches = [ + { name: 'transpile', callback: transpile, source: project.transpiler.source }, + { name: 'markup', callback: processMarkup, source: project.markupProcessor.source }, + { name: 'CSS', callback: processCSS, source: project.cssProcessor.source } +]; + +if (typeof project.build.copyFiles === 'object') { + for (let src of Object.keys(project.build.copyFiles)) { + watches.push({ name: 'file copy', callback: copyFiles, source: src }); + } +} + +let watch = (callback) => { + watchCallback = callback || watchCallback; + + // watch every glob individually + for(let watcher of watches) { + if (Array.isArray(watcher.source)) { + for(let glob of watcher.source) { + watchPath(glob); + } + } else { + watchPath(watcher.source); + } + } +}; + +let watchPath = (p) => { + gulpWatch( + p, + { + read: false, // performance optimization: do not read actual file contents + verbose: true + }, + (vinyl) => processChange(vinyl)); +}; + +let processChange = (vinyl) => { + if (vinyl.path && vinyl.cwd && vinyl.path.startsWith(vinyl.cwd)) { + let pathToAdd = vinyl.path.substr(vinyl.cwd.length + 1); + log(`Watcher: Adding path ${pathToAdd} to pending build changes...`); + pendingRefreshPaths.push(pathToAdd); + refresh(); + } +} + +let refresh = debounce(() => { + if (isBuilding) { + log('Watcher: A build is already in progress, deferring change detection...'); + return; + } + + isBuilding = true; + + let paths = pendingRefreshPaths.splice(0); + let refreshTasks = []; + + // determine which tasks need to be executed + // based on the files that have changed + for (let watcher of watches) { + if (Array.isArray(watcher.source)) { + for(let source of watcher.source) { + if (paths.find(path => minimatch(path, source))) { + refreshTasks.push(watcher); + } + } + } + else { + if (paths.find(path => minimatch(path, watcher.source))) { + refreshTasks.push(watcher); + } + } + } + + if (refreshTasks.length === 0) { + log('Watcher: No relevant changes found, skipping next build.'); + isBuilding = false; + return; + } + + log(`Watcher: Running ${refreshTasks.map(x => x.name).join(', ')} tasks on next build...`); + + let toExecute = gulp.series( + readProjectConfiguration, + gulp.parallel(refreshTasks.map(x => x.callback)), + writeBundles, + (done) => { + isBuilding = false; + watchCallback(); + done(); + if (pendingRefreshPaths.length > 0) { + log('Watcher: Found more pending changes after finishing build, triggering next one...'); + refresh(); + } + } + ); + + toExecute(); +}, debounceWaitTime); + +function log(message) { + console.log(message); +} + +function readProjectConfiguration() { + return build.src(project); +} + +function writeBundles() { + return build.dest(); +} + +export default watch; \ No newline at end of file diff --git a/content/app/.babelrc b/content/app/.babelrc deleted file mode 100644 index 87316ba..0000000 --- a/content/app/.babelrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "presets": [ - "./.babelrc.js" - ] -} \ No newline at end of file diff --git a/content/app/.babelrc.js b/content/app/.babelrc.js deleted file mode 100644 index 4d2bde9..0000000 --- a/content/app/.babelrc.js +++ /dev/null @@ -1,27 +0,0 @@ -// this file will be used by default by babel@7 once it is released -module.exports = () => { - return { - "plugins": [ - "transform-decorators-legacy", - "transform-class-properties" - ], - "presets": [ - [ - "env", { - "targets": process.env.BABEL_TARGET === 'node' ? { - "node": process.env.IN_PROTRACTOR ? '6' : 'current' - } : { - "browsers": [ - "last 2 versions", - "not ie <= 11" - ], - "uglify": process.env.NODE_ENV === 'production', - }, - "loose": true, - "modules": process.env.BABEL_TARGET === 'node' ? 'commonjs' : false, - "useBuiltIns": true - } - ] - ] - } -} \ No newline at end of file diff --git a/content/app/.editorconfig b/content/app/.editorconfig deleted file mode 100644 index 26692da..0000000 --- a/content/app/.editorconfig +++ /dev/null @@ -1,12 +0,0 @@ -# EditorConfig is awesome: http://EditorConfig.org - -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -# 2 space indentation -indent_style = space -indent_size = 2 diff --git a/content/app/.eslintrc.json b/content/app/.eslintrc.json deleted file mode 100644 index 6cbb37d..0000000 --- a/content/app/.eslintrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "./node_modules/aurelia-tools/.eslintrc.json" -} diff --git a/content/app/.gitignore b/content/app/.gitignore deleted file mode 100644 index 2ebf2f7..0000000 --- a/content/app/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -# You may want to customise this file depending on your Operating System -# and the editor that you use. -# -# We recommend that you use a Global Gitignore for files that are not related -# to the project. (https://help.github.com/articles/ignoring-files/#create-a-global-gitignore) - -# OS -# -# Ref: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -# Ref: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore -# Ref: https://github.com/github/gitignore/blob/master/Global/Linux.gitignore -.DS_STORE -Thumbs.db - -# Editors -# -# Ref: https://github.com/github/gitignore/blob/master/Global -# Ref: https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore -# Ref: https://github.com/github/gitignore/blob/master/Global/VisualStudioCode.gitignore -.idea -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json - -# Dependencies -node_modules - -# Compiled files -scripts diff --git a/content/app/.vscode/extensions.json b/content/app/.vscode/extensions.json deleted file mode 100644 index c8227c3..0000000 --- a/content/app/.vscode/extensions.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "recommendations": [ - "AureliaEffect.aurelia", - "msjsdiag.debugger-for-chrome", - "steoates.autoimport", - "EditorConfig.EditorConfig", - "christian-kohler.path-intellisense", - "behzad88.Aurelia" - ] -} \ No newline at end of file diff --git a/content/app/.vscode/launch.json b/content/app/.vscode/launch.json deleted file mode 100644 index 3a5f9b4..0000000 --- a/content/app/.vscode/launch.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - // Use IntelliSense to find out which attributes exist for node debugging - // Use hover for the description of the existing attributes - // For further information visit https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Chrome", - "type": "chrome", - "request": "launch", - "url": "http://localhost:8080", - "webRoot": "${workspaceRoot}/src", - "userDataDir": "${workspaceRoot}/.chrome", - "sourceMapPathOverrides": { - "webpack:///./src/*": "${webRoot}/*" - } - } - ] -} \ No newline at end of file diff --git a/content/app/.vscode/settings.json b/content/app/.vscode/settings.json deleted file mode 100644 index 7857ad3..0000000 --- a/content/app/.vscode/settings.json +++ /dev/null @@ -1,6 +0,0 @@ -// Place your settings in this file to overwrite default and user settings. -{ - "typescript.tsdk": "node_modules/typescript/lib", - "html.suggest.angular1": false, - "html.suggest.ionic": false -} diff --git a/content/app/aurelia_project/aurelia.json b/content/app/aurelia_project/aurelia.json deleted file mode 100644 index 772ffac..0000000 --- a/content/app/aurelia_project/aurelia.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "name": "app", - "type": "project:application", - "bundler": { - "id": "webpack", - "displayName": "Webpack" - }, - "build": { - "options": { - "server": "dev", - "extractCss": "prod", - "coverage": false - } - }, - "platform": { - "id": "web", - "displayName": "Web", - "hmr": false, - "open": false, - "port": 8080, - "output": "dist" - }, - "loader": { - "id": "none", - "displayName": "None" - }, - "transpiler": { - "id": "babel", - "displayName": "Babel", - "fileExtension": ".js", - "options": { - "plugins": [ - "transform-es2015-modules-amd" - ] - } - }, - "markupProcessor": { - "id": "minimum", - "displayName": "Minimal Minification", - "fileExtension": ".html" - }, - "cssProcessor": { - "id": "none", - "displayName": "None", - "fileExtension": ".css" - }, - "editor": { - "id": "vscode", - "displayName": "Visual Studio Code" - }, - "unitTestRunners": [ - { - "id": "jest", - "displayName": "Jest" - }, - { - "id": "karma", - "displayName": "Karma" - } - ], - "integrationTestRunner": { - "id": "none", - "displayName": "None" - }, - "paths": { - "root": "src", - "resources": "resources", - "elements": "resources/elements", - "attributes": "resources/attributes", - "valueConverters": "resources/value-converters", - "bindingBehaviors": "resources/binding-behaviors" - }, - "testFramework": { - "id": "jasmine", - "displayName": "Jasmine" - }, - "packageManager": "npm" -} \ No newline at end of file diff --git a/content/app/aurelia_project/tasks/build.js b/content/app/aurelia_project/tasks/build.js deleted file mode 100644 index 7028d32..0000000 --- a/content/app/aurelia_project/tasks/build.js +++ /dev/null @@ -1,58 +0,0 @@ -import webpackConfig from '../../webpack.config'; -import webpack from 'webpack'; -import project from '../aurelia.json'; -import {CLIOptions, Configuration} from 'aurelia-cli'; -import gulp from 'gulp'; -import configureEnvironment from './environment'; -import del from 'del'; - -const analyze = CLIOptions.hasFlag('analyze'); -const buildOptions = new Configuration(project.build.options); -const production = CLIOptions.getEnvironment() === 'prod'; -const server = buildOptions.isApplicable('server'); -const extractCss = buildOptions.isApplicable('extractCss'); -const coverage = buildOptions.isApplicable('coverage'); - -const config = webpackConfig({ - production, server, extractCss, coverage, analyze -}); -const compiler = webpack(config); - -function buildWebpack(done) { - if (CLIOptions.hasFlag('watch')) { - compiler.watch({}, onBuild); - } else { - compiler.run(onBuild); - compiler.plugin('done', () => done()); - } -} - -function onBuild(err, stats) { - if (!CLIOptions.hasFlag('watch') && err) { - console.error(err.stack || err); - if (err.details) console.error(err.details); - process.exit(1); - } else { - process.stdout.write(stats.toString({ colors: require('supports-color') }) + '\n'); - - if (!CLIOptions.hasFlag('watch') && stats.hasErrors()) { - process.exit(1); - } - } -} - -function clearDist() { - return del([config.output.path]); -} - -const build = gulp.series( - clearDist, - configureEnvironment, - buildWebpack -); - -export { - config, - buildWebpack, - build as default -}; diff --git a/content/app/aurelia_project/tasks/environment.js b/content/app/aurelia_project/tasks/environment.js deleted file mode 100644 index 4902dfd..0000000 --- a/content/app/aurelia_project/tasks/environment.js +++ /dev/null @@ -1,24 +0,0 @@ -import project from '../aurelia.json'; -import rename from 'gulp-rename'; -import {CLIOptions} from 'aurelia-cli'; -import gulp from 'gulp'; -import fs from 'fs'; -import path from 'path'; -import through from 'through2'; - -function configureEnvironment() { - let env = CLIOptions.getEnvironment(); - - return gulp.src(`aurelia_project/environments/${env}${project.transpiler.fileExtension}`) - .pipe(rename(`environment${project.transpiler.fileExtension}`)) - .pipe(gulp.dest(project.paths.root)) - .pipe(through.obj(function (file, enc, cb) { - // https://github.com/webpack/watchpack/issues/25#issuecomment-287789288 - var now = Date.now() / 1000; - var then = now - 10; - fs.utimes(file.path, then, then, function (err) { if (err) throw err }); - cb(null, file); - })); -} - -export default configureEnvironment; \ No newline at end of file diff --git a/content/app/aurelia_project/tasks/jest.js b/content/app/aurelia_project/tasks/jest.js deleted file mode 100644 index 3df63f9..0000000 --- a/content/app/aurelia_project/tasks/jest.js +++ /dev/null @@ -1,23 +0,0 @@ -import jest from 'jest-cli'; -import PluginError from 'plugin-error'; -import path from 'path'; -import packageJson from '../../package.json'; -import {CLIOptions} from 'aurelia-cli'; - -export default (cb) => { - let options = packageJson.jest; - - if (CLIOptions.hasFlag('watch')) { - Object.assign(options, { watch: true}); - } - - process.env.BABEL_TARGET = 'node'; - - jest.runCLI(options, [path.resolve(__dirname, '../../')]).then((result) => { - if (result.numFailedTests || result.numFailedTestSuites) { - cb(new PluginError('gulp-jest', { message: 'Tests Failed' })); - } else { - cb(); - } - }); -}; diff --git a/content/app/aurelia_project/tasks/jest.json b/content/app/aurelia_project/tasks/jest.json deleted file mode 100644 index c11176c..0000000 --- a/content/app/aurelia_project/tasks/jest.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "jest", - "description": "Runs Jest and reports the results.", - "parameters": [ - { - "name": "watch", - "description": "Watches test files for changes and re-runs the tests automatically.", - "type": "boolean" - } - ] -} diff --git a/content/app/aurelia_project/tasks/karma.js b/content/app/aurelia_project/tasks/karma.js deleted file mode 100644 index f5a63bb..0000000 --- a/content/app/aurelia_project/tasks/karma.js +++ /dev/null @@ -1,16 +0,0 @@ -import {Server as Karma} from 'karma'; -import {CLIOptions} from 'aurelia-cli'; -import path from 'path'; - -let karma = done => { - new Karma({ - configFile: path.join(__dirname, '/../../test/karma.conf.js'), - singleRun: !CLIOptions.hasFlag('watch'), - autoWatch: CLIOptions.hasFlag('watch') - }, function(exitCode) { - console.log('Karma has exited with ' + exitCode) - process.exit(exitCode) - }).start(); -}; - -export { karma as default }; diff --git a/content/app/aurelia_project/tasks/karma.json b/content/app/aurelia_project/tasks/karma.json deleted file mode 100644 index 9ff49da..0000000 --- a/content/app/aurelia_project/tasks/karma.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "karma", - "description": "Runs Karma and reports the results.", - "flags": [ - { - "name": "watch", - "description": "Watches test files for changes and re-runs the tests automatically.", - "type": "boolean" - } - ] -} diff --git a/content/app/aurelia_project/tasks/run.js b/content/app/aurelia_project/tasks/run.js deleted file mode 100644 index f07b383..0000000 --- a/content/app/aurelia_project/tasks/run.js +++ /dev/null @@ -1,46 +0,0 @@ -import {config} from './build'; -import configureEnvironment from './environment'; -import webpack from 'webpack'; -import Server from 'webpack-dev-server'; -import project from '../aurelia.json'; -import {CLIOptions, reportWebpackReadiness} from 'aurelia-cli'; -import gulp from 'gulp'; - -function runWebpack(done) { - // https://webpack.github.io/docs/webpack-dev-server.html - let opts = { - host: 'localhost', - publicPath: config.output.publicPath, - filename: config.output.filename, - hot: project.platform.hmr || CLIOptions.hasFlag('hmr'), - port: project.platform.port, - contentBase: config.output.path, - historyApiFallback: true, - open: project.platform.open, - stats: { - colors: require('supports-color') - } - }; - - if (project.platform.hmr || CLIOptions.hasFlag('hmr')) { - config.plugins.push(new webpack.HotModuleReplacementPlugin()); - config.entry.app.unshift(`webpack-dev-server/client?http://${opts.host}:${opts.port}/`, 'webpack/hot/dev-server'); - } - - const compiler = webpack(config); - let server = new Server(compiler, opts); - - server.listen(opts.port, opts.host, function(err) { - if (err) throw err; - - reportWebpackReadiness(opts); - done(); - }); -} - -const run = gulp.series( - configureEnvironment, - runWebpack -); - -export { run as default }; diff --git a/content/app/favicon.ico b/content/app/favicon.ico deleted file mode 100644 index 330515e9c1d77fdfe88d7989060380932ca13e99..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15086 zcmdU$3s{v^*2iB&MJ)y8rl5$Lrg=*<(=2f+Q&TiWEh}#|Up1A23Y>G`00#uQh@v2< zs0f0opk^0GO-stu@-k+ZvFWR%>86&7*`sD~_V-)wxp48wFw@iX%y*t=x#94>d#}rX zueJADOHFgr+_gLJ)EI-c&D}L^u%>Cj!S>(1H0>+C^J0|0Ki^c-7V$t&p5Ya379`*6 zpWAH1f7`zWkIr%XZ{w-4{H%N={Fc?@=0@a?n>+OXqZ}(nMa;|_6Ml8|*zoU=A#zRV zT#)p~eTu^@?$8s^{gBh{8>S?-*)YWddK>>)`oR32%O09{D(B${l{Y#m-scd9efeheDfv0bgVZraQ#kvV|nqX5Cw#{MgAmIaETS8kQWv4xiUhp4RJSEYJ z3{~*IXTxO6unm*ro7{|d`9AsH$eF44MP5lCzCdLn!%}2eK60MQ8HFvzAVV!%tQ$Yq zY3GLKto=81@F#R}4t%Pthvxll@re14W<6-|D4A?|0G{82et_;To|-(oc{u^T)`8z!2S+fc-H2x zp`Urj7c9OlbBIpF#^~wi5APu*QHDmfE&WgFyd?jX}Ntp*3RKnnBl{h3yfhXM- zf+w*Bdt0}K4Nnn^*N>DBpnYL%_{hkzH&lbBS&iGQX@9dzV4Q3^4r+580-E@trnJ zOYXROY-DcU=y{hR^fh0t9dA@clM|3bWJoB0S_=QBUWn6l;BBhk!H7r;0f#=Mvs9G`5PMH-3Q$4t%nfP$RLDFf~im04?Sc}W4Bc;O+A(unR+f!raRJ=sZX-veSI$Q zqy$f*A8f4Kg1xQMLl#_QZ;x$=XUE@4CchxKiLJrSyc*n~7tvAdK+$~+YsRs5f-?0@ zf{&C-=yZ8>k0k;5q2Zn2JrDW?x{57kI_5WaT|3LzZRJ%{_Z(%qJxiH-WhhhcMa+>X zx)7TxGq#m=L|0;OFq;AY&b{N9%hibP?`OaN;J{6$Yuv!QS+~8cD>~G9xFg+a>Xmui z*dr@6W0*y3F_rz0v~tXXRytucFO;UvCBGT?6z8&y5}OpGGxf){WN3%Pv}GJ zDmsd@;ps4YyRo=w2X6K_aRcsT9|;yk7h>C5xY6w{YodFw!1}!wD;*cNFS~?(ml?XQ z3jF?+0NrQ5=(p^a7yOoPdeMKWiU`P4hR(>)b&WFKmZwZTvUzW*9ZxBCJeiTfcmb?F z;!4l;zbkvREfWG;s!tPZ{P;rb96pLr#e0a>zxa&#-QS3 z#!fGX&g+oh0vW>K|09t>$Yu*<)$z0v8FDUQ$423%HjX&|`4IEsiGSzxICX=+sf`=i zvku&_|D3p40skv)`V`)S*Teq?W$d(389Q#eWC$!>W(?R7@E5;Khb?~5Z6W(2Fjqwf zvnRT(&R{?2{-$tJtQT}g;l$Vm&ruFJh<8oE%?RS){)E9%)it;gUr(%QEN;4jiQocw zFH**!68L{v83MN`L%>$6p~LoLhW4+Gi||`7wwMgnw#EC=o!2^XQy6BBE)0wP1{n-c zTL+*2Y9yBXf*T9|=A1oFHRNx^<~QOdxDeip?YiF#|7GyMO&QwnPzL|kFB$xHX2tmJ z#TJXj7OSztw~V0<-U=s~hZcp!eODA_R><%h{O^K>LXEP8X<$?n_Us7uY&rg>+7_o8 zgB#Jk9XCNbZs5Jt#(RfX;QuxFe?uAl{%SS)?LKDm-8(MaZyo-1Nk9CQhwz^}D%^Y3 zBlCB!n_%KR7zc?A(4^RJp%D%l|JC@_@|{f#eat?@sYFwsg+JQkl-<`m{Eg_|?r&V+ z#@JEEjRH6D{;KF6-giQ~l*xAw^yVd#&%P|P&$|H*esV`eL?c7B+{f00M%R|%F#LCP zJlD`zHe*$LD0}P7m7`aTNpEWGoic(r^$u~W+8(F=6Wl0pBf3{c-`&Eyf_D|;^OiNn zd;if`?{~(>wmaA?Z*=&0`2QGEYsMQm2gZvG7oaf>@$C59)|qRYY@N9}aqG-g)|aPc zUnrcEo>4M2-9NH>hPSC_W)lA9CtIAV?Qd%1hCSPHlN~o((S04<)YAQ4;a$aezpY}u z%T;WkGZmRV-CBD0!zi9++?7Dv&{^8yG9r!<>%W0$Me)@5DV)6vk)ctz**0sf-?mw6_QSs_oxVyHPhBefJLn=mXOuja=5Oeh z=SQ4cNZk2JKa(}=Z@_(h+&FZ<-_HBH@cy1Mw>_ld+P<&iygs-T=Xq?Y`PP#GyW+<; z>fW+#_WCC9p9oozL2aG6MwQK2tu{@|cG$sTi?<5H(gQ|mWp11i9>U)oAWl{5zWzVM z4Z0WJ4?>59cj%~!_dI4z@H%lc!TY07i|?n+9QeN3xP5lPgWG1WI|u*DM#!Mcfi0fO zt8I%SaHZd;WG+*eLSKA+GI8p>4LA6D7yia*^EWrcjh%PV{So0^#e4ltCA9lcS$saO zO!WWz(xeWb-4sLHXRp5n{$GO>GQhu($WbGM-4>s)5A^#~MC;Pl;jK3(LXSlHZfR!h zxcNci)O*CKYFnHVU;l68#;*J0DxvKOc>hQx`hBXB+Mlu}1%7^XVW%%clY=X6um$|P zL!t106tdn#hF{nh(;W7L?`OkXZ~7Iw$j|BFw{Gz>cHHKRzga|_I&Y6tH~JeNr@y%w zZWOpt3En4_#rG4H*#4AC3iyXw*zpUM-1)1@lrCQ{U3A;GE^UDf9pOILKFPLE=>Pjks~_S>4~*_Ns72kru`cTV{gKq3XU3)V{;5uGP;`q7&EUVr7B(z>1fKNlJA11Y zR4h1+@jRd++q?$pUHo>FK2{Q;?xC`&%g9HH^YqrHwxUSQ-=)jJqY>=dK(%JInS&3 zu~zuA67g%uVe@hLIfoqtPcCfnQ$*`6_sRV8+&^@WX?tK4aq2K}%4&~Ob#deE^fwLR zM!|bdM&Ao{un(`dK-(dFs7`M%-s+GIKlThVTuo?qQuhzFWdKihIgT*a*aF@cN3GnzKQqhXJ zO2mhWUc?_uOp(|k>(-aSZj1BicC=&u4O13}6g;}w;(iyMn0Cxxe}s2uy#Sx}41V{T_}_({zR>3v9f__i zz8~xULbpY&J%J3V=C()l^DcJ?pVH~MdpABVXTem?!s%-BliAiSPh}t2GJW~&6E)QY zn~ue{AD|zrJx&zF(yqVa#QsR^oH@AzwId>Y~ z>-b8UzoAchp9{C(r#7YHYsKe^@0Iw$`9qI|H{uCfwEOUUyw{0Qj(NEQ4d)(r1{pZZ z=5Zz$%7s>3D4m{jL!JlSH$_L|Smy}qS?##F3Lnop=4|XpZ196#0drMpy^sM6ivO*# zMSVQ|-3ks;@k@5xYSfe94TS}bz8Q#~Ud*^w#vHZ(( z@ZT1S=Kb%9*T`^2rFO>_;8NnD#B}i!c3Zp$hIQP?yPTEAKo^lgmDQEu5d1rFBhR|} zuvRm0^8ow@yZU=$zf13X!3`OPBEv4``b}bYY7cB-$CF@{y?q|rJ8>g(%UKT!gHGr& z*lchCJKTVq#`5xep0nG+P}>%EJXx{DBKDq3Jivc2{O3ZK!4bI0bNSrw;jOXnX7s!0 zu*Gg{`O;lz!rx!@gJtbPz`@HtoS{t@5lw&?wn0X%)o-mZh2KVrQBC)m_Gj!&Z&aI&@)`mY``>p4v4ngwaDY z%6QGq5+UDLY84goT%|TZA1ky@dl@S=txXW) zHBEEBFNF1IU%J+r^%26zSY57ZL-_vMEKR#r#vz*Kk-&SLG-aI%4<6J~2s!Cx^(=J!Q0^`>eu)y<|%iS($RQ{F4{eaBF zm{=~O=8;&z{8r7={aS*IZQQFEl_khSDaP^;PkpQm$N7*=SNK+XE~Hi|{X5bt zAvH{7x(*Me=%T&j`T8TedW1Uv1$jq$PN;SM$eam@_rwHjd^}}hVOYY?`QxHFZ=3Bs z6qc*3pLoD%ax?Zx_M)z`(|ngv?>BJt;K)4EYa%sZ=6(wvyz8$kzw>>7U`C!3z86vB zrd}pB=W6Or`xEX;9GyST@EH9AC#9ET4ZR$NVewb6!%TUf8bTCx@2Z&o3A|&{Ywgm1 zBDHdz6R=a)QZj-??{cyyg&Aym181S z!pD_WV*?YeC-hG)8FYebG`0Q?*cV{d0+ZRutzn$D(0d|t}%$-N1>bZ4!w*0 zq~AfWFG~-EUL#DAdc4$0-ZJ-EI*LAoP_Wwd&t6$=BLZ@F>2=E6sC!GjSb8X=4}^E6 z2ZXuyVvn2YUGV;{Q}6VL2+#7KUgwj#d>?uWq_!&k1X5S+zT%vr>*_dT@CGmHbEBwp zRo2ve^YxmsUeBSAgI<&~^oF?9yVwD}N2B-ab@WdEkls&X(>rU^4thDtZH-?8yoWEP4_;s2ch?LaC)%;z1wQ=dM!WK zUdNX@IJMYL8_yX#mYT!;^Y4KNspbEo>mrDHdAC(>8oOtEZ+zU?iW-@-mR28s$lesc zF$TTAkKU~}*E@B+Zc@vZ+6?tbsijJ7AfT+;&|$~EX#ZCqw(H^(`Z~^n3tjKjxaLx8 zJOK~WAc>?dKe2a32bk_OrGxj2dTrFT-tBcEsi8{^nmVYS*ME(i^3HQ6zddGZpZC7t zmpR5u+v7&h%-!oI7{AtQonhuHtiKo{NZ%}?fai|wB{4*VX*c2*rnuJw-W zQpc3~vD7f7{;Jn6tEr#uBd2$NM&H7w)ccl8%@Q7@-d7DDaqA{TyTk+M;BlqXSDq@F zy2O}vZ)zW7&&BCrs8a8NaIJS+9Z#>HO8rr4r;^jvbLr>EDJEnNS~7Ii*oalsuCGw9 z+Y1ja_aS-kK<*UpZ+ap}>Oob|o`OfyL#Qc+Qj`0Deh{mz9_Lc;$Zo5B+G>a7!rMvh z>R>hbs(lu}_eSEU!-}VxUFHhN%QPjAy;$lZQV)6g@#WN|(}j<-g<)xb2FHQ;xJ>X~ zY3rMCsdrlq$J>^Nch=3QJCXM|8}E5CHqP^Nm$H+`9Y<}W(pj6K&bQ^MTw=_UtLrDF z;op^8gy-hY;C(!J{{Xzx^FaO7sdtgxsdr?j20-1*mJ6lkMQ+vNeX@#s^xH`RpNDWa zt&^)Fw?7dcPTT4$HT5Cxb?f#TEX}B)+(#YaLvr7yNWU$84FTITsijof>dr3p&iYbw zBai7t%}4508I0G4?+P&5fy=Q^0;-+Hf3F?HHU)tW8hut%r?DC{|IY?)1M0BwmU6j2w_m<7xue=cDk=kQN?^v(HSyCgGT&u0lcZ1&b90@s} zFOa>ztRo-R^nm6=2cZG-9l2=(^}#B^jpWvC`CRIsHM;mA#`E3#>?<$zE zcm!)t51rb9nb>J?|>@wHm$Wqj%?-RpzMufj4ik zxm(YL@t)*WrPh_$UUI5>E>d){C$`mzwy*rpiZa`c* zMHD`ws#XqhFFDXUK8_qxXXeQzKlU~AI%^O0*LD1E&mWA0j|1$HYT;XQzLFCpPhL$f zTi5%x*{fR+FIL0DZ}vPU`Pe*{=PcH4L0+hjtGcFR-TEUo@`r~M-aD`7SS7F5x)edbZ+ zp6PMT-P7}$hv)jLHl3B#bH7sSZ7cVLc~M+2{cjx~TwCDeOL>Es^4CPM!XYSLw--+&TaHp?7BYPx0;*W&C%$=~$`iV9F--mlr z7w+{(xXF&gw+))b=b9Rk45Z0_@yUV*=vLtlm$>o;YNk(^ETZkUb4NyxeX;aaos_smPewI9BQA5`FV6EOzIYz7uv+S# zQnO8H_fhGF@g>9X-4(>He-c0YCitEXhVONpQ?}uE>co@uK0kHFCub8EE_04NZSnuI z|MsWz`ccm+Cl0;jur)HbWbHcdI{t=VZH`Pc@Tt!@zQcd|Ku)|lzITjzZu79Fy?=n% pn#%bIlKg3TAURl8N#j - - - - <%- htmlWebpackPlugin.options.metadata.title %> - - - - - - <% if (htmlWebpackPlugin.options.metadata.server) { %> - - - <% } %> - - diff --git a/content/app/jsconfig.json b/content/app/jsconfig.json deleted file mode 100644 index dd9df72..0000000 --- a/content/app/jsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "compilerOptions": { - "target": "es2015", - "lib": ["es2017", "dom"], - "experimentalDecorators": true - }, - "exclude": [ - "node_modules", - "dist" - ] -} diff --git a/content/app/package-scripts.js b/content/app/package-scripts.js deleted file mode 100644 index e31b0b2..0000000 --- a/content/app/package-scripts.js +++ /dev/null @@ -1,79 +0,0 @@ -const {series, crossEnv, concurrent, rimraf} = require('nps-utils') - -module.exports = { - scripts: { - default: 'nps webpack', - test: { - default: 'nps test.jest', - jest: { - default: series( - rimraf('test/coverage-jest'), - crossEnv('BABEL_TARGET=node jest') - ), - accept: crossEnv('BABEL_TARGET=node jest -u'), - watch: crossEnv('BABEL_TARGET=node jest --watch'), - }, - - karma: { - default: series( - rimraf('test/coverage-karma'), - 'karma start test/karma.conf.js' - ), - watch: 'karma start test/karma.conf.js --auto-watch --no-single-run', - debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug' - }, - - lint: { - default: 'eslint src', - fix: 'eslint src --fix' - }, - all: concurrent({ - browser: series.nps('test.karma'), - jest: 'nps test.jest', - lint: 'nps test.lint' - }) - }, - build: 'nps webpack.build', - webpack: { - default: 'nps webpack.server', - build: { - before: rimraf('dist'), - default: 'nps webpack.build.production', - development: { - default: series( - 'nps webpack.build.before', - 'webpack --progress -d' - ), - extractCss: series( - 'nps webpack.build.before', - 'webpack --progress -d --env.extractCss' - ), - serve: series.nps( - 'webpack.build.development', - 'serve' - ), - }, - production: { - inlineCss: series( - 'nps webpack.build.before', - crossEnv('NODE_ENV=production webpack --progress -p --env.production') - ), - default: series( - 'nps webpack.build.before', - crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss') - ), - serve: series.nps( - 'webpack.build.production', - 'serve' - ), - } - }, - server: { - default: `webpack-dev-server -d --devtool '#source-map' --inline --env.server`, - extractCss: `webpack-dev-server -d --devtool '#source-map' --inline --env.server --env.extractCss`, - hmr: `webpack-dev-server -d --devtool '#source-map' --inline --hot --env.server` - }, - }, - serve: 'http-server dist --cors', - }, -} \ No newline at end of file diff --git a/content/app/package.json b/content/app/package.json deleted file mode 100644 index a69e82e..0000000 --- a/content/app/package.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "name": "app", - "description": "An Aurelia client application.", - "version": "0.1.0", - "repository": { - "type": "???", - "url": "???" - }, - "license": "MIT", - "dependencies": { - "aurelia-bootstrapper": "^2.2.0", - "aurelia-animator-css": "^1.0.4", - "bluebird": "^3.5.1", - "aurelia-polyfills": "^1.3.0" - }, - "peerDependencies": {}, - "devDependencies": { - "aurelia-cli": "^0.34.0", - "aurelia-testing": "^1.0.0-beta.4.0.0", - "aurelia-tools": "^2.0.0", - "gulp": "^4.0.0", - "minimatch": "^3.0.4", - "through2": "^2.0.3", - "vinyl-fs": "^3.0.2", - "babel-eslint": "7.2.3", - "eslint": "3.19.0", - "babel-loader": "^7.1.4", - "babel-core": "^6.26.0", - "babel-plugin-syntax-flow": "^6.18.0", - "babel-plugin-transform-class-properties": "^6.24.1", - "babel-plugin-transform-decorators-legacy": "^1.3.4", - "babel-plugin-transform-flow-strip-types": "^6.22.0", - "babel-polyfill": "^6.26.0", - "babel-preset-env": "^1.6.1", - "babel-preset-es2015": "^6.24.1", - "babel-preset-stage-1": "^6.24.1", - "babel-register": "^6.26.0", - "babel-plugin-istanbul": "^4.1.5", - "jest": "^22.4.2", - "jest-cli": "^23.0.0-alpha.0", - "plugin-error": "^1.0.1", - "aurelia-loader-nodejs": "^1.0.1", - "aurelia-pal-nodejs": "^1.0.0-beta.3.2.0", - "babel-jest": "^23.0.0-alpha.0", - "jasmine-core": "^3.1.0", - "karma": "^2.0.0", - "karma-chrome-launcher": "^2.2.0", - "karma-coverage": "latest", - "karma-jasmine": "^1.1.1", - "karma-mocha-reporter": "latest", - "karma-webpack": "^v4.0.0-beta.0", - "karma-coverage-istanbul-reporter": "^1.4.2", - "jest-jasmine2": "^23.0.0-alpha.0", - "jest-matchers": "^20.0.3", - "karma-babel-preprocessor": "^7.0.0", - "gulp-rename": "^1.2.2", - "html-webpack-plugin": "^3.0.6", - "copy-webpack-plugin": "^4.5.1", - "mini-css-extract-plugin": "^0.4.1", - "aurelia-webpack-plugin": "^3.0.0-rc.1", - "duplicate-package-checker-webpack-plugin": "^3.0.0", - "webpack": "^4.1.1", - "webpack-cli": "^2.0.12", - "webpack-dev-server": "^3.1.1", - "expose-loader": "^0.7.5", - "style-loader": "^0.20.3", - "url-loader": "^1.0.1", - "del": "^3.0.0", - "css-loader": "^0.28.11", - "nps": "^5.8.2", - "nps-utils": "^1.5.0", - "file-loader": "^1.1.11", - "json-loader": "^0.5.7", - "html-loader": "^0.5.5", - "istanbul-instrumenter-loader": "^3.0.0", - "opn": "^5.3.0", - "webpack-bundle-analyzer": "latest" - }, - "jest": { - "modulePaths": [ - "/src", - "/node_modules" - ], - "moduleFileExtensions": [ - "js", - "json" - ], - "transform": { - "^.+\\.jsx?$": "babel-jest" - }, - "testRegex": "\\.spec\\.(ts|js)x?$", - "setupFiles": [ - "/test/jest-pretest.js" - ], - "testEnvironment": "node", - "collectCoverage": true, - "collectCoverageFrom": [ - "src/**/*.{js,ts}", - "!**/*.spec.{js,ts}", - "!**/node_modules/**", - "!**/test/**" - ], - "coverageDirectory": "/test/coverage-jest", - "coverageReporters": [ - "json", - "lcov", - "text", - "html" - ] - }, - "engines": { - "node": ">= 6.0.0" - }, - "scripts": { - "start": "nps", - "test": "nps test" - }, - "main": "dist/app.bundle.js" -} diff --git a/content/app/src/app.html b/content/app/src/app.html deleted file mode 100644 index 668958d..0000000 --- a/content/app/src/app.html +++ /dev/null @@ -1,7 +0,0 @@ - \ No newline at end of file diff --git a/content/app/src/main.js b/content/app/src/main.js deleted file mode 100644 index c783449..0000000 --- a/content/app/src/main.js +++ /dev/null @@ -1,30 +0,0 @@ -import environment from './environment'; -import {PLATFORM} from 'aurelia-pal'; -import 'babel-polyfill'; -import * as Bluebird from 'bluebird'; - -// remove out if you don't want a Promise polyfill (remove also from webpack.config.js) -Bluebird.config({ warnings: { wForgottenReturn: false } }); - -export function configure(aurelia) { - aurelia.use - .standardConfiguration() - .feature(PLATFORM.moduleName('resources/index')); - - // Uncomment the line below to enable animation. - // aurelia.use.plugin(PLATFORM.moduleName('aurelia-animator-css')); - // if the css animator is enabled, add swap-order="after" to all router-view elements - - // Anyone wanting to use HTMLImports to load views, will need to install the following plugin. - // aurelia.use.plugin(PLATFORM.moduleName('aurelia-html-import-template-loader')); - - if (environment.debug) { - aurelia.use.developmentLogging(); - } - - if (environment.testing) { - aurelia.use.plugin(PLATFORM.moduleName('aurelia-testing')); - } - - return aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app'))); -} diff --git a/content/app/static/favicon.ico b/content/app/static/favicon.ico deleted file mode 100644 index 330515e9c1d77fdfe88d7989060380932ca13e99..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15086 zcmdU$3s{v^*2iB&MJ)y8rl5$Lrg=*<(=2f+Q&TiWEh}#|Up1A23Y>G`00#uQh@v2< zs0f0opk^0GO-stu@-k+ZvFWR%>86&7*`sD~_V-)wxp48wFw@iX%y*t=x#94>d#}rX zueJADOHFgr+_gLJ)EI-c&D}L^u%>Cj!S>(1H0>+C^J0|0Ki^c-7V$t&p5Ya379`*6 zpWAH1f7`zWkIr%XZ{w-4{H%N={Fc?@=0@a?n>+OXqZ}(nMa;|_6Ml8|*zoU=A#zRV zT#)p~eTu^@?$8s^{gBh{8>S?-*)YWddK>>)`oR32%O09{D(B${l{Y#m-scd9efeheDfv0bgVZraQ#kvV|nqX5Cw#{MgAmIaETS8kQWv4xiUhp4RJSEYJ z3{~*IXTxO6unm*ro7{|d`9AsH$eF44MP5lCzCdLn!%}2eK60MQ8HFvzAVV!%tQ$Yq zY3GLKto=81@F#R}4t%Pthvxll@re14W<6-|D4A?|0G{82et_;To|-(oc{u^T)`8z!2S+fc-H2x zp`Urj7c9OlbBIpF#^~wi5APu*QHDmfE&WgFyd?jX}Ntp*3RKnnBl{h3yfhXM- zf+w*Bdt0}K4Nnn^*N>DBpnYL%_{hkzH&lbBS&iGQX@9dzV4Q3^4r+580-E@trnJ zOYXROY-DcU=y{hR^fh0t9dA@clM|3bWJoB0S_=QBUWn6l;BBhk!H7r;0f#=Mvs9G`5PMH-3Q$4t%nfP$RLDFf~im04?Sc}W4Bc;O+A(unR+f!raRJ=sZX-veSI$Q zqy$f*A8f4Kg1xQMLl#_QZ;x$=XUE@4CchxKiLJrSyc*n~7tvAdK+$~+YsRs5f-?0@ zf{&C-=yZ8>k0k;5q2Zn2JrDW?x{57kI_5WaT|3LzZRJ%{_Z(%qJxiH-WhhhcMa+>X zx)7TxGq#m=L|0;OFq;AY&b{N9%hibP?`OaN;J{6$Yuv!QS+~8cD>~G9xFg+a>Xmui z*dr@6W0*y3F_rz0v~tXXRytucFO;UvCBGT?6z8&y5}OpGGxf){WN3%Pv}GJ zDmsd@;ps4YyRo=w2X6K_aRcsT9|;yk7h>C5xY6w{YodFw!1}!wD;*cNFS~?(ml?XQ z3jF?+0NrQ5=(p^a7yOoPdeMKWiU`P4hR(>)b&WFKmZwZTvUzW*9ZxBCJeiTfcmb?F z;!4l;zbkvREfWG;s!tPZ{P;rb96pLr#e0a>zxa&#-QS3 z#!fGX&g+oh0vW>K|09t>$Yu*<)$z0v8FDUQ$423%HjX&|`4IEsiGSzxICX=+sf`=i zvku&_|D3p40skv)`V`)S*Teq?W$d(389Q#eWC$!>W(?R7@E5;Khb?~5Z6W(2Fjqwf zvnRT(&R{?2{-$tJtQT}g;l$Vm&ruFJh<8oE%?RS){)E9%)it;gUr(%QEN;4jiQocw zFH**!68L{v83MN`L%>$6p~LoLhW4+Gi||`7wwMgnw#EC=o!2^XQy6BBE)0wP1{n-c zTL+*2Y9yBXf*T9|=A1oFHRNx^<~QOdxDeip?YiF#|7GyMO&QwnPzL|kFB$xHX2tmJ z#TJXj7OSztw~V0<-U=s~hZcp!eODA_R><%h{O^K>LXEP8X<$?n_Us7uY&rg>+7_o8 zgB#Jk9XCNbZs5Jt#(RfX;QuxFe?uAl{%SS)?LKDm-8(MaZyo-1Nk9CQhwz^}D%^Y3 zBlCB!n_%KR7zc?A(4^RJp%D%l|JC@_@|{f#eat?@sYFwsg+JQkl-<`m{Eg_|?r&V+ z#@JEEjRH6D{;KF6-giQ~l*xAw^yVd#&%P|P&$|H*esV`eL?c7B+{f00M%R|%F#LCP zJlD`zHe*$LD0}P7m7`aTNpEWGoic(r^$u~W+8(F=6Wl0pBf3{c-`&Eyf_D|;^OiNn zd;if`?{~(>wmaA?Z*=&0`2QGEYsMQm2gZvG7oaf>@$C59)|qRYY@N9}aqG-g)|aPc zUnrcEo>4M2-9NH>hPSC_W)lA9CtIAV?Qd%1hCSPHlN~o((S04<)YAQ4;a$aezpY}u z%T;WkGZmRV-CBD0!zi9++?7Dv&{^8yG9r!<>%W0$Me)@5DV)6vk)ctz**0sf-?mw6_QSs_oxVyHPhBefJLn=mXOuja=5Oeh z=SQ4cNZk2JKa(}=Z@_(h+&FZ<-_HBH@cy1Mw>_ld+P<&iygs-T=Xq?Y`PP#GyW+<; z>fW+#_WCC9p9oozL2aG6MwQK2tu{@|cG$sTi?<5H(gQ|mWp11i9>U)oAWl{5zWzVM z4Z0WJ4?>59cj%~!_dI4z@H%lc!TY07i|?n+9QeN3xP5lPgWG1WI|u*DM#!Mcfi0fO zt8I%SaHZd;WG+*eLSKA+GI8p>4LA6D7yia*^EWrcjh%PV{So0^#e4ltCA9lcS$saO zO!WWz(xeWb-4sLHXRp5n{$GO>GQhu($WbGM-4>s)5A^#~MC;Pl;jK3(LXSlHZfR!h zxcNci)O*CKYFnHVU;l68#;*J0DxvKOc>hQx`hBXB+Mlu}1%7^XVW%%clY=X6um$|P zL!t106tdn#hF{nh(;W7L?`OkXZ~7Iw$j|BFw{Gz>cHHKRzga|_I&Y6tH~JeNr@y%w zZWOpt3En4_#rG4H*#4AC3iyXw*zpUM-1)1@lrCQ{U3A;GE^UDf9pOILKFPLE=>Pjks~_S>4~*_Ns72kru`cTV{gKq3XU3)V{;5uGP;`q7&EUVr7B(z>1fKNlJA11Y zR4h1+@jRd++q?$pUHo>FK2{Q;?xC`&%g9HH^YqrHwxUSQ-=)jJqY>=dK(%JInS&3 zu~zuA67g%uVe@hLIfoqtPcCfnQ$*`6_sRV8+&^@WX?tK4aq2K}%4&~Ob#deE^fwLR zM!|bdM&Ao{un(`dK-(dFs7`M%-s+GIKlThVTuo?qQuhzFWdKihIgT*a*aF@cN3GnzKQqhXJ zO2mhWUc?_uOp(|k>(-aSZj1BicC=&u4O13}6g;}w;(iyMn0Cxxe}s2uy#Sx}41V{T_}_({zR>3v9f__i zz8~xULbpY&J%J3V=C()l^DcJ?pVH~MdpABVXTem?!s%-BliAiSPh}t2GJW~&6E)QY zn~ue{AD|zrJx&zF(yqVa#QsR^oH@AzwId>Y~ z>-b8UzoAchp9{C(r#7YHYsKe^@0Iw$`9qI|H{uCfwEOUUyw{0Qj(NEQ4d)(r1{pZZ z=5Zz$%7s>3D4m{jL!JlSH$_L|Smy}qS?##F3Lnop=4|XpZ196#0drMpy^sM6ivO*# zMSVQ|-3ks;@k@5xYSfe94TS}bz8Q#~Ud*^w#vHZ(( z@ZT1S=Kb%9*T`^2rFO>_;8NnD#B}i!c3Zp$hIQP?yPTEAKo^lgmDQEu5d1rFBhR|} zuvRm0^8ow@yZU=$zf13X!3`OPBEv4``b}bYY7cB-$CF@{y?q|rJ8>g(%UKT!gHGr& z*lchCJKTVq#`5xep0nG+P}>%EJXx{DBKDq3Jivc2{O3ZK!4bI0bNSrw;jOXnX7s!0 zu*Gg{`O;lz!rx!@gJtbPz`@HtoS{t@5lw&?wn0X%)o-mZh2KVrQBC)m_Gj!&Z&aI&@)`mY``>p4v4ngwaDY z%6QGq5+UDLY84goT%|TZA1ky@dl@S=txXW) zHBEEBFNF1IU%J+r^%26zSY57ZL-_vMEKR#r#vz*Kk-&SLG-aI%4<6J~2s!Cx^(=J!Q0^`>eu)y<|%iS($RQ{F4{eaBF zm{=~O=8;&z{8r7={aS*IZQQFEl_khSDaP^;PkpQm$N7*=SNK+XE~Hi|{X5bt zAvH{7x(*Me=%T&j`T8TedW1Uv1$jq$PN;SM$eam@_rwHjd^}}hVOYY?`QxHFZ=3Bs z6qc*3pLoD%ax?Zx_M)z`(|ngv?>BJt;K)4EYa%sZ=6(wvyz8$kzw>>7U`C!3z86vB zrd}pB=W6Or`xEX;9GyST@EH9AC#9ET4ZR$NVewb6!%TUf8bTCx@2Z&o3A|&{Ywgm1 zBDHdz6R=a)QZj-??{cyyg&Aym181S z!pD_WV*?YeC-hG)8FYebG`0Q?*cV{d0+ZRutzn$D(0d|t}%$-N1>bZ4!w*0 zq~AfWFG~-EUL#DAdc4$0-ZJ-EI*LAoP_Wwd&t6$=BLZ@F>2=E6sC!GjSb8X=4}^E6 z2ZXuyVvn2YUGV;{Q}6VL2+#7KUgwj#d>?uWq_!&k1X5S+zT%vr>*_dT@CGmHbEBwp zRo2ve^YxmsUeBSAgI<&~^oF?9yVwD}N2B-ab@WdEkls&X(>rU^4thDtZH-?8yoWEP4_;s2ch?LaC)%;z1wQ=dM!WK zUdNX@IJMYL8_yX#mYT!;^Y4KNspbEo>mrDHdAC(>8oOtEZ+zU?iW-@-mR28s$lesc zF$TTAkKU~}*E@B+Zc@vZ+6?tbsijJ7AfT+;&|$~EX#ZCqw(H^(`Z~^n3tjKjxaLx8 zJOK~WAc>?dKe2a32bk_OrGxj2dTrFT-tBcEsi8{^nmVYS*ME(i^3HQ6zddGZpZC7t zmpR5u+v7&h%-!oI7{AtQonhuHtiKo{NZ%}?fai|wB{4*VX*c2*rnuJw-W zQpc3~vD7f7{;Jn6tEr#uBd2$NM&H7w)ccl8%@Q7@-d7DDaqA{TyTk+M;BlqXSDq@F zy2O}vZ)zW7&&BCrs8a8NaIJS+9Z#>HO8rr4r;^jvbLr>EDJEnNS~7Ii*oalsuCGw9 z+Y1ja_aS-kK<*UpZ+ap}>Oob|o`OfyL#Qc+Qj`0Deh{mz9_Lc;$Zo5B+G>a7!rMvh z>R>hbs(lu}_eSEU!-}VxUFHhN%QPjAy;$lZQV)6g@#WN|(}j<-g<)xb2FHQ;xJ>X~ zY3rMCsdrlq$J>^Nch=3QJCXM|8}E5CHqP^Nm$H+`9Y<}W(pj6K&bQ^MTw=_UtLrDF z;op^8gy-hY;C(!J{{Xzx^FaO7sdtgxsdr?j20-1*mJ6lkMQ+vNeX@#s^xH`RpNDWa zt&^)Fw?7dcPTT4$HT5Cxb?f#TEX}B)+(#YaLvr7yNWU$84FTITsijof>dr3p&iYbw zBai7t%}4508I0G4?+P&5fy=Q^0;-+Hf3F?HHU)tW8hut%r?DC{|IY?)1M0BwmU6j2w_m<7xue=cDk=kQN?^v(HSyCgGT&u0lcZ1&b90@s} zFOa>ztRo-R^nm6=2cZG-9l2=(^}#B^jpWvC`CRIsHM;mA#`E3#>?<$zE zcm!)t51rb9nb>J?|>@wHm$Wqj%?-RpzMufj4ik zxm(YL@t)*WrPh_$UUI5>E>d){C$`mzwy*rpiZa`c* zMHD`ws#XqhFFDXUK8_qxXXeQzKlU~AI%^O0*LD1E&mWA0j|1$HYT;XQzLFCpPhL$f zTi5%x*{fR+FIL0DZ}vPU`Pe*{=PcH4L0+hjtGcFR-TEUo@`r~M-aD`7SS7F5x)edbZ+ zp6PMT-P7}$hv)jLHl3B#bH7sSZ7cVLc~M+2{cjx~TwCDeOL>Es^4CPM!XYSLw--+&TaHp?7BYPx0;*W&C%$=~$`iV9F--mlr z7w+{(xXF&gw+))b=b9Rk45Z0_@yUV*=vLtlm$>o;YNk(^ETZkUb4NyxeX;aaos_smPewI9BQA5`FV6EOzIYz7uv+S# zQnO8H_fhGF@g>9X-4(>He-c0YCitEXhVONpQ?}uE>co@uK0kHFCub8EE_04NZSnuI z|MsWz`ccm+Cl0;jur)HbWbHcdI{t=VZH`Pc@Tt!@zQcd|Ku)|lzITjzZu79Fy?=n% pn#%bIlKg3TAURl8N#j { - const jestMatchersObject = Object.create(null); - Object.keys(jasmineMatchersObject).forEach(name => { - jestMatchersObject[name] = function() { - const result = jasmineMatchersObject[name](jasmine.matchersUtil, null); - // if there is no 'negativeCompare', both should be handled by `compare` - const negativeCompare = result.negativeCompare || result.compare; - - return this.isNot - ? negativeCompare.apply(null, arguments) - : result.compare.apply(null, arguments); - }; - }); - - const expect = global.expect; - expect.extend(jestMatchersObject); - }; -} \ No newline at end of file diff --git a/content/app/test/karma.conf.js b/content/app/test/karma.conf.js deleted file mode 100644 index 4fd9bea..0000000 --- a/content/app/test/karma.conf.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict'; -const path = require('path'); - -module.exports = function (config) { - config.set({ - /** - * base path that will be used to resolve all patterns (e.g. files, exclude) - */ - basePath: path.dirname(__dirname), - - /** - * Frameworks to use - * - * available frameworks: https://npmjs.org/browse/keyword/karma-adapter - */ - frameworks: [ 'jasmine' ], - - /** - * list of files / patterns to load in the browser - * we are building the test environment in ./spec-bundle.js - */ - files: [ - { pattern: 'test/karma-bundle.js', watched: false } - ], - - /* - * preprocess matching files before serving them to the browser - * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - */ - preprocessors: { - 'test/karma-bundle.js': [ 'webpack' ] - }, - - webpack: require('../webpack.config')({ coverage: true, karma: true }), - - /* - * test results reporter to use - * - * possible values: 'dots', 'progress' - * available reporters: https://npmjs.org/browse/keyword/karma-reporter - */ - reporters: [ 'mocha', 'progress', 'coverage' ], - - coverageReporter: { - reporters: [ { type: 'html' }, { type: 'lcovonly' }, { type: 'text-summary' } ], - dir: path.resolve(__dirname, 'coverage-karma'), - subdir: '.', - }, - - // Webpack please don't spam the console when running in karma! - webpackServer: { noInfo: true }, - - // web server port - port: 9876, - - // enable / disable colors in the output (reporters and logs) - colors: true, - - /* - * level of logging - * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - */ - logLevel: config.LOG_INFO, - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: false, - - /* - * start these browsers - * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - */ - browsers: [ - 'Chrome', - ], - - /* - * Continuous Integration mode - * if true, Karma captures browsers, runs the tests and exits - */ - singleRun: true - }) -} \ No newline at end of file diff --git a/content/app/test/unit/.eslintrc b/content/app/test/unit/.eslintrc deleted file mode 100644 index 9262967..0000000 --- a/content/app/test/unit/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "no-var": 0 - } -} diff --git a/content/app/test/unit/app.spec.js b/content/app/test/unit/app.spec.js deleted file mode 100644 index 500fdb5..0000000 --- a/content/app/test/unit/app.spec.js +++ /dev/null @@ -1,7 +0,0 @@ -import {App} from '../../src/app'; - -describe('the app', () => { - it('says hello', () => { - expect(new App().message).toBe('Hello World!'); - }); -}); diff --git a/content/app/webpack.config.js b/content/app/webpack.config.js deleted file mode 100644 index 484fe20..0000000 --- a/content/app/webpack.config.js +++ /dev/null @@ -1,116 +0,0 @@ -const path = require('path'); -const HtmlWebpackPlugin = require('html-webpack-plugin'); -const CopyWebpackPlugin = require('copy-webpack-plugin'); -const MiniCssExtractPlugin = require('mini-css-extract-plugin'); -const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin'); -const project = require('./aurelia_project/aurelia.json'); -const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin'); -const { ProvidePlugin } = require('webpack'); -const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); - -// config helpers: -const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []; -const when = (condition, config, negativeConfig) => - condition ? ensureArray(config) : ensureArray(negativeConfig); - -// primary config: -const title = 'Aurelia Navigation Skeleton'; -const outDir = path.resolve(__dirname, project.platform.output); -const srcDir = path.resolve(__dirname, 'src'); -const nodeModulesDir = path.resolve(__dirname, 'node_modules'); -const baseUrl = '/'; - -const cssRules = [ - { loader: 'css-loader' }, -]; - -module.exports = ({production, server, extractCss, coverage, analyze, karma} = {}) => ({ - resolve: { - extensions: ['.js'], - modules: [srcDir, 'node_modules'], - // Enforce single aurelia-binding, to avoid v1/v2 duplication due to - // out-of-date dependencies on 3rd party aurelia plugins - alias: { 'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding') } - }, - entry: { - app: ['aurelia-bootstrapper'], - vendor: ['bluebird'], - }, - mode: production ? 'production' : 'development', - output: { - path: outDir, - publicPath: baseUrl, - filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js', - sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map', - chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js' - }, - performance: { hints: false }, - devServer: { - contentBase: outDir, - // serve index.html for all 404 (required for push-state) - historyApiFallback: true - }, - devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map', - module: { - rules: [ - // CSS required in JS/TS files should use the style-loader that auto-injects it into the website - // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates - { - test: /\.css$/i, - issuer: [{ not: [{ test: /\.html$/i }] }], - use: extractCss ? [{ - loader: MiniCssExtractPlugin.loader - }, - 'css-loader' - ] : ['style-loader', ...cssRules] - }, - { - test: /\.css$/i, - issuer: [{ test: /\.html$/i }], - // CSS required in templates cannot be extracted safely - // because Aurelia would try to require it again in runtime - use: cssRules - }, - { test: /\.html$/i, loader: 'html-loader' }, - { test: /\.js$/i, loader: 'babel-loader', exclude: nodeModulesDir, - options: coverage ? { sourceMap: 'inline', plugins: [ 'istanbul' ] } : {}, - }, - // use Bluebird as the global Promise implementation: - { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' }, - // embed small images and fonts as Data Urls and larger ones as files: - { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } }, - { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } }, - { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } }, - // load these fonts normally, as files: - { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' }, - ] - }, - plugins: [ - ...when(!karma, new DuplicatePackageCheckerPlugin()), - new AureliaPlugin(), - new ProvidePlugin({ - 'Promise': 'bluebird' - }), - new ModuleDependenciesPlugin({ - 'aurelia-testing': [ './compile-spy', './view-spy' ] - }), - new HtmlWebpackPlugin({ - template: 'index.ejs', - minify: production ? { - removeComments: true, - collapseWhitespace: true - } : undefined, - metadata: { - // available in index.ejs // - title, server, baseUrl - } - }), - ...when(extractCss, new MiniCssExtractPlugin({ - filename: production ? '[contenthash].css' : '[id].css', - allChunks: true - })), - ...when(production || server, new CopyWebpackPlugin([ - { from: 'static', to: outDir }])), - ...when(analyze, new BundleAnalyzerPlugin()) - ] -}); diff --git a/content/dist/app-bundle.js b/content/dist/app-bundle.js new file mode 100644 index 0000000..d385820 --- /dev/null +++ b/content/dist/app-bundle.js @@ -0,0 +1,107 @@ +define('welcome/welcome',["exports"], function (exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + var NoSelection = exports.NoSelection = function NoSelection() { + _classCallCheck(this, NoSelection); + + this.message = "Please Select a Contact."; + }; +}); +define('text!welcome/welcome.html', ['module'], function(module) { module.exports = ""; }); +define('resources/index',["exports"], function (exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.configure = configure; + function configure(config) {} +}); +define('main',['exports', './environment'], function (exports, _environment) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.configure = configure; + + var _environment2 = _interopRequireDefault(_environment); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + function configure(aurelia) { + aurelia.use.standardConfiguration().feature('resources'); + + if (_environment2.default.debug) { + aurelia.use.developmentLogging(); + } + + if (_environment2.default.testing) { + aurelia.use.plugin('aurelia-testing'); + } + + return aurelia.start().then(function () { + return aurelia.setRoot(); + }); + } +}); +define('environment',["exports"], function (exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = { + debug: true, + testing: true + }; +}); +define('app',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.App = undefined; + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + var App = exports.App = function () { + function App() { + _classCallCheck(this, App); + } + + App.prototype.configureRouter = function configureRouter(config, router) { + config.title = 'Welcome'; + config.map([{ + route: '', + moduleId: _aureliaPal.PLATFORM.moduleName('welcome/welcome'), + title: 'Welcome' + }]); + + this.router = router; + }; + + return App; + }(); +}); +define('text!app.html', ['module'], function(module) { module.exports = ""; }); +//# sourceMappingURL=app-bundle.js.map \ No newline at end of file diff --git a/content/dist/app-bundle.js.map b/content/dist/app-bundle.js.map new file mode 100644 index 0000000..c203bb2 --- /dev/null +++ b/content/dist/app-bundle.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["src/welcome/welcome.js","/Users/robertwaggott/Code/Me/payrun-demo/src/welcome/welcome.html","src/resources/index.js","src/main.js","src/environment.js","src/app.js","/Users/robertwaggott/Code/Me/payrun-demo/src/app.html"],"names":["NoSelection","message","configure","config","aurelia","use","standardConfiguration","feature","environment","debug","developmentLogging","testing","plugin","start","then","setRoot","App","configureRouter","router","title","map","route","moduleId","PLATFORM","moduleName"],"mappings":";;;;;;;;;;;;;QAAaA,sBAAAA,cACT,uBAAc;AAAA;;AACV,aAAKC,OAAL,GAAe,0BAAf;AACH;;ACHL;;;;;;;UCAgBC,YAAAA;AAAT,WAASA,SAAT,CAAmBC,MAAnB,EAA2B,CAEjC;;;;;;;;UCAeD,YAAAA;;;;;;;;;;AAAT,WAASA,SAAT,CAAmBE,OAAnB,EAA4B;AACjCA,YAAQC,GAAR,CACGC,qBADH,GAEGC,OAFH,CAEW,WAFX;;AAIA,QAAIC,sBAAYC,KAAhB,EAAuB;AACrBL,cAAQC,GAAR,CAAYK,kBAAZ;AACD;;AAED,QAAIF,sBAAYG,OAAhB,EAAyB;AACvBP,cAAQC,GAAR,CAAYO,MAAZ,CAAmB,iBAAnB;AACD;;AAED,WAAOR,QAAQS,KAAR,GAAgBC,IAAhB,CAAqB;AAAA,aAAMV,QAAQW,OAAR,EAAN;AAAA,KAArB,CAAP;AACD;;;;;;;;oBChBc;AACbN,WAAO,IADM;AAEbE,aAAS;AAFI;;;;;;;;;;;;;;;;KCEFK,cAAAA;;;;;gBACZC,2CAAgBd,QAAQe,QAAQ;AAC/Bf,UAAOgB,KAAP,GAAe,SAAf;AACAhB,UAAOiB,GAAP,CAAW,CACV;AACCC,WAAO,EADR;AAECC,cAAUC,qBAASC,UAAT,CAAoB,iBAApB,CAFX;AAGCL,WAAO;AAHR,IADU,CAAX;;AAQG,QAAKD,MAAL,GAAcA,MAAd;AACH;;;;;ACdF","file":"app-bundle.js","sourcesContent":["export class NoSelection {\n constructor() {\n this.message = \"Please Select a Contact.\";\n }\n}",null,"export function configure(config) {\n //config.globalResources([]);\n}\n","import environment from './environment';\n\nexport function configure(aurelia) {\n aurelia.use\n .standardConfiguration()\n .feature('resources');\n\n if (environment.debug) {\n aurelia.use.developmentLogging();\n }\n\n if (environment.testing) {\n aurelia.use.plugin('aurelia-testing');\n }\n\n return aurelia.start().then(() => aurelia.setRoot());\n}\n","export default {\n debug: true,\n testing: true\n};\n","import { PLATFORM } from 'aurelia-pal';\n\nexport class App {\n\tconfigureRouter(config, router) {\n\t\tconfig.title = 'Welcome';\n\t\tconfig.map([\n\t\t\t{ \n\t\t\t\troute: '',\n\t\t\t\tmoduleId: PLATFORM.moduleName('welcome/welcome'),\n\t\t\t\ttitle: 'Welcome' \n\t\t\t}\n\t\t]);\n\n \tthis.router = router;\n\t}\n}",null],"sourceRoot":"../.."} \ No newline at end of file diff --git a/content/dist/vendor-bundle.js b/content/dist/vendor-bundle.js new file mode 100644 index 0000000..5fada3e --- /dev/null +++ b/content/dist/vendor-bundle.js @@ -0,0 +1,28489 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 3.5.1 + * Features enabled: core + * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = Async; +module.exports.firstLineError = firstLineError; + +},{"./queue":17,"./schedule":18,"./util":21}],2:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + if (((this._bitField & 50397184) === 0)) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, undefined, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 2097152; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~2097152); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 2097152) === 2097152; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; +}; + +},{}],3:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise":15}],4:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise._isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent._isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + promise._setWillBeCancelled(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this._isCancellable()) return; + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype._isCancellable = function() { + return this.isPending() && !this._isCancelled(); +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this._isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; + +},{"./util":21}],5:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util"); +var getKeys = _dereq_("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; + +},{"./es5":10,"./util":21}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var longStackTraces = false; +var contextStack = []; + +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; +}; + +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; +}; + +},{}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, Context) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (true || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); + +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); + +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 524288); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 524288) !== 0) return; + this._setRejectionIsUnhandled(); + var self = this; + setTimeout(function() { + self._notifyUnhandledRejection(); + }, 1); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._setReturnedNonUndefined = function() { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._returnedNonUndefined = function() { + return (this._bitField & 268435456) !== 0; +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +var fireDomEvent = (function() { + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new CustomEvent(name.toLowerCase(), { + detail: event, + cancelable: true + }); + return !util.global.dispatchEvent(domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new Event(name.toLowerCase(), { + cancelable: true + }); + domEvent.detail = event; + return !util.global.dispatchEvent(domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name.toLowerCase(), false, true, + event); + return !util.global.dispatchEvent(domEvent); + }; + } + } catch (e) {} + return function() { + return false; + }; +})(); + +var fireGlobalEvent = (function() { + if (util.isNode) { + return function() { + return process.emit.apply(process, arguments); + }; + } else { + if (!util.global) { + return function() { + return false; + }; + } + return function(name) { + var methodName = "on" + name.toLowerCase(); + var method = util.global[methodName]; + if (!method) return false; + method.apply(util.global, [].slice.call(arguments, 1)); + return true; + }; + } +})(); + +function generatePromiseLifecycleEventObject(name, promise) { + return {promise: promise}; +} + +var eventToObjectGenerator = { + promiseCreated: generatePromiseLifecycleEventObject, + promiseFulfilled: generatePromiseLifecycleEventObject, + promiseRejected: generatePromiseLifecycleEventObject, + promiseResolved: generatePromiseLifecycleEventObject, + promiseCancelled: generatePromiseLifecycleEventObject, + promiseChained: function(name, promise, child) { + return {promise: promise, child: child}; + }, + warning: function(name, warning) { + return {warning: warning}; + }, + unhandledRejection: function (name, reason, promise) { + return {reason: reason, promise: promise}; + }, + rejectionHandled: generatePromiseLifecycleEventObject +}; + +var activeFireEvent = function (name) { + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent.apply(null, arguments); + } catch (e) { + async.throwLater(e); + globalEventFired = true; + } + + var domEventFired = false; + try { + domEventFired = fireDomEvent(name, + eventToObjectGenerator[name].apply(null, arguments)); + } catch (e) { + async.throwLater(e); + domEventFired = true; + } + + return domEventFired || globalEventFired; +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + var warningsOption = opts.warnings; + config.warnings = !!warningsOption; + wForgottenReturn = config.warnings; + + if (util.isObject(warningsOption)) { + if ("wForgottenReturn" in warningsOption) { + wForgottenReturn = !!warningsOption.wForgottenReturn; + } + } + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } + if ("monitoring" in opts) { + if (opts.monitoring && !config.monitoring) { + config.monitoring = true; + Promise.prototype._fireEvent = activeFireEvent; + } else if (!opts.monitoring && config.monitoring) { + config.monitoring = false; + Promise.prototype._fireEvent = defaultFireEvent; + } + } + return Promise; +}; + +function defaultFireEvent() { return false; } + +Promise.prototype._fireEvent = defaultFireEvent; +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } +} + +function cancellationAttachCancellationCallback(onCancel) { + if (!this._isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } +} + +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} + +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} + +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise, + parent) { + if (returnValue === undefined && promiseCreated !== null && + wForgottenReturn) { + if (parent !== undefined && parent._returnedNonUndefined()) return; + if ((promise._bitField & 65535) === 0) return; + + if (name) name = name + " "; + var handlerLine = ""; + var creatorLine = ""; + if (promiseCreated._trace) { + var traceLines = promiseCreated._trace.stack.split("\n"); + var stack = cleanStack(traceLines); + for (var i = stack.length - 1; i >= 0; --i) { + var line = stack[i]; + if (!nodeFramePattern.test(line)) { + var lineMatches = line.match(parseLinePattern); + if (lineMatches) { + handlerLine = "at " + lineMatches[1] + + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; + } + break; + } + } + + if (stack.length > 0) { + var firstUserLine = stack[0]; + for (var i = 0; i < traceLines.length; ++i) { + + if (traceLines[i] === firstUserLine) { + if (i > 0) { + creatorLine = "\n" + traceLines[i - 1]; + } + break; + } + } + + } + } + var msg = "a promise was created in a " + name + + "handler " + handlerLine + "but was not returned from it, " + + "see http://goo.gl/rRqMUw" + + creatorLine; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + + if (!activeFireEvent("warning", warning)) { + formatAndLogError(warning, "", true); + } +} + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = " (No stack trace)" === line || + stackFramePattern.test(line); + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0 && error.name != "SyntaxError") { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: error.name == "SyntaxError" ? stack : cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + if (name === "unhandledRejection") { + if (!activeFireEvent(name, reason, promise) && !localEventFired) { + formatAndLogError(reason, "Unhandled rejection "); + } + } else { + activeFireEvent(name, promise); + } +} + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +function longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit -= 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit -= 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } +} + +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false, + monitoring: false +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + monitoring: function() { + return config.monitoring; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace, + fireDomEvent: fireDomEvent, + fireGlobalEvent: fireGlobalEvent +}; +}; + +},{"./errors":9,"./util":21}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; + +},{}],9:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + es5.defineProperty(Error, "__BluebirdErrorTypes__", { + value: errorTypes, + writable: false, + enumerable: false, + configurable: false + }); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5":10,"./util":21}],10:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],11:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); + +function PassThroughHandlerContext(promise, type, handler) { + this.promise = promise; + this.type = type; + this.handler = handler; + this.called = false; + this.cancelPromise = null; +} + +PassThroughHandlerContext.prototype.isFinallyHandler = function() { + return this.type === 0; +}; + +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; +} + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; + } + return false; +} + +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + if (!this.called) { + this.called = true; + var ret = this.isFinallyHandler() + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret === NEXT_FILTER) { + return ret; + } else if (ret !== undefined) { + promise._setReturnedNonUndefined(); + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise._isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } + } + } + + if (promise.isRejected()) { + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; + } else { + checkCancel(this); + return reasonOrValue; + } +} + +Promise.prototype._passThrough = function(handler, type, success, fail) { + if (typeof handler !== "function") return this.then(); + return this._then(success, + fail, + undefined, + new PassThroughHandlerContext(this, type, handler), + undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); +}; + + +Promise.prototype.tap = function (handler) { + return this._passThrough(handler, 1, finallyHandler); +}; + +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + +return PassThroughHandlerContext; +}; + +},{"./catch_filter":5,"./util":21}],12:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, + getDomain) { +var util = _dereq_("./util"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); + }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise, async) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.asyncNeeded = true; \n\ + this.now = 0; \n\ + } \n\ + \n\ + [TheName].prototype._callFunction = function(promise) { \n\ + promise._pushContext(); \n\ + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + if (this.asyncNeeded) { \n\ + async.invoke(this._callFunction, this, promise); \n\ + } else { \n\ + this._callFunction(promise); \n\ + } \n\ + \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise, async); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", "async", code) + (tryCatch, errorObj, Promise, async); + }; + + var holderClasses = []; + var thenCallbacks = []; + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); + } + + reject = function (reason) { + this._reject(reason); + }; +}} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last <= 8 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); + var callbacks = thenCallbacks; + + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + promiseSetters[i](maybePromise, holder); + holder.asyncNeeded = false; + } else if (((bitField & 33554432) !== 0)) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else if (((bitField & 16777216) !== 0)) { + ret._reject(maybePromise._reason()); + } else { + ret._cancel(); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + + if (!ret._isFateSealed()) { + if (holder.asyncNeeded) { + var domain = getDomain(); + if (domain !== null) { + holder.fn = util.domainBind(domain, holder.fn); + } + } + ret._setAsyncGuaranteed(); + ret._setOnCancel(holder); + } + return ret; + } + } + } + var args = [].slice.call(arguments);; + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util":21}],13:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util":21}],14:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors"); +var OperationalError = errors.OperationalError; +var es5 = _dereq_("./es5"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise, multiArgs) { + return function(err, value) { + if (promise === null) return; + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (!multiArgs) { + promise._fulfill(value); + } else { + var args = [].slice.call(arguments, 1);; + promise._fulfill(args); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; + +},{"./errors":9,"./es5":10,"./util":21}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = _dereq_("./util"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var es5 = _dereq_("./es5"); +var Async = _dereq_("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = _dereq_("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {}; +var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = _dereq_("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; +var debug = _dereq_("./debuggability")(Promise, Context); +var CapturedTrace = debug.CapturedTrace; +var PassThroughHandlerContext = + _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + +} + +function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._resolveFromExecutor(executor); + this._promiseCreated(); + this._fireEvent("promiseCreated", this); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("Catch statement predicate: " + + "expecting an object but got " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + return this.then(undefined, catchFilter(catchInstances, fn, this)); + } + return this.then(undefined, fn); +}; + +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, undefined, undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.getNewLibraryCopy = module.exports; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + return async.setScheduler(fn); +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + this._fireEvent("promiseChained", this, promise); + } + + var domain = getDomain(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: domain === null ? handler + : (typeof handler === "function" && + util.domainBind(domain, handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; + this._fireEvent("promiseFulfilled", this); +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; + this._fireEvent("promiseRejected", this); +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; + this._fireEvent("promiseResolved", this); +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; + this._fireEvent("promiseCancelled", this); +}; + +Promise.prototype._setWillBeCancelled = function() { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + if (async.hasCustomScheduler()) return; + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : util.domainBind(domain, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : util.domainBind(domain, reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + var promise = maybePromise._target(); + + if (promise === this) { + this._reject(makeSelfResolutionError()); + return; + } + + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + if (executor === INTERNAL) return; + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj) { + promise._rejectCallback(x.e, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise, this); + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (receiver instanceof PassThroughHandlerContext && + receiver.isFinallyHandler()) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + async.settlePromises(this); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); +_dereq_("./direct_resolve")(Promise); +_dereq_("./synchronous_inspection")(Promise); +_dereq_("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); +Promise.Promise = Promise; +Promise.version = "3.5.1"; + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = _dereq_("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + case -6: return new Map(); + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise._isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util":21}],17:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],18:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var schedule; +var noAsyncScheduler = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var NativePromise = util.getNativePromise(); +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if (typeof NativePromise === "function" && + typeof NativePromise.resolve === "function") { + var nativePromise = NativePromise.resolve(); + schedule = function(fn) { + nativePromise.then(fn); + }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + (window.navigator.standalone || window.cordova))) { + schedule = (function() { + var div = document.createElement("div"); + var opts = {attributes: true}; + var toggleScheduled = false; + var div2 = document.createElement("div"); + var o2 = new MutationObserver(function() { + div.classList.toggle("foo"); + toggleScheduled = false; + }); + o2.observe(div2, opts); + + var scheduleToggle = function() { + if (toggleScheduled) return; + toggleScheduled = true; + div2.classList.toggle("foo"); + }; + + return function schedule(fn) { + var o = new MutationObserver(function() { + o.disconnect(); + fn(); + }); + o.observe(div, opts); + scheduleToggle(); + }; + })(); +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util":21}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; + } + else { + this._bitField = 0; + this._settledValueField = undefined; + } +} + +PromiseInspection.prototype._settledValue = function() { + return this._settledValueField; +}; + +var value = PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; +}; + +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; +}; + +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; +}; + +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = function() { + return (this._bitField & 8454144) !== 0; +}; + +Promise.prototype.__isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype._isCancelled = function() { + return this._target().__isCancelled(); +}; + +Promise.prototype.isCancelled = function() { + return (this._target()._bitField & 8454144) !== 0; +}; + +Promise.prototype.isPending = function() { + return isPending.call(this._target()); +}; + +Promise.prototype.isRejected = function() { + return isRejected.call(this._target()); +}; + +Promise.prototype.isFulfilled = function() { + return isFulfilled.call(this._target()); +}; + +Promise.prototype.isResolved = function() { + return isResolved.call(this._target()); +}; + +Promise.prototype.value = function() { + return value.call(this._target()); +}; + +Promise.prototype.reason = function() { + var target = this._target(); + target._unsetRejectionIsUnhandled(); + return reason.call(target); +}; + +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = getThen(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + try { + return hasProp.call(obj, "_promise0"); + } catch (e) { + return false; + } +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util":21}],21:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var canEvaluate = typeof navigator == "undefined"; + +var errorObj = {e: {}}; +var tryCatchTarget; +var globalObject = typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + this !== undefined ? this : null; + +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return typeof value === "function" || + typeof value === "object" && value !== null; +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; + } + +})(); + +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function FakeConstructor() {} + FakeConstructor.prototype = obj; + var l = 8; + while (l--) new FakeConstructor(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function isError(obj) { + return obj instanceof Error || + (obj !== null && + typeof obj === "object" && + typeof obj.message === "string" && + typeof obj.name === "string"); +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return isError(obj) && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } +} + +var asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; + +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; + + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} + +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; + +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; + +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} + +function getNativePromise() { + if (typeof Promise === "function") { + try { + var promise = new Promise(function(){}); + if ({}.toString.call(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +function domainBind(self, cb) { + return self.bind(cb); +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + isError: isError, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + domainBind: domainBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5":10}]},{},[3])(3) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } +//Configure Bluebird Promises. +Promise.config({ + warnings: { + wForgottenReturn: false + } +}); + +/** vim: et:ts=4:sw=4:sts=4 + * @license RequireJS 2.3.5 Copyright jQuery Foundation and other contributors. + * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE + */ +//Not using strict: uneven strict support in browsers, #392, and causes +//problems with requirejs.exec()/transpiler plugins that may not be strict. +/*jslint regexp: true, nomen: true, sloppy: true */ +/*global window, navigator, document, importScripts, setTimeout, opera */ + +var requirejs, require, define; +(function (global, setTimeout) { + var req, s, head, baseElement, dataMain, src, + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.3.5', + commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg, + cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, + jsSuffixRegExp = /\.js$/, + currDirRegExp = /^\.\//, + op = Object.prototype, + ostring = op.toString, + hasOwn = op.hasOwnProperty, + isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), + isWebWorker = !isBrowser && typeof importScripts !== 'undefined', + //PS3 indicates loaded and complete, but need to wait for complete + //specifically. Sequence is 'loading', 'loaded', execution, + // then 'complete'. The UA check is unfortunate, but not sure how + //to feature test w/o causing perf issues. + readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? + /^complete$/ : /^(complete|loaded)$/, + defContextName = '_', + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', + contexts = {}, + cfg = {}, + globalDefQueue = [], + useInteractive = false; + + //Could match something like ')//comment', do not lose the prefix to comment. + function commentReplace(match, singlePrefix) { + return singlePrefix || ''; + } + + function isFunction(it) { + return ostring.call(it) === '[object Function]'; + } + + function isArray(it) { + return ostring.call(it) === '[object Array]'; + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + /** + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. + */ + function eachReverse(ary, func) { + if (ary) { + var i; + for (i = ary.length - 1; i > -1; i -= 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function getOwn(obj, prop) { + return hasProp(obj, prop) && obj[prop]; + } + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + */ + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } + } + }); + } + return target; + } + + //Similar to Function.prototype.bind, but the 'this' object is specified + //first, since it is easier to read/figure out what 'this' will be. + function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + } + + function scripts() { + return document.getElementsByTagName('script'); + } + + function defaultOnError(err) { + throw err; + } + + //Allow getting a global that is expressed in + //dot notation, like 'a.b.c'. + function getGlobal(value) { + if (!value) { + return value; + } + var g = global; + each(value.split('.'), function (part) { + g = g[part]; + }); + return g; + } + + /** + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. + * + * @returns {Error} + */ + function makeError(id, msg, err, requireModules) { + var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); + e.requireType = id; + e.requireModules = requireModules; + if (err) { + e.originalError = err; + } + return e; + } + + if (typeof define !== 'undefined') { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } + + if (typeof requirejs !== 'undefined') { + if (isFunction(requirejs)) { + //Do not overwrite an existing requirejs instance. + return; + } + cfg = requirejs; + requirejs = undefined; + } + + //Allow for a require config object + if (typeof require !== 'undefined' && !isFunction(require)) { + //assume it is a config object. + cfg = require; + require = undefined; + } + + function newContext(contextName) { + var inCheckLoaded, Module, context, handlers, + checkLoadedTimeoutId, + config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. + waitSeconds: 7, + baseUrl: './', + paths: {}, + bundles: {}, + pkgs: {}, + shim: {}, + config: {} + }, + registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, + undefEvents = {}, + defQueue = [], + defined = {}, + urlFetched = {}, + bundlesMap = {}, + requireCounter = 1, + unnormalizedCounter = 1; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; i < ary.length; i++) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @param {Boolean} applyMap apply the map config to the value. Should + * only be done if this normalization is for a dependency ID. + * @returns {String} normalized name + */ + function normalize(name, baseName, applyMap) { + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), + map = config.map, + starMap = map && map['*']; + + //Adjust any relative paths. + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; + + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); + } + + //Apply map config if available. + if (applyMap && map && (baseParts || starMap)) { + nameParts = name.split('/'); + + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join('/'); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = getOwn(map, baseParts.slice(0, j).join('/')); + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = getOwn(mapValue, nameSegment); + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break outerLoop; + } + } + } + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { + foundStarMap = getOwn(starMap, nameSegment); + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; + } + + function removeScript(name) { + if (isBrowser) { + each(scripts(), function (scriptNode) { + if (scriptNode.getAttribute('data-requiremodule') === name && + scriptNode.getAttribute('data-requirecontext') === context.contextName) { + scriptNode.parentNode.removeChild(scriptNode); + return true; + } + }); + } + } + + function hasPathFallback(id) { + var pathConfig = getOwn(config.paths, id); + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.require.undef(id); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + + return true; + } + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * @param {Boolean} isNormalized: is the ID already normalized. + * This is true if this call is done for a define() module ID. + * @param {Boolean} applyMap: apply the map config to the ID. + * Should only be true if this map is for a dependency. + * + * @returns {Object} + */ + function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { + var url, pluginModule, suffix, nameParts, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + isDefine = true, + normalizedName = ''; + + //If no name, then it means it is a require call, generate an + //internal name. + if (!name) { + isDefine = false; + name = '_@r' + (requireCounter += 1); + } + + nameParts = splitPrefix(name); + prefix = nameParts[0]; + name = nameParts[1]; + + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = getOwn(defined, prefix); + } + + //Account for relative paths if there is a base name. + if (name) { + if (prefix) { + if (isNormalized) { + normalizedName = name; + } else if (pluginModule && pluginModule.normalize) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize(name, function (name) { + return normalize(name, parentName, applyMap); + }); + } else { + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; + } + } else { + //A regular module. + normalizedName = normalize(name, parentName, applyMap); + + //Normalized name may be a plugin ID due to map config + //application in normalize. The map config values must + //already be normalized, so do not need to redo that part. + nameParts = splitPrefix(normalizedName); + prefix = nameParts[0]; + normalizedName = nameParts[1]; + isNormalized = true; + + url = context.nameToUrl(normalizedName); + } + } + + //If the id is a plugin id that cannot be determined if it needs + //normalization, stamp it with a unique ID so two matching relative + //ids that may conflict can be separate. + suffix = prefix && !pluginModule && !isNormalized ? + '_unnormalized' + (unnormalizedCounter += 1) : + ''; + + return { + prefix: prefix, + name: normalizedName, + parentMap: parentModuleMap, + unnormalized: !!suffix, + url: url, + originalName: originalName, + isDefine: isDefine, + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix + }; + } + + function getModule(depMap) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (!mod) { + mod = registry[id] = new context.Module(depMap); + } + + return mod; + } + + function on(depMap, name, fn) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); + } + } + } + + function onError(err, errback) { + var ids = err.requireModules, + notified = false; + + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = getOwn(registry, id); + if (mod) { + //Set error on module, so it skips timeout checks. + mod.error = err; + if (mod.events.error) { + notified = true; + mod.emit('error', err); + } + } + }); + + if (!notified) { + req.onError(err); + } + } + } + + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + function takeGlobalQueue() { + //Push all the globalDefQueue items into the context's defQueue + if (globalDefQueue.length) { + each(globalDefQueue, function(queueItem) { + var id = queueItem[0]; + if (typeof id === 'string') { + context.defQueueMap[id] = true; + } + defQueue.push(queueItem); + }); + globalDefQueue = []; + } + } + + handlers = { + 'require': function (mod) { + if (mod.require) { + return mod.require; + } else { + return (mod.require = context.makeRequire(mod.map)); + } + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + if (mod.exports) { + return (defined[mod.map.id] = mod.exports); + } else { + return (mod.exports = defined[mod.map.id] = {}); + } + } + }, + 'module': function (mod) { + if (mod.module) { + return mod.module; + } else { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return getOwn(config.config, mod.map.id) || {}; + }, + exports: mod.exports || (mod.exports = {}) + }); + } + } + }; + + function cleanRegistry(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + delete enabledRegistry[id]; + } + + function breakCycle(mod, traced, processed) { + var id = mod.map.id; + + if (mod.error) { + mod.emit('error', mod.error); + } else { + traced[id] = true; + each(mod.depMaps, function (depMap, i) { + var depId = depMap.id, + dep = getOwn(registry, depId); + + //Only force things that have not completed + //being defined, so still in the registry, + //and only if it has not been matched up + //in the module already. + if (dep && !mod.depMatched[i] && !processed[depId]) { + if (getOwn(traced, depId)) { + mod.defineDep(i, defined[depId]); + mod.check(); //pass false? + } else { + breakCycle(dep, traced, processed); + } + } + }); + processed[id] = true; + } + } + + function checkLoaded() { + var err, usingPathFallback, + waitInterval = config.waitSeconds * 1000, + //It is possible to disable the wait interval by using waitSeconds of 0. + expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), + noLoads = [], + reqCalls = [], + stillLoading = false, + needCycleCheck = true; + + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { + return; + } + + inCheckLoaded = true; + + //Figure out the state of all the modules. + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; + + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + if (!map.isDefine) { + reqCalls.push(mod); + } + + if (!mod.error) { + //If the module should be executed, and it has not + //been inited and time is up, remember it. + if (!mod.inited && expired) { + if (hasPathFallback(modId)) { + usingPathFallback = true; + stillLoading = true; + } else { + noLoads.push(modId); + removeScript(modId); + } + } else if (!mod.inited && mod.fetched && map.isDefine) { + stillLoading = true; + if (!map.prefix) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + return (needCycleCheck = false); + } + } + } + }); + + if (expired && noLoads.length) { + //If wait time expired, throw error of unloaded modules. + err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); + err.contextName = context.contextName; + return onError(err); + } + + //Not expired, check for a cycle. + if (needCycleCheck) { + each(reqCalls, function (mod) { + breakCycle(mod, {}, {}); + }); + } + + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ((!expired || usingPathFallback) && stillLoading) { + //Something is still waiting to load. Wait for it, but only + //if a timeout is not already in effect. + if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { + checkLoadedTimeoutId = setTimeout(function () { + checkLoadedTimeoutId = 0; + checkLoaded(); + }, 50); + } + } + + inCheckLoaded = false; + } + + Module = function (map) { + this.events = getOwn(undefEvents, map.id) || {}; + this.map = map; + this.shim = getOwn(config.shim, map.id); + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; + + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; + + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; + + //Do not do more inits if already done. Can happen if there + //are multiple define calls for the same module. That is not + //a normal, common case, but it is also not unexpected. + if (this.inited) { + return; + } + + this.factory = factory; + + if (errback) { + //Register for errors on this module. + this.on('error', errback); + } else if (this.events.error) { + //If no errback already, but there are error listeners + //on this module, set up an errback to pass to the deps. + errback = bind(this, function (err) { + this.emit('error', err); + }); + } + + //Do a copy of the dependency array, so that + //source inputs are not modified. For example + //"shim" deps are passed in here directly, and + //doing a direct modification of the depMaps array + //would affect that config. + this.depMaps = depMaps && depMaps.slice(0); + + this.errback = errback; + + //Indicate this module has be initialized + this.inited = true; + + this.ignore = options.ignore; + + //Could have option to init this module in enabled mode, + //or could have been previously marked as enabled. However, + //the dependencies are not known until init is called. So + //if enabled previously, now trigger dependencies as enabled. + if (options.enabled || this.enabled) { + //Enable this module and dependencies. + //Will call this.check() + this.enable(); + } else { + this.check(); + } + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, + + fetch: function () { + if (this.fetched) { + return; + } + this.fetched = true; + + context.startTime = (new Date()).getTime(); + + var map = this.map; + + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if (this.shim) { + context.makeRequire(this.map, { + enableBuildCallback: true + })(this.shim.deps || [], bind(this, function () { + return map.prefix ? this.callPlugin() : this.load(); + })); + } else { + //Regular dependency. + return map.prefix ? this.callPlugin() : this.load(); + } + }, + + load: function () { + var url = this.map.url; + + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks if the module is ready to define itself, and if so, + * define it. + */ + check: function () { + if (!this.enabled || this.enabling) { + return; + } + + var err, cjsModule, + id = this.map.id, + depExports = this.depExports, + exports = this.exports, + factory = this.factory; + + if (!this.inited) { + // Only fetch if not already in the defQueue. + if (!hasProp(context.defQueueMap, id)) { + this.fetch(); + } + } else if (this.error) { + this.emit('error', this.error); + } else if (!this.defining) { + //The factory could trigger another require call + //that would result in checking this module to + //define itself again. If already in the process + //of doing that, skip this work. + this.defining = true; + + if (this.depCount < 1 && !this.defined) { + if (isFunction(factory)) { + //If there is an error listener, favor passing + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //errbacks should not be called for failures in + //their callbacks (#699). However if a global + //onError is set, use that. + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { + cjsModule = this.module; + if (cjsModule) { + exports = cjsModule.exports; + } else if (this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } + + this.exports = exports; + + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; + + if (req.onResourceLoad) { + var resLoadMaps = []; + each(this.depMaps, function (depMap) { + resLoadMaps.push(depMap.normalizedMap || depMap); + }); + req.onResourceLoad(context, this.map, resLoadMaps); + } + } + + //Clean up + cleanRegistry(id); + + this.defined = true; + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (this.defined && !this.defineEmitted) { + this.defineEmitted = true; + this.emit('defined', this.exports); + this.defineEmitComplete = true; + } + + } + }, + + callPlugin: function () { + var map = this.map, + id = map.id, + //Map already normalized the prefix. + pluginMap = makeModuleMap(map.prefix); + + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(pluginMap); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + bundleId = getOwn(bundlesMap, this.map.id), + name = this.map.name, + parentName = this.map.parentMap ? this.map.parentMap.name : null, + localRequire = context.makeRequire(map.parentMap, { + enableBuildCallback: true + }); + + //If current map is not normalized, wait for that + //normalized name to load instead of continuing. + if (this.map.unnormalized) { + //Normalize the ID if the plugin allows it. + if (plugin.normalize) { + name = plugin.normalize(name, function (name) { + return normalize(name, parentName, true); + }) || ''; + } + + //prefix and name should already be normalized, no need + //for applying map config again either. + normalizedMap = makeModuleMap(map.prefix + '!' + name, + this.map.parentMap, + true); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.map.normalizedMap = normalizedMap; + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); + + normalizedMod = getOwn(registry, normalizedMap.id); + if (normalizedMod) { + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(normalizedMap); + + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + return; + } + + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + + load = bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true + }); + }); + + load.error = bind(this, function (err) { + this.inited = true; + this.error = err; + err.requireModules = [id]; + + //Remove temp unnormalized modules for this module, + //since they will never be resolved otherwise now. + eachProp(registry, function (mod) { + if (mod.map.id.indexOf(id + '_unnormalized') === 0) { + cleanRegistry(mod.map.id); + } + }); + + onError(err); + }); + + //Allow plugins to load other code without having to know the + //context or how to 'complete' the load. + load.fromText = bind(this, function (text, textAlt) { + /*jslint evil: true */ + var moduleName = map.name, + moduleMap = makeModuleMap(moduleName), + hasInteractive = useInteractive; + + //As of 2.1.0, support just passing the text, to reinforce + //fromText only being called once per resource. Still + //support old style of passing moduleName but discard + //that moduleName in favor of the internal ref. + if (textAlt) { + text = textAlt; + } + + //Turn off interactive script matching for IE for any define + //calls in the text, then turn it back on at the end. + if (hasInteractive) { + useInteractive = false; + } + + //Prime the system by creating a module instance for + //it. + getModule(moduleMap); + + //Transfer any config to this other module. + if (hasProp(config.config, id)) { + config.config[moduleName] = config.config[id]; + } + + try { + req.exec(text); + } catch (e) { + return onError(makeError('fromtexteval', + 'fromText eval for ' + id + + ' failed: ' + e, + e, + [id])); + } + + if (hasInteractive) { + useInteractive = true; + } + + //Mark this as a dependency for the plugin + //resource + this.depMaps.push(moduleMap); + + //Support anonymous modules. + context.completeLoad(moduleName); + + //Bind the value of that module to the value for this + //resource ID. + localRequire([moduleName], load); + }); + + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load(map.name, localRequire, load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + enabledRegistry[this.map.id] = this; + this.enabled = true; + + //Set flag mentioning that the module is enabling, + //so that immediate calls to the defined callbacks + //for dependencies do not trigger inadvertent load + //with the depCount still being zero. + this.enabling = true; + + //Enable each dependency + each(this.depMaps, bind(this, function (depMap, i) { + var id, mod, handler; + + if (typeof depMap === 'string') { + //Dependency needs to be converted to a depMap + //and wired up to this module. + depMap = makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, + !this.skipMap); + this.depMaps[i] = depMap; + + handler = getOwn(handlers, depMap.id); + + if (handler) { + this.depExports[i] = handler(this); + return; + } + + this.depCount += 1; + + on(depMap, 'defined', bind(this, function (depExports) { + if (this.undefed) { + return; + } + this.defineDep(i, depExports); + this.check(); + })); + + if (this.errback) { + on(depMap, 'error', bind(this, this.errback)); + } else if (this.events.error) { + // No direct errback on this module, but something + // else is listening for errors, so be sure to + // propagate the error correctly. + on(depMap, 'error', bind(this, function(err) { + this.emit('error', err); + })); + } + } + + id = depMap.id; + mod = registry[id]; + + //Skip special modules like 'require', 'exports', 'module' + //Also, don't call enable if it is already enabled, + //important in circular dependency cases. + if (!hasProp(handlers, id) && mod && !mod.enabled) { + context.enable(depMap, this); + } + })); + + //Enable each plugin that is used in + //a dependency + eachProp(this.pluginMaps, bind(this, function (pluginMap) { + var mod = getOwn(registry, pluginMap.id); + if (mod && !mod.enabled) { + context.enable(pluginMap, this); + } + })); + + this.enabling = false; + + this.check(); + }, + + on: function (name, cb) { + var cbs = this.events[name]; + if (!cbs) { + cbs = this.events[name] = []; + } + cbs.push(cb); + }, + + emit: function (name, evt) { + each(this.events[name], function (cb) { + cb(evt); + }); + if (name === 'error') { + //Now that the error handler was triggered, remove + //the listeners, since this broken Module instance + //can stay around for a while in the registry. + delete this.events[name]; + } + } + }; + + function callGetModule(args) { + //Skip modules already defined. + if (!hasProp(defined, args[0])) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); + } + } + + function removeListener(node, func, name, ieName) { + //Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if (node.detachEvent && !isOpera) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + if (ieName) { + node.detachEvent(ieName, func); + } + } else { + node.removeEventListener(name, func, false); + } + } + + /** + * Given an event from a script node, get the requirejs info from it, + * and then removes the event listeners on the node. + * @param {Event} evt + * @returns {Object} + */ + function getScriptData(evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + var node = evt.currentTarget || evt.srcElement; + + //Remove the listeners once here. + removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); + removeListener(node, context.onScriptError, 'error'); + + return { + node: node, + id: node && node.getAttribute('data-requiremodule') + }; + } + + function intakeDefines() { + var args; + + //Any defined modules in the global queue, intake them now. + takeGlobalQueue(); + + //Make sure any remaining defQueue items get properly processed. + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + + args[args.length - 1])); + } else { + //args are id, deps, factory. Should be normalized by the + //define() function. + callGetModule(args); + } + } + context.defQueueMap = {}; + } + + context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + defQueue: defQueue, + defQueueMap: {}, + Module: Module, + makeModuleMap: makeModuleMap, + nextTick: req.nextTick, + onError: onError, + + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure: function (cfg) { + //Make sure the baseUrl ends in a slash. + if (cfg.baseUrl) { + if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { + cfg.baseUrl += '/'; + } + } + + // Convert old style urlArgs string to a function. + if (typeof cfg.urlArgs === 'string') { + var urlArgs = cfg.urlArgs; + cfg.urlArgs = function(id, url) { + return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; + }; + } + + //Save off the paths since they require special processing, + //they are additive. + var shim = config.shim, + objs = { + paths: true, + bundles: true, + config: true, + map: true + }; + + eachProp(cfg, function (value, prop) { + if (objs[prop]) { + if (!config[prop]) { + config[prop] = {}; + } + mixin(config[prop], value, true, true); + } else { + config[prop] = value; + } + }); + + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if ((value.exports || value.init) && !value.exportsFn) { + value.exportsFn = context.makeShimExports(value); + } + shim[id] = value; + }); + config.shim = shim; + } + + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location, name; + + pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; + + name = pkgObj.name; + location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } + + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); + }); + } + + //If there are any "waiting to execute" modules in the registry, + //update the maps for them, since their info, like URLs to load, + //may have changed. + eachProp(registry, function (mod, id) { + //If module already has init called, since it is too + //late to modify them, and ignore unnormalized ones + //since they are transient. + if (!mod.inited && !mod.map.unnormalized) { + mod.map = makeModuleMap(id, null, true); + } + }); + + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if (cfg.deps || cfg.callback) { + context.require(cfg.deps || [], cfg.callback); + } + }, + + makeShimExports: function (value) { + function fn() { + var ret; + if (value.init) { + ret = value.init.apply(global, arguments); + } + return ret || (value.exports && getGlobal(value.exports)); + } + return fn; + }, + + makeRequire: function (relMap, options) { + options = options || {}; + + function localRequire(deps, callback, errback) { + var id, map, requireMod; + + if (options.enableBuildCallback && callback && isFunction(callback)) { + callback.__requireJsBuild = true; + } + + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //If require|exports|module are requested, get the + //value for them from the special handlers. Caveat: + //this only works while module is being defined. + if (relMap && hasProp(handlers, deps)) { + return handlers[deps](registry[relMap.id]); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + if (req.get) { + return req.get(context, deps, relMap, localRequire); + } + + //Normalize module name, if it contains . or .. + map = makeModuleMap(deps, relMap, false, true); + id = map.id; + + if (!hasProp(defined, id)) { + return onError(makeError('notloaded', 'Module name "' + + id + + '" has not been loaded yet for context: ' + + contextName + + (relMap ? '' : '. Use require([])'))); + } + return defined[id]; + } + + //Grab defines waiting in the global queue. + intakeDefines(); + + //Mark all the dependencies as needing to be loaded. + context.nextTick(function () { + //Some defines could have been added since the + //require call, collect them. + intakeDefines(); + + requireMod = getModule(makeModuleMap(null, relMap)); + + //Store if map config should be applied to this require + //call for dependencies. + requireMod.skipMap = options.skipMap; + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + }); + + return localRequire; + } + + mixin(localRequire, { + isBrowser: isBrowser, + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl: function (moduleNamePlusExt) { + var ext, + index = moduleNamePlusExt.lastIndexOf('.'), + segment = moduleNamePlusExt.split('/')[0], + isRelative = segment === '.' || segment === '..'; + + //Have a file extension alias, and it is not the + //dots from a relative path. + if (index !== -1 && (!isRelative || index > 1)) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } + + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); + }, + + defined: function (id) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, + + specified: function (id) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + } + }); + + //Only allow undef on top level require calls + if (!relMap) { + localRequire.undef = function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, relMap, true), + mod = getOwn(registry, id); + + mod.undefed = true; + removeScript(id); + + delete defined[id]; + delete urlFetched[map.url]; + delete undefEvents[id]; + + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if (args[0] === id) { + defQueue.splice(i, 1); + } + }); + delete context.defQueueMap[id]; + + if (mod) { + //Hold on to listeners in case the + //module will be attempted to be reloaded + //using a different config. + if (mod.events.defined) { + undefEvents[id] = mod.events; + } + + cleanRegistry(id); + } + }; + } + + return localRequire; + }, + + /** + * Called to enable a module if it is still in the registry + * awaiting enablement. A second arg, parent, the parent module, + * is passed in for context, when this method is overridden by + * the optimizer. Not shown here to keep code compact. + */ + enable: function (depMap) { + var mod = getOwn(registry, depMap.id); + if (mod) { + getModule(depMap).enable(); + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad: function (moduleName) { + var found, args, mod, + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; + + takeGlobalQueue(); + + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + args[0] = moduleName; + //If already found an anonymous module and bound it + //to this name, then this is some other anon module + //waiting for its completeLoad to fire. + if (found) { + break; + } + found = true; + } else if (args[0] === moduleName) { + //Found matching define call for this script! + found = true; + } + + callGetModule(args); + } + context.defQueueMap = {}; + + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = getOwn(registry, moduleName); + + if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { + if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { + if (hasPathFallback(moduleName)) { + return; + } else { + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); + } + } else { + //A script that does not call define(), so just simulate + //the call for it. + callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); + } + } + + checkLoaded(); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + * Note that it **does not** call normalize on the moduleName, + * it is assumed to have already been normalized. This is an + * internal API, not a public one. Use toUrl for the public API. + */ + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } + + //If a colon is in the URL, it indicates a protocol is used and it is just + //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) + //or ends with .js, then assume the user meant to use an url and not a module id. + //The slash is important for protocol-less URLs as well as full paths. + if (req.jsExtRegExp.test(moduleName)) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext || ''); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + + syms = moduleName.split('/'); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for (i = syms.length; i > 0; i -= 1) { + parentModule = syms.slice(0, i).join('/'); + + parentPath = getOwn(paths, parentModule); + if (parentPath) { + //If an array, it means there are a few choices, + //Choose the one that is desired + if (isArray(parentPath)) { + parentPath = parentPath[0]; + } + syms.splice(0, i, parentPath); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; + } + + return config.urlArgs && !/^blob\:/.test(url) ? + url + config.urlArgs(moduleName, url) : url; + }, + + //Delegates to req.load. Broken out as a separate function to + //allow overriding in the optimizer. + load: function (id, url) { + req.load(context, id, url); + }, + + /** + * Executes a module callback function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + execCb: function (name, callback, args, exports) { + return callback.apply(exports, args); + }, + + /** + * callback for script loads, used to check status of loading. + * + * @param {Event} evt the event from the browser for the script + * that was loaded. + */ + onScriptLoad: function (evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + if (evt.type === 'load' || + (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { + //Reset interactive script so a script node is not held onto for + //to long. + interactiveScript = null; + + //Pull out the name of the module and the context. + var data = getScriptData(evt); + context.completeLoad(data.id); + } + }, + + /** + * Callback for script errors. + */ + onScriptError: function (evt) { + var data = getScriptData(evt); + if (!hasPathFallback(data.id)) { + var parents = []; + eachProp(registry, function(value, key) { + if (key.indexOf('_@r') !== 0) { + each(value.depMaps, function(depMap) { + if (depMap.id === data.id) { + parents.push(key); + return true; + } + }); + } + }); + return onError(makeError('scripterror', 'Script error for "' + data.id + + (parents.length ? + '", needed by: ' + parents.join(', ') : + '"'), evt, [data.id])); + } + } + }; + + context.require = context.makeRequire(); + return context; + } + + /** + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. + * + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. + */ + req = requirejs = function (deps, callback, errback, optional) { + + //Find the right context, use default + var context, config, + contextName = defContextName; + + // Determine if have config object in the call. + if (!isArray(deps) && typeof deps !== 'string') { + // deps is a config object + config = deps; + if (isArray(callback)) { + // Adjust args if there are dependencies + deps = callback; + callback = errback; + errback = optional; + } else { + deps = []; + } + } + + if (config && config.context) { + contextName = config.context; + } + + context = getOwn(contexts, contextName); + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); + } + + if (config) { + context.configure(config); + } + + return context.require(deps, callback, errback); + }; + + /** + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. + */ + req.config = function (config) { + return req(config); + }; + + /** + * Execute something after the current tick + * of the event loop. Override for other envs + * that have a better solution than setTimeout. + * @param {Function} fn function to execute later. + */ + req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { + setTimeout(fn, 4); + } : function (fn) { fn(); }; + + /** + * Export require as a global, but only if it does not already exist. + */ + if (!require) { + require = req; + } + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + req.isBrowser = isBrowser; + s = req.s = { + contexts: contexts, + newContext: newContext + }; + + //Create default context. + req({}); + + //Exports some context-sensitive methods on global require. + each([ + 'toUrl', + 'undef', + 'defined', + 'specified' + ], function (prop) { + //Reference from contexts instead of early binding to default context, + //so that during builds, the latest instance of the default context + //with its config gets used. + req[prop] = function () { + var ctx = contexts[defContextName]; + return ctx.require[prop].apply(ctx, arguments); + }; + }); + + if (isBrowser) { + head = s.head = document.getElementsByTagName('head')[0]; + //If BASE tag is in play, using appendChild is a problem for IE6. + //When that browser dies, this can be removed. Details in this jQuery bug: + //http://dev.jquery.com/ticket/2709 + baseElement = document.getElementsByTagName('base')[0]; + if (baseElement) { + head = s.head = baseElement.parentNode; + } + } + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = defaultOnError; + + /** + * Creates the node for the load command. Only used in browser envs. + */ + req.createNode = function (config, moduleName, url) { + var node = config.xhtml ? + document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : + document.createElement('script'); + node.type = config.scriptType || 'text/javascript'; + node.charset = 'utf-8'; + node.async = true; + return node; + }; + + /** + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. + */ + req.load = function (context, moduleName, url) { + var config = (context && context.config) || {}, + node; + if (isBrowser) { + //In the browser so use a script tag + node = req.createNode(config, moduleName, url); + + node.setAttribute('data-requirecontext', context.contextName); + node.setAttribute('data-requiremodule', moduleName); + + //Set up load listener. Test attachEvent first because IE9 has + //a subtle issue in its addEventListener and script onload firings + //that do not match the behavior of all other browsers with + //addEventListener support, which fire the onload event for a + //script right after the script execution. See: + //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution + //UNFORTUNATELY Opera implements attachEvent but does not follow the script + //script execution mode. + if (node.attachEvent && + //Check if node.attachEvent is artificially added by custom script or + //natively supported by browser + //read https://github.com/requirejs/requirejs/issues/187 + //if we can NOT find [native code] then it must NOT natively supported. + //in IE8, node.attachEvent does not have toString() + //Note the test for "[native code" with no closing brace, see: + //https://github.com/requirejs/requirejs/issues/273 + !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && + !isOpera) { + //Probably IE. IE (at least 6-8) do not fire + //script onload right after executing the script, so + //we cannot tie the anonymous define call to a name. + //However, IE reports the script as being in 'interactive' + //readyState at the time of the define call. + useInteractive = true; + + node.attachEvent('onreadystatechange', context.onScriptLoad); + //It would be great to add an error handler here to catch + //404s in IE9+. However, onreadystatechange will fire before + //the error handler, so that does not help. If addEventListener + //is used, then IE will fire error before load, but we cannot + //use that pathway given the connect.microsoft.com issue + //mentioned above about not doing the 'script execute, + //then fire the script load event listener before execute + //next script' that other browsers do. + //Best hope: IE10 fixes the issues, + //and then destroys all installs of IE 6-9. + //node.attachEvent('onerror', context.onScriptError); + } else { + node.addEventListener('load', context.onScriptLoad, false); + node.addEventListener('error', context.onScriptError, false); + } + node.src = url; + + //Calling onNodeCreated after all properties on the node have been + //set, but before it is placed in the DOM. + if (config.onNodeCreated) { + config.onNodeCreated(node, config, moduleName, url); + } + + //For some cache cases in IE 6-8, the script executes before the end + //of the appendChild execution, so to tie an anonymous define + //call to the module name (which is stored on the node), hold on + //to a reference to this node, but clear after the DOM insertion. + currentlyAddingScript = node; + if (baseElement) { + head.insertBefore(node, baseElement); + } else { + head.appendChild(node); + } + currentlyAddingScript = null; + + return node; + } else if (isWebWorker) { + try { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation is that a build has been done so + //that only one script needs to be loaded anyway. This may need + //to be reevaluated if other use cases become common. + + // Post a task to the event loop to work around a bug in WebKit + // where the worker gets garbage-collected after calling + // importScripts(): https://webkit.org/b/153317 + setTimeout(function() {}, 0); + importScripts(url); + + //Account for anonymous modules + context.completeLoad(moduleName); + } catch (e) { + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); + } + } + }; + + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; + } + + eachReverse(scripts(), function (script) { + if (script.readyState === 'interactive') { + return (interactiveScript = script); + } + }); + return interactiveScript; + } + + //Look for a data-main script attribute, which could also adjust the baseUrl. + if (isBrowser && !cfg.skipDataMain) { + //Figure out baseUrl. Get it from the script tag with require.js in it. + eachReverse(scripts(), function (script) { + //Set the 'head' where we can append children by + //using the script's parent. + if (!head) { + head = script.parentNode; + } + + //Look for a data-main attribute to set main script for the page + //to load. If it is there, the path to data main becomes the + //baseUrl, if it is not already set. + dataMain = script.getAttribute('data-main'); + if (dataMain) { + //Preserve dataMain in case it is a path (i.e. contains '?') + mainScript = dataMain; + + //Set final baseUrl if there is not already an explicit one, + //but only do so if the data-main value is not a loader plugin + //module ID. + if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { + //Pull off the directory of data-main for use as the + //baseUrl. + src = mainScript.split('/'); + mainScript = src.pop(); + subPath = src.length ? src.join('/') + '/' : './'; + + cfg.baseUrl = subPath; + } + + //Strip off any trailing .js since mainScript is now + //like a module name. + mainScript = mainScript.replace(jsSuffixRegExp, ''); + + //If mainScript is still a path, fall back to dataMain + if (req.jsExtRegExp.test(mainScript)) { + mainScript = dataMain; + } + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; + + return true; + } + }); + } + + /** + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. + */ + define = function (name, deps, callback) { + var node, context; + + //Allow for anonymous modules + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = null; + } + + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if (!deps && isFunction(callback)) { + deps = []; + //Remove comments from the callback string, + //look for require calls, and pull them into the dependencies, + //but only if there are function args. + if (callback.length) { + callback + .toString() + .replace(commentRegExp, commentReplace) + .replace(cjsRequireRegExp, function (match, dep) { + deps.push(dep); + }); + + //May be a CommonJS thing even without require calls, but still + //could use exports, and module. Avoid doing exports and module + //work though if it just needs require. + //REQUIRES the function to expect the CommonJS variables in the + //order listed below. + deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); + } + } + + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if (useInteractive) { + node = currentlyAddingScript || getInteractiveScript(); + if (node) { + if (!name) { + name = node.getAttribute('data-requiremodule'); + } + context = contexts[node.getAttribute('data-requirecontext')]; + } + } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + if (context) { + context.defQueue.push([name, deps, callback]); + context.defQueueMap[name] = true; + } else { + globalDefQueue.push([name, deps, callback]); + } + }; + + define.amd = { + jQuery: true + }; + + /** + * Executes the text. Normally just uses eval, but can be modified + * to use a better, environment-specific call. Only used for transpiling + * loader plugins, not for plain JS modules. + * @param {String} text the text to execute/evaluate. + */ + req.exec = function (text) { + /*jslint evil: true */ + return eval(text); + }; + + //Set up with config info. + req(cfg); +}(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout))); + +_aureliaConfigureModuleLoader(); +define('text',{}); +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +define('aurelia-testing/wait',["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + /** + * Generic function to wait for something to happen. Uses polling + * @param getter: a getter function that returns anything else than `null` or an + * empty array or an empty jQuery object when the + * condition is met + * @param options: lookup options, defaults to + * `{present: true, interval: 50, timeout: 5000}` + */ + function waitFor(getter, options) { + if (options === void 0) { options = { present: true, interval: 50, timeout: 5000 }; } + // prevents infinite recursion if the request times out + var timedOut = false; + options = __assign({ present: true, interval: 50, timeout: 5000 }, options); + function wait() { + var element = getter(); + // boolean is needed here, hence the length > 0 + var found = element !== null && (!(element instanceof NodeList) && + !element.jquery || element.length > 0); + if (!options.present === !found || timedOut) { + return Promise.resolve(element); + } + return new Promise(function (rs) { return setTimeout(rs, options.interval); }).then(wait); + } + return Promise.race([ + new Promise(function (_, rj) { return setTimeout(function () { + timedOut = true; + rj(options.present ? 'Element not found' : 'Element not removed'); + }, options.timeout); }), + wait() + ]); + } + exports.waitFor = waitFor; + function waitForDocumentElement(selector, options) { + return waitFor(function () { return document.querySelector(selector); }, options); + } + exports.waitForDocumentElement = waitForDocumentElement; + function waitForDocumentElements(selector, options) { + return waitFor(function () { return document.querySelectorAll(selector); }, options); + } + exports.waitForDocumentElements = waitForDocumentElements; +}); + +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +define('aurelia-testing/view-spy',["require", "exports", "aurelia-templating", "aurelia-logging"], function (require, exports, aurelia_templating_1, aurelia_logging_1) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + /** + * Attribute to be placed on any HTML element in a view to emit the View instance + * to the debug console, giving you insight into the live View instance, including + * all child views, live bindings, behaviors and more. + */ + var ViewSpy = /** @class */ (function () { + /** + * Creates a new instance of ViewSpy. + */ + function ViewSpy() { + this.logger = aurelia_logging_1.getLogger('view-spy'); + } + ViewSpy.prototype._log = function (lifecycleName, context) { + if (!this.value && lifecycleName === 'created') { + this.logger.info(lifecycleName, this.view); + } + else if (this.value && this.value.indexOf(lifecycleName) !== -1) { + this.logger.info(lifecycleName, this.view, context); + } + }; + /** + * Invoked when the target view is created. + * @param view The target view. + */ + ViewSpy.prototype.created = function (view) { + this.view = view; + this._log('created'); + }; + /** + * Invoked when the target view is bound. + * @param bindingContext The target view's binding context. + */ + ViewSpy.prototype.bind = function (bindingContext) { + this._log('bind', bindingContext); + }; + /** + * Invoked when the target element is attached to the DOM. + */ + ViewSpy.prototype.attached = function () { + this._log('attached'); + }; + /** + * Invoked when the target element is detached from the DOM. + */ + ViewSpy.prototype.detached = function () { + this._log('detached'); + }; + /** + * Invoked when the target element is unbound. + */ + ViewSpy.prototype.unbind = function () { + this._log('unbind'); + }; + ViewSpy = __decorate([ + aurelia_templating_1.customAttribute('view-spy') + ], ViewSpy); + return ViewSpy; + }()); + exports.ViewSpy = ViewSpy; +}); + +define('aurelia-testing/component-tester',["require", "exports", "aurelia-templating", "./wait"], function (require, exports, aurelia_templating_1, wait_1) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var StageComponent = /** @class */ (function () { + function StageComponent() { + } + StageComponent.withResources = function (resources) { + if (resources === void 0) { resources = []; } + return new ComponentTester().withResources(resources); + }; + return StageComponent; + }()); + exports.StageComponent = StageComponent; + var ComponentTester = /** @class */ (function () { + function ComponentTester() { + this.resources = []; + } + ComponentTester.prototype.configure = function (aurelia) { + return aurelia.use.standardConfiguration(); + }; + ComponentTester.prototype.bootstrap = function (configure) { + this.configure = configure; + }; + ComponentTester.prototype.withResources = function (resources) { + this.resources = resources; + return this; + }; + ComponentTester.prototype.inView = function (html) { + this.html = html; + return this; + }; + ComponentTester.prototype.boundTo = function (bindingContext) { + this.bindingContext = bindingContext; + return this; + }; + ComponentTester.prototype.manuallyHandleLifecycle = function () { + this._prepareLifecycle(); + return this; + }; + ComponentTester.prototype.create = function (bootstrap) { + var _this = this; + return bootstrap(function (aurelia) { + return Promise.resolve(_this.configure(aurelia)).then(function () { + if (_this.resources) { + aurelia.use.globalResources(_this.resources); + } + return aurelia.start().then(function () { + _this.host = document.createElement('div'); + _this.host.innerHTML = _this.html; + document.body.appendChild(_this.host); + return aurelia.enhance(_this.bindingContext, _this.host).then(function () { + _this.rootView = aurelia.root; + _this.element = _this.host.firstElementChild; + if (aurelia.root.controllers.length) { + _this.viewModel = aurelia.root.controllers[0].viewModel; + } + return new Promise(function (resolve) { return setTimeout(function () { return resolve(); }, 0); }); + }); + }); + }); + }); + }; + ComponentTester.prototype.dispose = function () { + if (this.host === undefined || this.rootView === undefined) { + throw new Error('Cannot call ComponentTester.dispose() before ComponentTester.create()'); + } + this.rootView.detached(); + this.rootView.unbind(); + return this.host.parentNode.removeChild(this.host); + }; + ComponentTester.prototype._prepareLifecycle = function () { + var _this = this; + // bind + var bindPrototype = aurelia_templating_1.View.prototype.bind; + // tslint:disable-next-line:no-empty + aurelia_templating_1.View.prototype.bind = function () { }; + this.bind = function (bindingContext) { return new Promise(function (resolve) { + aurelia_templating_1.View.prototype.bind = bindPrototype; + if (bindingContext !== undefined) { + _this.bindingContext = bindingContext; + } + _this.rootView.bind(_this.bindingContext); + setTimeout(function () { return resolve(); }, 0); + }); }; + // attached + var attachedPrototype = aurelia_templating_1.View.prototype.attached; + // tslint:disable-next-line:no-empty + aurelia_templating_1.View.prototype.attached = function () { }; + this.attached = function () { return new Promise(function (resolve) { + aurelia_templating_1.View.prototype.attached = attachedPrototype; + _this.rootView.attached(); + setTimeout(function () { return resolve(); }, 0); + }); }; + // detached + this.detached = function () { return new Promise(function (resolve) { + _this.rootView.detached(); + setTimeout(function () { return resolve(); }, 0); + }); }; + // unbind + this.unbind = function () { return new Promise(function (resolve) { + _this.rootView.unbind(); + setTimeout(function () { return resolve(); }, 0); + }); }; + }; + ComponentTester.prototype.waitForElement = function (selector, options) { + var _this = this; + return wait_1.waitFor(function () { return _this.element.querySelector(selector); }, options); + }; + ComponentTester.prototype.waitForElements = function (selector, options) { + var _this = this; + return wait_1.waitFor(function () { return _this.element.querySelectorAll(selector); }, options); + }; + return ComponentTester; + }()); + exports.ComponentTester = ComponentTester; +}); + +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +define('aurelia-testing/compile-spy',["require", "exports", "aurelia-templating", "aurelia-dependency-injection", "aurelia-logging", "aurelia-pal"], function (require, exports, aurelia_templating_1, aurelia_dependency_injection_1, aurelia_logging_1, aurelia_pal_1) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + /** + * Attribute to be placed on any element to have it emit the View Compiler's + * TargetInstruction into the debug console, giving you insight into all the + * parsed bindings, behaviors and event handers for the targeted element. + */ + var CompileSpy = /** @class */ (function () { + /** + * Creates and instanse of CompileSpy. + * @param element target element on where attribute is placed on. + * @param instruction instructions for how the target element should be enhanced. + */ + function CompileSpy(element, instruction) { + aurelia_logging_1.getLogger('compile-spy').info(element.toString(), instruction); + } + CompileSpy = __decorate([ + aurelia_templating_1.customAttribute('compile-spy'), + aurelia_dependency_injection_1.inject(aurelia_pal_1.DOM.Element, aurelia_templating_1.TargetInstruction) + ], CompileSpy); + return CompileSpy; + }()); + exports.CompileSpy = CompileSpy; +}); + +define('aurelia-testing/aurelia-testing',["require", "exports", "./compile-spy", "./view-spy", "./component-tester", "./wait"], function (require, exports, compile_spy_1, view_spy_1, component_tester_1, wait_1) { + "use strict"; + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, "__esModule", { value: true }); + __export(compile_spy_1); + __export(view_spy_1); + __export(component_tester_1); + __export(wait_1); + function configure(config) { + config.globalResources([ + './compile-spy', + './view-spy' + ]); + } + exports.configure = configure; +}); + +;define('aurelia-testing', ['aurelia-testing/aurelia-testing'], function (main) { return main; }); + +define('aurelia-templating',['exports', 'aurelia-logging', 'aurelia-metadata', 'aurelia-pal', 'aurelia-loader', 'aurelia-path', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-task-queue'], function (exports, _aureliaLogging, _aureliaMetadata, _aureliaPal, _aureliaLoader, _aureliaPath, _aureliaDependencyInjection, _aureliaBinding, _aureliaTaskQueue) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TemplatingEngine = exports.ElementConfigResource = exports.CompositionEngine = exports.SwapStrategies = exports.HtmlBehaviorResource = exports.BindableProperty = exports.BehaviorPropertyObserver = exports.Controller = exports.ViewEngine = exports.ModuleAnalyzer = exports.ResourceDescription = exports.ResourceModule = exports.ViewCompiler = exports.ViewFactory = exports.BoundViewFactory = exports.ViewSlot = exports.View = exports.ViewResources = exports.ShadowDOM = exports.ShadowSlot = exports.PassThroughSlot = exports.SlotCustomAttribute = exports.BindingLanguage = exports.ViewLocator = exports.StaticViewStrategy = exports.InlineViewStrategy = exports.TemplateRegistryViewStrategy = exports.NoViewStrategy = exports.ConventionalViewStrategy = exports.RelativeViewStrategy = exports.viewStrategy = exports.TargetInstruction = exports.BehaviorInstruction = exports.ViewCompileInstruction = exports.ResourceLoadContext = exports.ElementEvents = exports.ViewEngineHooksResource = exports.CompositionTransaction = exports.CompositionTransactionOwnershipToken = exports.CompositionTransactionNotifier = exports.Animator = exports.animationEvent = undefined; + exports._hyphenate = _hyphenate; + exports._isAllWhitespace = _isAllWhitespace; + exports.viewEngineHooks = viewEngineHooks; + exports.validateBehaviorName = validateBehaviorName; + exports.children = children; + exports.child = child; + exports.resource = resource; + exports.behavior = behavior; + exports.customElement = customElement; + exports.customAttribute = customAttribute; + exports.templateController = templateController; + exports.bindable = bindable; + exports.dynamicOptions = dynamicOptions; + exports.useShadowDOM = useShadowDOM; + exports.processAttributes = processAttributes; + exports.processContent = processContent; + exports.containerless = containerless; + exports.useViewStrategy = useViewStrategy; + exports.useView = useView; + exports.inlineView = inlineView; + exports.noView = noView; + exports.view = view; + exports.elementConfig = elementConfig; + exports.viewResources = viewResources; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + var _class, _temp, _dec, _class2, _dec2, _class3, _dec3, _class4, _dec4, _class5, _dec5, _class6, _dec6, _class7, _class8, _temp2, _class9, _temp3, _class11, _dec7, _class13, _dec8, _class14, _class15, _temp4, _dec9, _class16, _dec10, _class17, _dec11, _class18; + + + + var animationEvent = exports.animationEvent = { + enterBegin: 'animation:enter:begin', + enterActive: 'animation:enter:active', + enterDone: 'animation:enter:done', + enterTimeout: 'animation:enter:timeout', + + leaveBegin: 'animation:leave:begin', + leaveActive: 'animation:leave:active', + leaveDone: 'animation:leave:done', + leaveTimeout: 'animation:leave:timeout', + + staggerNext: 'animation:stagger:next', + + removeClassBegin: 'animation:remove-class:begin', + removeClassActive: 'animation:remove-class:active', + removeClassDone: 'animation:remove-class:done', + removeClassTimeout: 'animation:remove-class:timeout', + + addClassBegin: 'animation:add-class:begin', + addClassActive: 'animation:add-class:active', + addClassDone: 'animation:add-class:done', + addClassTimeout: 'animation:add-class:timeout', + + animateBegin: 'animation:animate:begin', + animateActive: 'animation:animate:active', + animateDone: 'animation:animate:done', + animateTimeout: 'animation:animate:timeout', + + sequenceBegin: 'animation:sequence:begin', + sequenceDone: 'animation:sequence:done' + }; + + var Animator = exports.Animator = function () { + function Animator() { + + } + + Animator.prototype.enter = function enter(element) { + return Promise.resolve(false); + }; + + Animator.prototype.leave = function leave(element) { + return Promise.resolve(false); + }; + + Animator.prototype.removeClass = function removeClass(element, className) { + element.classList.remove(className); + return Promise.resolve(false); + }; + + Animator.prototype.addClass = function addClass(element, className) { + element.classList.add(className); + return Promise.resolve(false); + }; + + Animator.prototype.animate = function animate(element, className) { + return Promise.resolve(false); + }; + + Animator.prototype.runSequence = function runSequence(animations) {}; + + Animator.prototype.registerEffect = function registerEffect(effectName, properties) {}; + + Animator.prototype.unregisterEffect = function unregisterEffect(effectName) {}; + + return Animator; + }(); + + var CompositionTransactionNotifier = exports.CompositionTransactionNotifier = function () { + function CompositionTransactionNotifier(owner) { + + + this.owner = owner; + this.owner._compositionCount++; + } + + CompositionTransactionNotifier.prototype.done = function done() { + this.owner._compositionCount--; + this.owner._tryCompleteTransaction(); + }; + + return CompositionTransactionNotifier; + }(); + + var CompositionTransactionOwnershipToken = exports.CompositionTransactionOwnershipToken = function () { + function CompositionTransactionOwnershipToken(owner) { + + + this.owner = owner; + this.owner._ownershipToken = this; + this.thenable = this._createThenable(); + } + + CompositionTransactionOwnershipToken.prototype.waitForCompositionComplete = function waitForCompositionComplete() { + this.owner._tryCompleteTransaction(); + return this.thenable; + }; + + CompositionTransactionOwnershipToken.prototype.resolve = function resolve() { + this._resolveCallback(); + }; + + CompositionTransactionOwnershipToken.prototype._createThenable = function _createThenable() { + var _this = this; + + return new Promise(function (resolve, reject) { + _this._resolveCallback = resolve; + }); + }; + + return CompositionTransactionOwnershipToken; + }(); + + var CompositionTransaction = exports.CompositionTransaction = function () { + function CompositionTransaction() { + + + this._ownershipToken = null; + this._compositionCount = 0; + } + + CompositionTransaction.prototype.tryCapture = function tryCapture() { + return this._ownershipToken === null ? new CompositionTransactionOwnershipToken(this) : null; + }; + + CompositionTransaction.prototype.enlist = function enlist() { + return new CompositionTransactionNotifier(this); + }; + + CompositionTransaction.prototype._tryCompleteTransaction = function _tryCompleteTransaction() { + if (this._compositionCount <= 0) { + this._compositionCount = 0; + + if (this._ownershipToken !== null) { + var token = this._ownershipToken; + this._ownershipToken = null; + token.resolve(); + } + } + }; + + return CompositionTransaction; + }(); + + var capitalMatcher = /([A-Z])/g; + + function addHyphenAndLower(char) { + return '-' + char.toLowerCase(); + } + + function _hyphenate(name) { + return (name.charAt(0).toLowerCase() + name.slice(1)).replace(capitalMatcher, addHyphenAndLower); + } + + function _isAllWhitespace(node) { + return !(node.auInterpolationTarget || /[^\t\n\r ]/.test(node.textContent)); + } + + var ViewEngineHooksResource = exports.ViewEngineHooksResource = function () { + function ViewEngineHooksResource() { + + } + + ViewEngineHooksResource.prototype.initialize = function initialize(container, target) { + this.instance = container.get(target); + }; + + ViewEngineHooksResource.prototype.register = function register(registry, name) { + registry.registerViewEngineHooks(this.instance); + }; + + ViewEngineHooksResource.prototype.load = function load(container, target) {}; + + ViewEngineHooksResource.convention = function convention(name) { + if (name.endsWith('ViewEngineHooks')) { + return new ViewEngineHooksResource(); + } + }; + + return ViewEngineHooksResource; + }(); + + function viewEngineHooks(target) { + var deco = function deco(t) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ViewEngineHooksResource(), t); + }; + + return target ? deco(target) : deco; + } + + var ElementEvents = exports.ElementEvents = function () { + function ElementEvents(element) { + + + this.element = element; + this.subscriptions = {}; + } + + ElementEvents.prototype._enqueueHandler = function _enqueueHandler(handler) { + this.subscriptions[handler.eventName] = this.subscriptions[handler.eventName] || []; + this.subscriptions[handler.eventName].push(handler); + }; + + ElementEvents.prototype._dequeueHandler = function _dequeueHandler(handler) { + var index = void 0; + var subscriptions = this.subscriptions[handler.eventName]; + if (subscriptions) { + index = subscriptions.indexOf(handler); + if (index > -1) { + subscriptions.splice(index, 1); + } + } + return handler; + }; + + ElementEvents.prototype.publish = function publish(eventName) { + var detail = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var bubbles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + var cancelable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + + var event = _aureliaPal.DOM.createCustomEvent(eventName, { cancelable: cancelable, bubbles: bubbles, detail: detail }); + this.element.dispatchEvent(event); + }; + + ElementEvents.prototype.subscribe = function subscribe(eventName, handler) { + var captureOrOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + + if (typeof handler === 'function') { + var eventHandler = new EventHandlerImpl(this, eventName, handler, captureOrOptions, false); + return eventHandler; + } + + return undefined; + }; + + ElementEvents.prototype.subscribeOnce = function subscribeOnce(eventName, handler) { + var captureOrOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + + if (typeof handler === 'function') { + var eventHandler = new EventHandlerImpl(this, eventName, handler, captureOrOptions, true); + return eventHandler; + } + + return undefined; + }; + + ElementEvents.prototype.dispose = function dispose(eventName) { + if (eventName && typeof eventName === 'string') { + var subscriptions = this.subscriptions[eventName]; + if (subscriptions) { + while (subscriptions.length) { + var subscription = subscriptions.pop(); + if (subscription) { + subscription.dispose(); + } + } + } + } else { + this.disposeAll(); + } + }; + + ElementEvents.prototype.disposeAll = function disposeAll() { + for (var _key in this.subscriptions) { + this.dispose(_key); + } + }; + + return ElementEvents; + }(); + + var EventHandlerImpl = function () { + function EventHandlerImpl(owner, eventName, handler, captureOrOptions, once) { + + + this.owner = owner; + this.eventName = eventName; + this.handler = handler; + + this.capture = typeof captureOrOptions === 'boolean' ? captureOrOptions : captureOrOptions.capture; + this.bubbles = !this.capture; + this.captureOrOptions = captureOrOptions; + this.once = once; + owner.element.addEventListener(eventName, this, captureOrOptions); + owner._enqueueHandler(this); + } + + EventHandlerImpl.prototype.handleEvent = function handleEvent(e) { + var fn = this.handler; + fn(e); + if (this.once) { + this.dispose(); + } + }; + + EventHandlerImpl.prototype.dispose = function dispose() { + this.owner.element.removeEventListener(this.eventName, this, this.captureOrOptions); + this.owner._dequeueHandler(this); + this.owner = this.handler = null; + }; + + return EventHandlerImpl; + }(); + + var ResourceLoadContext = exports.ResourceLoadContext = function () { + function ResourceLoadContext() { + + + this.dependencies = {}; + } + + ResourceLoadContext.prototype.addDependency = function addDependency(url) { + this.dependencies[url] = true; + }; + + ResourceLoadContext.prototype.hasDependency = function hasDependency(url) { + return url in this.dependencies; + }; + + return ResourceLoadContext; + }(); + + var ViewCompileInstruction = exports.ViewCompileInstruction = function ViewCompileInstruction() { + var targetShadowDOM = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var compileSurrogate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + + + this.targetShadowDOM = targetShadowDOM; + this.compileSurrogate = compileSurrogate; + this.associatedModuleId = null; + }; + + ViewCompileInstruction.normal = new ViewCompileInstruction(); + + var BehaviorInstruction = exports.BehaviorInstruction = function () { + BehaviorInstruction.enhance = function enhance() { + var instruction = new BehaviorInstruction(); + instruction.enhance = true; + return instruction; + }; + + BehaviorInstruction.unitTest = function unitTest(type, attributes) { + var instruction = new BehaviorInstruction(); + instruction.type = type; + instruction.attributes = attributes || {}; + return instruction; + }; + + BehaviorInstruction.element = function element(node, type) { + var instruction = new BehaviorInstruction(); + instruction.type = type; + instruction.attributes = {}; + instruction.anchorIsContainer = !(node.hasAttribute('containerless') || type.containerless); + instruction.initiatedByBehavior = true; + return instruction; + }; + + BehaviorInstruction.attribute = function attribute(attrName, type) { + var instruction = new BehaviorInstruction(); + instruction.attrName = attrName; + instruction.type = type || null; + instruction.attributes = {}; + return instruction; + }; + + BehaviorInstruction.dynamic = function dynamic(host, viewModel, viewFactory) { + var instruction = new BehaviorInstruction(); + instruction.host = host; + instruction.viewModel = viewModel; + instruction.viewFactory = viewFactory; + instruction.inheritBindingContext = true; + return instruction; + }; + + function BehaviorInstruction() { + + + this.initiatedByBehavior = false; + this.enhance = false; + this.partReplacements = null; + this.viewFactory = null; + this.originalAttrName = null; + this.skipContentProcessing = false; + this.contentFactory = null; + this.viewModel = null; + this.anchorIsContainer = false; + this.host = null; + this.attributes = null; + this.type = null; + this.attrName = null; + this.inheritBindingContext = false; + } + + return BehaviorInstruction; + }(); + + BehaviorInstruction.normal = new BehaviorInstruction(); + + var TargetInstruction = exports.TargetInstruction = (_temp = _class = function () { + TargetInstruction.shadowSlot = function shadowSlot(parentInjectorId) { + var instruction = new TargetInstruction(); + instruction.parentInjectorId = parentInjectorId; + instruction.shadowSlot = true; + return instruction; + }; + + TargetInstruction.contentExpression = function contentExpression(expression) { + var instruction = new TargetInstruction(); + instruction.contentExpression = expression; + return instruction; + }; + + TargetInstruction.lifting = function lifting(parentInjectorId, liftingInstruction) { + var instruction = new TargetInstruction(); + instruction.parentInjectorId = parentInjectorId; + instruction.expressions = TargetInstruction.noExpressions; + instruction.behaviorInstructions = [liftingInstruction]; + instruction.viewFactory = liftingInstruction.viewFactory; + instruction.providers = [liftingInstruction.type.target]; + instruction.lifting = true; + return instruction; + }; + + TargetInstruction.normal = function normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction) { + var instruction = new TargetInstruction(); + instruction.injectorId = injectorId; + instruction.parentInjectorId = parentInjectorId; + instruction.providers = providers; + instruction.behaviorInstructions = behaviorInstructions; + instruction.expressions = expressions; + instruction.anchorIsContainer = elementInstruction ? elementInstruction.anchorIsContainer : true; + instruction.elementInstruction = elementInstruction; + return instruction; + }; + + TargetInstruction.surrogate = function surrogate(providers, behaviorInstructions, expressions, values) { + var instruction = new TargetInstruction(); + instruction.expressions = expressions; + instruction.behaviorInstructions = behaviorInstructions; + instruction.providers = providers; + instruction.values = values; + return instruction; + }; + + function TargetInstruction() { + + + this.injectorId = null; + this.parentInjectorId = null; + + this.shadowSlot = false; + this.slotName = null; + this.slotFallbackFactory = null; + + this.contentExpression = null; + + this.expressions = null; + this.behaviorInstructions = null; + this.providers = null; + + this.viewFactory = null; + + this.anchorIsContainer = false; + this.elementInstruction = null; + this.lifting = false; + + this.values = null; + } + + return TargetInstruction; + }(), _class.noExpressions = Object.freeze([]), _temp); + var viewStrategy = exports.viewStrategy = _aureliaMetadata.protocol.create('aurelia:view-strategy', { + validate: function validate(target) { + if (!(typeof target.loadViewFactory === 'function')) { + return 'View strategies must implement: loadViewFactory(viewEngine: ViewEngine, compileInstruction: ViewCompileInstruction, loadContext?: ResourceLoadContext): Promise'; + } + + return true; + }, + compose: function compose(target) { + if (!(typeof target.makeRelativeTo === 'function')) { + target.makeRelativeTo = _aureliaPal.PLATFORM.noop; + } + } + }); + + var RelativeViewStrategy = exports.RelativeViewStrategy = (_dec = viewStrategy(), _dec(_class2 = function () { + function RelativeViewStrategy(path) { + + + this.path = path; + this.absolutePath = null; + } + + RelativeViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) { + if (this.absolutePath === null && this.moduleId) { + this.absolutePath = (0, _aureliaPath.relativeToFile)(this.path, this.moduleId); + } + + compileInstruction.associatedModuleId = this.moduleId; + return viewEngine.loadViewFactory(this.absolutePath || this.path, compileInstruction, loadContext, target); + }; + + RelativeViewStrategy.prototype.makeRelativeTo = function makeRelativeTo(file) { + if (this.absolutePath === null) { + this.absolutePath = (0, _aureliaPath.relativeToFile)(this.path, file); + } + }; + + return RelativeViewStrategy; + }()) || _class2); + var ConventionalViewStrategy = exports.ConventionalViewStrategy = (_dec2 = viewStrategy(), _dec2(_class3 = function () { + function ConventionalViewStrategy(viewLocator, origin) { + + + this.moduleId = origin.moduleId; + this.viewUrl = viewLocator.convertOriginToViewUrl(origin); + } + + ConventionalViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) { + compileInstruction.associatedModuleId = this.moduleId; + return viewEngine.loadViewFactory(this.viewUrl, compileInstruction, loadContext, target); + }; + + return ConventionalViewStrategy; + }()) || _class3); + var NoViewStrategy = exports.NoViewStrategy = (_dec3 = viewStrategy(), _dec3(_class4 = function () { + function NoViewStrategy(dependencies, dependencyBaseUrl) { + + + this.dependencies = dependencies || null; + this.dependencyBaseUrl = dependencyBaseUrl || ''; + } + + NoViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) { + var entry = this.entry; + var dependencies = this.dependencies; + + if (entry && entry.factoryIsReady) { + return Promise.resolve(null); + } + + this.entry = entry = new _aureliaLoader.TemplateRegistryEntry(this.moduleId || this.dependencyBaseUrl); + + entry.dependencies = []; + entry.templateIsLoaded = true; + + if (dependencies !== null) { + for (var i = 0, ii = dependencies.length; i < ii; ++i) { + var current = dependencies[i]; + + if (typeof current === 'string' || typeof current === 'function') { + entry.addDependency(current); + } else { + entry.addDependency(current.from, current.as); + } + } + } + + compileInstruction.associatedModuleId = this.moduleId; + + return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target); + }; + + return NoViewStrategy; + }()) || _class4); + var TemplateRegistryViewStrategy = exports.TemplateRegistryViewStrategy = (_dec4 = viewStrategy(), _dec4(_class5 = function () { + function TemplateRegistryViewStrategy(moduleId, entry) { + + + this.moduleId = moduleId; + this.entry = entry; + } + + TemplateRegistryViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) { + var entry = this.entry; + + if (entry.factoryIsReady) { + return Promise.resolve(entry.factory); + } + + compileInstruction.associatedModuleId = this.moduleId; + return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target); + }; + + return TemplateRegistryViewStrategy; + }()) || _class5); + var InlineViewStrategy = exports.InlineViewStrategy = (_dec5 = viewStrategy(), _dec5(_class6 = function () { + function InlineViewStrategy(markup, dependencies, dependencyBaseUrl) { + + + this.markup = markup; + this.dependencies = dependencies || null; + this.dependencyBaseUrl = dependencyBaseUrl || ''; + } + + InlineViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) { + var entry = this.entry; + var dependencies = this.dependencies; + + if (entry && entry.factoryIsReady) { + return Promise.resolve(entry.factory); + } + + this.entry = entry = new _aureliaLoader.TemplateRegistryEntry(this.moduleId || this.dependencyBaseUrl); + entry.template = _aureliaPal.DOM.createTemplateFromMarkup(this.markup); + + if (dependencies !== null) { + for (var i = 0, ii = dependencies.length; i < ii; ++i) { + var current = dependencies[i]; + + if (typeof current === 'string' || typeof current === 'function') { + entry.addDependency(current); + } else { + entry.addDependency(current.from, current.as); + } + } + } + + compileInstruction.associatedModuleId = this.moduleId; + return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target); + }; + + return InlineViewStrategy; + }()) || _class6); + var StaticViewStrategy = exports.StaticViewStrategy = (_dec6 = viewStrategy(), _dec6(_class7 = function () { + function StaticViewStrategy(config) { + + + if (typeof config === 'string' || config instanceof HTMLTemplateElement) { + config = { + template: config + }; + } + this.template = config.template; + this.dependencies = config.dependencies || []; + this.factoryIsReady = false; + this.onReady = null; + } + + StaticViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) { + var _this2 = this; + + if (this.factoryIsReady) { + return Promise.resolve(this.factory); + } + var deps = this.dependencies; + deps = typeof deps === 'function' ? deps() : deps; + deps = deps ? deps : []; + deps = Array.isArray(deps) ? deps : [deps]; + + return Promise.all(deps).then(function (dependencies) { + var container = viewEngine.container; + var appResources = viewEngine.appResources; + var viewCompiler = viewEngine.viewCompiler; + var viewResources = new ViewResources(appResources); + + var resource = void 0; + var elDeps = []; + + if (target) { + viewResources.autoRegister(container, target); + } + + for (var _iterator = dependencies, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var dep = _ref; + + if (typeof dep === 'function') { + resource = viewResources.autoRegister(container, dep); + } else if (dep && (typeof dep === 'undefined' ? 'undefined' : _typeof(dep)) === 'object') { + for (var _key2 in dep) { + var exported = dep[_key2]; + if (typeof exported === 'function') { + resource = viewResources.autoRegister(container, exported); + } + } + } else { + throw new Error('dependency neither function nor object. Received: "' + (typeof dep === 'undefined' ? 'undefined' : _typeof(dep)) + '"'); + } + if (resource.elementName !== null) { + elDeps.push(resource); + } + } + + return Promise.all(elDeps.map(function (el) { + return el.load(container, el.target); + })).then(function () { + var factory = viewCompiler.compile(_this2.template, viewResources, compileInstruction); + _this2.factoryIsReady = true; + _this2.factory = factory; + return factory; + }); + }); + }; + + return StaticViewStrategy; + }()) || _class7); + var ViewLocator = exports.ViewLocator = (_temp2 = _class8 = function () { + function ViewLocator() { + + } + + ViewLocator.prototype.getViewStrategy = function getViewStrategy(value) { + if (!value) { + return null; + } + + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && 'getViewStrategy' in value) { + var _origin = _aureliaMetadata.Origin.get(value.constructor); + + value = value.getViewStrategy(); + + if (typeof value === 'string') { + value = new RelativeViewStrategy(value); + } + + viewStrategy.assert(value); + + if (_origin.moduleId) { + value.makeRelativeTo(_origin.moduleId); + } + + return value; + } + + if (typeof value === 'string') { + value = new RelativeViewStrategy(value); + } + + if (viewStrategy.validate(value)) { + return value; + } + + if (typeof value !== 'function') { + value = value.constructor; + } + + if ('$view' in value) { + var c = value.$view; + var _view = void 0; + c = typeof c === 'function' ? c.call(value) : c; + if (c === null) { + _view = new NoViewStrategy(); + } else { + _view = c instanceof StaticViewStrategy ? c : new StaticViewStrategy(c); + } + _aureliaMetadata.metadata.define(ViewLocator.viewStrategyMetadataKey, _view, value); + return _view; + } + + var origin = _aureliaMetadata.Origin.get(value); + var strategy = _aureliaMetadata.metadata.get(ViewLocator.viewStrategyMetadataKey, value); + + if (!strategy) { + if (!origin.moduleId) { + throw new Error('Cannot determine default view strategy for object.', value); + } + + strategy = this.createFallbackViewStrategy(origin); + } else if (origin.moduleId) { + strategy.moduleId = origin.moduleId; + } + + return strategy; + }; + + ViewLocator.prototype.createFallbackViewStrategy = function createFallbackViewStrategy(origin) { + return new ConventionalViewStrategy(this, origin); + }; + + ViewLocator.prototype.convertOriginToViewUrl = function convertOriginToViewUrl(origin) { + var moduleId = origin.moduleId; + var id = moduleId.endsWith('.js') || moduleId.endsWith('.ts') ? moduleId.substring(0, moduleId.length - 3) : moduleId; + return id + '.html'; + }; + + return ViewLocator; + }(), _class8.viewStrategyMetadataKey = 'aurelia:view-strategy', _temp2); + + + function mi(name) { + throw new Error('BindingLanguage must implement ' + name + '().'); + } + + var BindingLanguage = exports.BindingLanguage = function () { + function BindingLanguage() { + + } + + BindingLanguage.prototype.inspectAttribute = function inspectAttribute(resources, elementName, attrName, attrValue) { + mi('inspectAttribute'); + }; + + BindingLanguage.prototype.createAttributeInstruction = function createAttributeInstruction(resources, element, info, existingInstruction) { + mi('createAttributeInstruction'); + }; + + BindingLanguage.prototype.inspectTextContent = function inspectTextContent(resources, value) { + mi('inspectTextContent'); + }; + + return BindingLanguage; + }(); + + var noNodes = Object.freeze([]); + + var SlotCustomAttribute = exports.SlotCustomAttribute = function () { + SlotCustomAttribute.inject = function inject() { + return [_aureliaPal.DOM.Element]; + }; + + function SlotCustomAttribute(element) { + + + this.element = element; + this.element.auSlotAttribute = this; + } + + SlotCustomAttribute.prototype.valueChanged = function valueChanged(newValue, oldValue) {}; + + return SlotCustomAttribute; + }(); + + var PassThroughSlot = exports.PassThroughSlot = function () { + function PassThroughSlot(anchor, name, destinationName, fallbackFactory) { + + + this.anchor = anchor; + this.anchor.viewSlot = this; + this.name = name; + this.destinationName = destinationName; + this.fallbackFactory = fallbackFactory; + this.destinationSlot = null; + this.projections = 0; + this.contentView = null; + + var attr = new SlotCustomAttribute(this.anchor); + attr.value = this.destinationName; + } + + PassThroughSlot.prototype.renderFallbackContent = function renderFallbackContent(view, nodes, projectionSource, index) { + if (this.contentView === null) { + this.contentView = this.fallbackFactory.create(this.ownerView.container); + this.contentView.bind(this.ownerView.bindingContext, this.ownerView.overrideContext); + + var slots = Object.create(null); + slots[this.destinationSlot.name] = this.destinationSlot; + + ShadowDOM.distributeView(this.contentView, slots, projectionSource, index, this.destinationSlot.name); + } + }; + + PassThroughSlot.prototype.passThroughTo = function passThroughTo(destinationSlot) { + this.destinationSlot = destinationSlot; + }; + + PassThroughSlot.prototype.addNode = function addNode(view, node, projectionSource, index) { + if (this.contentView !== null) { + this.contentView.removeNodes(); + this.contentView.detached(); + this.contentView.unbind(); + this.contentView = null; + } + + if (node.viewSlot instanceof PassThroughSlot) { + node.viewSlot.passThroughTo(this); + return; + } + + this.projections++; + this.destinationSlot.addNode(view, node, projectionSource, index); + }; + + PassThroughSlot.prototype.removeView = function removeView(view, projectionSource) { + this.projections--; + this.destinationSlot.removeView(view, projectionSource); + + if (this.needsFallbackRendering) { + this.renderFallbackContent(null, noNodes, projectionSource); + } + }; + + PassThroughSlot.prototype.removeAll = function removeAll(projectionSource) { + this.projections = 0; + this.destinationSlot.removeAll(projectionSource); + + if (this.needsFallbackRendering) { + this.renderFallbackContent(null, noNodes, projectionSource); + } + }; + + PassThroughSlot.prototype.projectFrom = function projectFrom(view, projectionSource) { + this.destinationSlot.projectFrom(view, projectionSource); + }; + + PassThroughSlot.prototype.created = function created(ownerView) { + this.ownerView = ownerView; + }; + + PassThroughSlot.prototype.bind = function bind(view) { + if (this.contentView) { + this.contentView.bind(view.bindingContext, view.overrideContext); + } + }; + + PassThroughSlot.prototype.attached = function attached() { + if (this.contentView) { + this.contentView.attached(); + } + }; + + PassThroughSlot.prototype.detached = function detached() { + if (this.contentView) { + this.contentView.detached(); + } + }; + + PassThroughSlot.prototype.unbind = function unbind() { + if (this.contentView) { + this.contentView.unbind(); + } + }; + + _createClass(PassThroughSlot, [{ + key: 'needsFallbackRendering', + get: function get() { + return this.fallbackFactory && this.projections === 0; + } + }]); + + return PassThroughSlot; + }(); + + var ShadowSlot = exports.ShadowSlot = function () { + function ShadowSlot(anchor, name, fallbackFactory) { + + + this.anchor = anchor; + this.anchor.isContentProjectionSource = true; + this.anchor.viewSlot = this; + this.name = name; + this.fallbackFactory = fallbackFactory; + this.contentView = null; + this.projections = 0; + this.children = []; + this.projectFromAnchors = null; + this.destinationSlots = null; + } + + ShadowSlot.prototype.addNode = function addNode(view, node, projectionSource, index, destination) { + if (this.contentView !== null) { + this.contentView.removeNodes(); + this.contentView.detached(); + this.contentView.unbind(); + this.contentView = null; + } + + if (node.viewSlot instanceof PassThroughSlot) { + node.viewSlot.passThroughTo(this); + return; + } + + if (this.destinationSlots !== null) { + ShadowDOM.distributeNodes(view, [node], this.destinationSlots, this, index); + } else { + node.auOwnerView = view; + node.auProjectionSource = projectionSource; + node.auAssignedSlot = this; + + var anchor = this._findAnchor(view, node, projectionSource, index); + var parent = anchor.parentNode; + + parent.insertBefore(node, anchor); + this.children.push(node); + this.projections++; + } + }; + + ShadowSlot.prototype.removeView = function removeView(view, projectionSource) { + if (this.destinationSlots !== null) { + ShadowDOM.undistributeView(view, this.destinationSlots, this); + } else if (this.contentView && this.contentView.hasSlots) { + ShadowDOM.undistributeView(view, this.contentView.slots, projectionSource); + } else { + var found = this.children.find(function (x) { + return x.auSlotProjectFrom === projectionSource; + }); + if (found) { + var _children = found.auProjectionChildren; + + for (var i = 0, ii = _children.length; i < ii; ++i) { + var _child = _children[i]; + + if (_child.auOwnerView === view) { + _children.splice(i, 1); + view.fragment.appendChild(_child); + i--;ii--; + this.projections--; + } + } + + if (this.needsFallbackRendering) { + this.renderFallbackContent(view, noNodes, projectionSource); + } + } + } + }; + + ShadowSlot.prototype.removeAll = function removeAll(projectionSource) { + if (this.destinationSlots !== null) { + ShadowDOM.undistributeAll(this.destinationSlots, this); + } else if (this.contentView && this.contentView.hasSlots) { + ShadowDOM.undistributeAll(this.contentView.slots, projectionSource); + } else { + var found = this.children.find(function (x) { + return x.auSlotProjectFrom === projectionSource; + }); + + if (found) { + var _children2 = found.auProjectionChildren; + for (var i = 0, ii = _children2.length; i < ii; ++i) { + var _child2 = _children2[i]; + _child2.auOwnerView.fragment.appendChild(_child2); + this.projections--; + } + + found.auProjectionChildren = []; + + if (this.needsFallbackRendering) { + this.renderFallbackContent(null, noNodes, projectionSource); + } + } + } + }; + + ShadowSlot.prototype._findAnchor = function _findAnchor(view, node, projectionSource, index) { + if (projectionSource) { + var found = this.children.find(function (x) { + return x.auSlotProjectFrom === projectionSource; + }); + if (found) { + if (index !== undefined) { + var _children3 = found.auProjectionChildren; + var viewIndex = -1; + var lastView = void 0; + + for (var i = 0, ii = _children3.length; i < ii; ++i) { + var current = _children3[i]; + + if (current.auOwnerView !== lastView) { + viewIndex++; + lastView = current.auOwnerView; + + if (viewIndex >= index && lastView !== view) { + _children3.splice(i, 0, node); + return current; + } + } + } + } + + found.auProjectionChildren.push(node); + return found; + } + } + + return this.anchor; + }; + + ShadowSlot.prototype.projectTo = function projectTo(slots) { + this.destinationSlots = slots; + }; + + ShadowSlot.prototype.projectFrom = function projectFrom(view, projectionSource) { + var anchor = _aureliaPal.DOM.createComment('anchor'); + var parent = this.anchor.parentNode; + anchor.auSlotProjectFrom = projectionSource; + anchor.auOwnerView = view; + anchor.auProjectionChildren = []; + parent.insertBefore(anchor, this.anchor); + this.children.push(anchor); + + if (this.projectFromAnchors === null) { + this.projectFromAnchors = []; + } + + this.projectFromAnchors.push(anchor); + }; + + ShadowSlot.prototype.renderFallbackContent = function renderFallbackContent(view, nodes, projectionSource, index) { + if (this.contentView === null) { + this.contentView = this.fallbackFactory.create(this.ownerView.container); + this.contentView.bind(this.ownerView.bindingContext, this.ownerView.overrideContext); + this.contentView.insertNodesBefore(this.anchor); + } + + if (this.contentView.hasSlots) { + var slots = this.contentView.slots; + var projectFromAnchors = this.projectFromAnchors; + + if (projectFromAnchors !== null) { + for (var slotName in slots) { + var slot = slots[slotName]; + + for (var i = 0, ii = projectFromAnchors.length; i < ii; ++i) { + var anchor = projectFromAnchors[i]; + slot.projectFrom(anchor.auOwnerView, anchor.auSlotProjectFrom); + } + } + } + + this.fallbackSlots = slots; + ShadowDOM.distributeNodes(view, nodes, slots, projectionSource, index); + } + }; + + ShadowSlot.prototype.created = function created(ownerView) { + this.ownerView = ownerView; + }; + + ShadowSlot.prototype.bind = function bind(view) { + if (this.contentView) { + this.contentView.bind(view.bindingContext, view.overrideContext); + } + }; + + ShadowSlot.prototype.attached = function attached() { + if (this.contentView) { + this.contentView.attached(); + } + }; + + ShadowSlot.prototype.detached = function detached() { + if (this.contentView) { + this.contentView.detached(); + } + }; + + ShadowSlot.prototype.unbind = function unbind() { + if (this.contentView) { + this.contentView.unbind(); + } + }; + + _createClass(ShadowSlot, [{ + key: 'needsFallbackRendering', + get: function get() { + return this.fallbackFactory && this.projections === 0; + } + }]); + + return ShadowSlot; + }(); + + var ShadowDOM = exports.ShadowDOM = (_temp3 = _class9 = function () { + function ShadowDOM() { + + } + + ShadowDOM.getSlotName = function getSlotName(node) { + if (node.auSlotAttribute === undefined) { + return ShadowDOM.defaultSlotKey; + } + + return node.auSlotAttribute.value; + }; + + ShadowDOM.distributeView = function distributeView(view, slots, projectionSource, index, destinationOverride) { + var nodes = void 0; + + if (view === null) { + nodes = noNodes; + } else { + var childNodes = view.fragment.childNodes; + var ii = childNodes.length; + nodes = new Array(ii); + + for (var i = 0; i < ii; ++i) { + nodes[i] = childNodes[i]; + } + } + + ShadowDOM.distributeNodes(view, nodes, slots, projectionSource, index, destinationOverride); + }; + + ShadowDOM.undistributeView = function undistributeView(view, slots, projectionSource) { + for (var slotName in slots) { + slots[slotName].removeView(view, projectionSource); + } + }; + + ShadowDOM.undistributeAll = function undistributeAll(slots, projectionSource) { + for (var slotName in slots) { + slots[slotName].removeAll(projectionSource); + } + }; + + ShadowDOM.distributeNodes = function distributeNodes(view, nodes, slots, projectionSource, index, destinationOverride) { + for (var i = 0, ii = nodes.length; i < ii; ++i) { + var currentNode = nodes[i]; + var nodeType = currentNode.nodeType; + + if (currentNode.isContentProjectionSource) { + currentNode.viewSlot.projectTo(slots); + + for (var slotName in slots) { + slots[slotName].projectFrom(view, currentNode.viewSlot); + } + + nodes.splice(i, 1); + ii--;i--; + } else if (nodeType === 1 || nodeType === 3 || currentNode.viewSlot instanceof PassThroughSlot) { + if (nodeType === 3 && _isAllWhitespace(currentNode)) { + nodes.splice(i, 1); + ii--;i--; + } else { + var found = slots[destinationOverride || ShadowDOM.getSlotName(currentNode)]; + + if (found) { + found.addNode(view, currentNode, projectionSource, index); + nodes.splice(i, 1); + ii--;i--; + } + } + } else { + nodes.splice(i, 1); + ii--;i--; + } + } + + for (var _slotName in slots) { + var slot = slots[_slotName]; + + if (slot.needsFallbackRendering) { + slot.renderFallbackContent(view, nodes, projectionSource, index); + } + } + }; + + return ShadowDOM; + }(), _class9.defaultSlotKey = '__au-default-slot-key__', _temp3); + + + function register(lookup, name, resource, type) { + if (!name) { + return; + } + + var existing = lookup[name]; + if (existing) { + if (existing !== resource) { + throw new Error('Attempted to register ' + type + ' when one with the same name already exists. Name: ' + name + '.'); + } + + return; + } + + lookup[name] = resource; + } + + function validateBehaviorName(name, type) { + if (/[A-Z]/.test(name)) { + var newName = _hyphenate(name); + LogManager.getLogger('templating').warn('\'' + name + '\' is not a valid ' + type + ' name and has been converted to \'' + newName + '\'. Upper-case letters are not allowed because the DOM is not case-sensitive.'); + return newName; + } + return name; + } + + var conventionMark = '__au_resource__'; + + var ViewResources = exports.ViewResources = function () { + ViewResources.convention = function convention(target, existing) { + var resource = void 0; + + if (existing && conventionMark in existing) { + return existing; + } + if ('$resource' in target) { + var config = target.$resource; + + if (typeof config === 'string') { + resource = existing || new HtmlBehaviorResource(); + resource[conventionMark] = true; + if (!resource.elementName) { + resource.elementName = validateBehaviorName(config, 'custom element'); + } + } else { + if (typeof config === 'function') { + config = config.call(target); + } + if (typeof config === 'string') { + config = { name: config }; + } + + config = Object.assign({}, config); + + var resourceType = config.type || 'element'; + + var _name = config.name; + switch (resourceType) { + case 'element':case 'attribute': + resource = existing || new HtmlBehaviorResource(); + resource[conventionMark] = true; + if (resourceType === 'element') { + if (!resource.elementName) { + resource.elementName = _name ? validateBehaviorName(_name, 'custom element') : _hyphenate(target.name); + } + } else { + if (!resource.attributeName) { + resource.attributeName = _name ? validateBehaviorName(_name, 'custom attribute') : _hyphenate(target.name); + } + } + if ('templateController' in config) { + config.liftsContent = config.templateController; + delete config.templateController; + } + if ('defaultBindingMode' in config && resource.attributeDefaultBindingMode !== undefined) { + config.attributeDefaultBindingMode = config.defaultBindingMode; + delete config.defaultBindingMode; + } + + delete config.name; + + Object.assign(resource, config); + break; + case 'valueConverter': + resource = new _aureliaBinding.ValueConverterResource((0, _aureliaBinding.camelCase)(_name || target.name)); + break; + case 'bindingBehavior': + resource = new _aureliaBinding.BindingBehaviorResource((0, _aureliaBinding.camelCase)(_name || target.name)); + break; + case 'viewEngineHooks': + resource = new ViewEngineHooksResource(); + break; + } + } + + if (resource instanceof HtmlBehaviorResource) { + var _bindables = typeof config === 'string' ? undefined : config.bindables; + var currentProps = resource.properties; + if (Array.isArray(_bindables)) { + for (var i = 0, ii = _bindables.length; ii > i; ++i) { + var prop = _bindables[i]; + if (!prop || typeof prop !== 'string' && !prop.name) { + throw new Error('Invalid bindable property at "' + i + '" for class "' + target.name + '". Expected either a string or an object with "name" property.'); + } + var newProp = new BindableProperty(prop); + + var existed = false; + for (var j = 0, jj = currentProps.length; jj > j; ++j) { + if (currentProps[j].name === newProp.name) { + existed = true; + break; + } + } + if (existed) { + continue; + } + newProp.registerWith(target, resource); + } + } + } + } + return resource; + }; + + function ViewResources(parent, viewUrl) { + + + this.bindingLanguage = null; + + this.parent = parent || null; + this.hasParent = this.parent !== null; + this.viewUrl = viewUrl || ''; + this.lookupFunctions = { + valueConverters: this.getValueConverter.bind(this), + bindingBehaviors: this.getBindingBehavior.bind(this) + }; + this.attributes = Object.create(null); + this.elements = Object.create(null); + this.valueConverters = Object.create(null); + this.bindingBehaviors = Object.create(null); + this.attributeMap = Object.create(null); + this.values = Object.create(null); + this.beforeCompile = this.afterCompile = this.beforeCreate = this.afterCreate = this.beforeBind = this.beforeUnbind = false; + } + + ViewResources.prototype._tryAddHook = function _tryAddHook(obj, name) { + if (typeof obj[name] === 'function') { + var func = obj[name].bind(obj); + var counter = 1; + var callbackName = void 0; + + while (this[callbackName = name + counter.toString()] !== undefined) { + counter++; + } + + this[name] = true; + this[callbackName] = func; + } + }; + + ViewResources.prototype._invokeHook = function _invokeHook(name, one, two, three, four) { + if (this.hasParent) { + this.parent._invokeHook(name, one, two, three, four); + } + + if (this[name]) { + this[name + '1'](one, two, three, four); + + var callbackName = name + '2'; + if (this[callbackName]) { + this[callbackName](one, two, three, four); + + callbackName = name + '3'; + if (this[callbackName]) { + this[callbackName](one, two, three, four); + + var counter = 4; + + while (this[callbackName = name + counter.toString()] !== undefined) { + this[callbackName](one, two, three, four); + counter++; + } + } + } + } + }; + + ViewResources.prototype.registerViewEngineHooks = function registerViewEngineHooks(hooks) { + this._tryAddHook(hooks, 'beforeCompile'); + this._tryAddHook(hooks, 'afterCompile'); + this._tryAddHook(hooks, 'beforeCreate'); + this._tryAddHook(hooks, 'afterCreate'); + this._tryAddHook(hooks, 'beforeBind'); + this._tryAddHook(hooks, 'beforeUnbind'); + }; + + ViewResources.prototype.getBindingLanguage = function getBindingLanguage(bindingLanguageFallback) { + return this.bindingLanguage || (this.bindingLanguage = bindingLanguageFallback); + }; + + ViewResources.prototype.patchInParent = function patchInParent(newParent) { + var originalParent = this.parent; + + this.parent = newParent || null; + this.hasParent = this.parent !== null; + + if (newParent.parent === null) { + newParent.parent = originalParent; + newParent.hasParent = originalParent !== null; + } + }; + + ViewResources.prototype.relativeToView = function relativeToView(path) { + return (0, _aureliaPath.relativeToFile)(path, this.viewUrl); + }; + + ViewResources.prototype.registerElement = function registerElement(tagName, behavior) { + register(this.elements, tagName, behavior, 'an Element'); + }; + + ViewResources.prototype.getElement = function getElement(tagName) { + return this.elements[tagName] || (this.hasParent ? this.parent.getElement(tagName) : null); + }; + + ViewResources.prototype.mapAttribute = function mapAttribute(attribute) { + return this.attributeMap[attribute] || (this.hasParent ? this.parent.mapAttribute(attribute) : null); + }; + + ViewResources.prototype.registerAttribute = function registerAttribute(attribute, behavior, knownAttribute) { + this.attributeMap[attribute] = knownAttribute; + register(this.attributes, attribute, behavior, 'an Attribute'); + }; + + ViewResources.prototype.getAttribute = function getAttribute(attribute) { + return this.attributes[attribute] || (this.hasParent ? this.parent.getAttribute(attribute) : null); + }; + + ViewResources.prototype.registerValueConverter = function registerValueConverter(name, valueConverter) { + register(this.valueConverters, name, valueConverter, 'a ValueConverter'); + }; + + ViewResources.prototype.getValueConverter = function getValueConverter(name) { + return this.valueConverters[name] || (this.hasParent ? this.parent.getValueConverter(name) : null); + }; + + ViewResources.prototype.registerBindingBehavior = function registerBindingBehavior(name, bindingBehavior) { + register(this.bindingBehaviors, name, bindingBehavior, 'a BindingBehavior'); + }; + + ViewResources.prototype.getBindingBehavior = function getBindingBehavior(name) { + return this.bindingBehaviors[name] || (this.hasParent ? this.parent.getBindingBehavior(name) : null); + }; + + ViewResources.prototype.registerValue = function registerValue(name, value) { + register(this.values, name, value, 'a value'); + }; + + ViewResources.prototype.getValue = function getValue(name) { + return this.values[name] || (this.hasParent ? this.parent.getValue(name) : null); + }; + + ViewResources.prototype.autoRegister = function autoRegister(container, impl) { + var resourceTypeMeta = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.resource, impl); + if (resourceTypeMeta) { + if (resourceTypeMeta instanceof HtmlBehaviorResource) { + ViewResources.convention(impl, resourceTypeMeta); + + if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { + HtmlBehaviorResource.convention(impl.name, resourceTypeMeta); + } + if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { + resourceTypeMeta.elementName = _hyphenate(impl.name); + } + } + } else { + resourceTypeMeta = ViewResources.convention(impl) || HtmlBehaviorResource.convention(impl.name) || _aureliaBinding.ValueConverterResource.convention(impl.name) || _aureliaBinding.BindingBehaviorResource.convention(impl.name) || ViewEngineHooksResource.convention(impl.name); + if (!resourceTypeMeta) { + resourceTypeMeta = new HtmlBehaviorResource(); + resourceTypeMeta.elementName = _hyphenate(impl.name); + } + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, resourceTypeMeta, impl); + } + resourceTypeMeta.initialize(container, impl); + resourceTypeMeta.register(this); + return resourceTypeMeta; + }; + + return ViewResources; + }(); + + var View = exports.View = function () { + function View(container, viewFactory, fragment, controllers, bindings, children, slots) { + + + this.container = container; + this.viewFactory = viewFactory; + this.resources = viewFactory.resources; + this.fragment = fragment; + this.firstChild = fragment.firstChild; + this.lastChild = fragment.lastChild; + this.controllers = controllers; + this.bindings = bindings; + this.children = children; + this.slots = slots; + this.hasSlots = false; + this.fromCache = false; + this.isBound = false; + this.isAttached = false; + this.bindingContext = null; + this.overrideContext = null; + this.controller = null; + this.viewModelScope = null; + this.animatableElement = undefined; + this._isUserControlled = false; + this.contentView = null; + + for (var _key3 in slots) { + this.hasSlots = true; + break; + } + } + + View.prototype.returnToCache = function returnToCache() { + this.viewFactory.returnViewToCache(this); + }; + + View.prototype.created = function created() { + var i = void 0; + var ii = void 0; + var controllers = this.controllers; + + for (i = 0, ii = controllers.length; i < ii; ++i) { + controllers[i].created(this); + } + }; + + View.prototype.bind = function bind(bindingContext, overrideContext, _systemUpdate) { + var controllers = void 0; + var bindings = void 0; + var children = void 0; + var i = void 0; + var ii = void 0; + + if (_systemUpdate && this._isUserControlled) { + return; + } + + if (this.isBound) { + if (this.bindingContext === bindingContext) { + return; + } + + this.unbind(); + } + + this.isBound = true; + this.bindingContext = bindingContext; + this.overrideContext = overrideContext || (0, _aureliaBinding.createOverrideContext)(bindingContext); + + this.resources._invokeHook('beforeBind', this); + + bindings = this.bindings; + for (i = 0, ii = bindings.length; i < ii; ++i) { + bindings[i].bind(this); + } + + if (this.viewModelScope !== null) { + bindingContext.bind(this.viewModelScope.bindingContext, this.viewModelScope.overrideContext); + this.viewModelScope = null; + } + + controllers = this.controllers; + for (i = 0, ii = controllers.length; i < ii; ++i) { + controllers[i].bind(this); + } + + children = this.children; + for (i = 0, ii = children.length; i < ii; ++i) { + children[i].bind(bindingContext, overrideContext, true); + } + + if (this.hasSlots) { + ShadowDOM.distributeView(this.contentView, this.slots); + } + }; + + View.prototype.addBinding = function addBinding(binding) { + this.bindings.push(binding); + + if (this.isBound) { + binding.bind(this); + } + }; + + View.prototype.unbind = function unbind() { + var controllers = void 0; + var bindings = void 0; + var children = void 0; + var i = void 0; + var ii = void 0; + + if (this.isBound) { + this.isBound = false; + this.resources._invokeHook('beforeUnbind', this); + + if (this.controller !== null) { + this.controller.unbind(); + } + + bindings = this.bindings; + for (i = 0, ii = bindings.length; i < ii; ++i) { + bindings[i].unbind(); + } + + controllers = this.controllers; + for (i = 0, ii = controllers.length; i < ii; ++i) { + controllers[i].unbind(); + } + + children = this.children; + for (i = 0, ii = children.length; i < ii; ++i) { + children[i].unbind(); + } + + this.bindingContext = null; + this.overrideContext = null; + } + }; + + View.prototype.insertNodesBefore = function insertNodesBefore(refNode) { + refNode.parentNode.insertBefore(this.fragment, refNode); + }; + + View.prototype.appendNodesTo = function appendNodesTo(parent) { + parent.appendChild(this.fragment); + }; + + View.prototype.removeNodes = function removeNodes() { + var fragment = this.fragment; + var current = this.firstChild; + var end = this.lastChild; + var next = void 0; + + while (current) { + next = current.nextSibling; + fragment.appendChild(current); + + if (current === end) { + break; + } + + current = next; + } + }; + + View.prototype.attached = function attached() { + var controllers = void 0; + var children = void 0; + var i = void 0; + var ii = void 0; + + if (this.isAttached) { + return; + } + + this.isAttached = true; + + if (this.controller !== null) { + this.controller.attached(); + } + + controllers = this.controllers; + for (i = 0, ii = controllers.length; i < ii; ++i) { + controllers[i].attached(); + } + + children = this.children; + for (i = 0, ii = children.length; i < ii; ++i) { + children[i].attached(); + } + }; + + View.prototype.detached = function detached() { + var controllers = void 0; + var children = void 0; + var i = void 0; + var ii = void 0; + + if (this.isAttached) { + this.isAttached = false; + + if (this.controller !== null) { + this.controller.detached(); + } + + controllers = this.controllers; + for (i = 0, ii = controllers.length; i < ii; ++i) { + controllers[i].detached(); + } + + children = this.children; + for (i = 0, ii = children.length; i < ii; ++i) { + children[i].detached(); + } + } + }; + + return View; + }(); + + function getAnimatableElement(view) { + if (view.animatableElement !== undefined) { + return view.animatableElement; + } + + var current = view.firstChild; + + while (current && current.nodeType !== 1) { + current = current.nextSibling; + } + + if (current && current.nodeType === 1) { + return view.animatableElement = current.classList.contains('au-animate') ? current : null; + } + + return view.animatableElement = null; + } + + var ViewSlot = exports.ViewSlot = function () { + function ViewSlot(anchor, anchorIsContainer) { + var animator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Animator.instance; + + + + this.anchor = anchor; + this.anchorIsContainer = anchorIsContainer; + this.bindingContext = null; + this.overrideContext = null; + this.animator = animator; + this.children = []; + this.isBound = false; + this.isAttached = false; + this.contentSelectors = null; + anchor.viewSlot = this; + anchor.isContentProjectionSource = false; + } + + ViewSlot.prototype.animateView = function animateView(view) { + var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'enter'; + + var animatableElement = getAnimatableElement(view); + + if (animatableElement !== null) { + switch (direction) { + case 'enter': + return this.animator.enter(animatableElement); + case 'leave': + return this.animator.leave(animatableElement); + default: + throw new Error('Invalid animation direction: ' + direction); + } + } + }; + + ViewSlot.prototype.transformChildNodesIntoView = function transformChildNodesIntoView() { + var parent = this.anchor; + + this.children.push({ + fragment: parent, + firstChild: parent.firstChild, + lastChild: parent.lastChild, + returnToCache: function returnToCache() {}, + removeNodes: function removeNodes() { + var last = void 0; + + while (last = parent.lastChild) { + parent.removeChild(last); + } + }, + created: function created() {}, + bind: function bind() {}, + unbind: function unbind() {}, + attached: function attached() {}, + detached: function detached() {} + }); + }; + + ViewSlot.prototype.bind = function bind(bindingContext, overrideContext) { + var i = void 0; + var ii = void 0; + var children = void 0; + + if (this.isBound) { + if (this.bindingContext === bindingContext) { + return; + } + + this.unbind(); + } + + this.isBound = true; + this.bindingContext = bindingContext = bindingContext || this.bindingContext; + this.overrideContext = overrideContext = overrideContext || this.overrideContext; + + children = this.children; + for (i = 0, ii = children.length; i < ii; ++i) { + children[i].bind(bindingContext, overrideContext, true); + } + }; + + ViewSlot.prototype.unbind = function unbind() { + if (this.isBound) { + var i = void 0; + var ii = void 0; + var _children4 = this.children; + + this.isBound = false; + this.bindingContext = null; + this.overrideContext = null; + + for (i = 0, ii = _children4.length; i < ii; ++i) { + _children4[i].unbind(); + } + } + }; + + ViewSlot.prototype.add = function add(view) { + if (this.anchorIsContainer) { + view.appendNodesTo(this.anchor); + } else { + view.insertNodesBefore(this.anchor); + } + + this.children.push(view); + + if (this.isAttached) { + view.attached(); + return this.animateView(view, 'enter'); + } + }; + + ViewSlot.prototype.insert = function insert(index, view) { + var children = this.children; + var length = children.length; + + if (index === 0 && length === 0 || index >= length) { + return this.add(view); + } + + view.insertNodesBefore(children[index].firstChild); + children.splice(index, 0, view); + + if (this.isAttached) { + view.attached(); + return this.animateView(view, 'enter'); + } + }; + + ViewSlot.prototype.move = function move(sourceIndex, targetIndex) { + if (sourceIndex === targetIndex) { + return; + } + + var children = this.children; + var view = children[sourceIndex]; + + view.removeNodes(); + view.insertNodesBefore(children[targetIndex].firstChild); + children.splice(sourceIndex, 1); + children.splice(targetIndex, 0, view); + }; + + ViewSlot.prototype.remove = function remove(view, returnToCache, skipAnimation) { + return this.removeAt(this.children.indexOf(view), returnToCache, skipAnimation); + }; + + ViewSlot.prototype.removeMany = function removeMany(viewsToRemove, returnToCache, skipAnimation) { + var _this3 = this; + + var children = this.children; + var ii = viewsToRemove.length; + var i = void 0; + var rmPromises = []; + + viewsToRemove.forEach(function (child) { + if (skipAnimation) { + child.removeNodes(); + return; + } + + var animation = _this3.animateView(child, 'leave'); + if (animation) { + rmPromises.push(animation.then(function () { + return child.removeNodes(); + })); + } else { + child.removeNodes(); + } + }); + + var removeAction = function removeAction() { + if (_this3.isAttached) { + for (i = 0; i < ii; ++i) { + viewsToRemove[i].detached(); + } + } + + if (returnToCache) { + for (i = 0; i < ii; ++i) { + viewsToRemove[i].returnToCache(); + } + } + + for (i = 0; i < ii; ++i) { + var index = children.indexOf(viewsToRemove[i]); + if (index >= 0) { + children.splice(index, 1); + } + } + }; + + if (rmPromises.length > 0) { + return Promise.all(rmPromises).then(function () { + return removeAction(); + }); + } + + return removeAction(); + }; + + ViewSlot.prototype.removeAt = function removeAt(index, returnToCache, skipAnimation) { + var _this4 = this; + + var view = this.children[index]; + + var removeAction = function removeAction() { + index = _this4.children.indexOf(view); + view.removeNodes(); + _this4.children.splice(index, 1); + + if (_this4.isAttached) { + view.detached(); + } + + if (returnToCache) { + view.returnToCache(); + } + + return view; + }; + + if (!skipAnimation) { + var animation = this.animateView(view, 'leave'); + if (animation) { + return animation.then(function () { + return removeAction(); + }); + } + } + + return removeAction(); + }; + + ViewSlot.prototype.removeAll = function removeAll(returnToCache, skipAnimation) { + var _this5 = this; + + var children = this.children; + var ii = children.length; + var i = void 0; + var rmPromises = []; + + children.forEach(function (child) { + if (skipAnimation) { + child.removeNodes(); + return; + } + + var animation = _this5.animateView(child, 'leave'); + if (animation) { + rmPromises.push(animation.then(function () { + return child.removeNodes(); + })); + } else { + child.removeNodes(); + } + }); + + var removeAction = function removeAction() { + if (_this5.isAttached) { + for (i = 0; i < ii; ++i) { + children[i].detached(); + } + } + + if (returnToCache) { + for (i = 0; i < ii; ++i) { + var _child3 = children[i]; + + if (_child3) { + _child3.returnToCache(); + } + } + } + + _this5.children = []; + }; + + if (rmPromises.length > 0) { + return Promise.all(rmPromises).then(function () { + return removeAction(); + }); + } + + return removeAction(); + }; + + ViewSlot.prototype.attached = function attached() { + var i = void 0; + var ii = void 0; + var children = void 0; + var child = void 0; + + if (this.isAttached) { + return; + } + + this.isAttached = true; + + children = this.children; + for (i = 0, ii = children.length; i < ii; ++i) { + child = children[i]; + child.attached(); + this.animateView(child, 'enter'); + } + }; + + ViewSlot.prototype.detached = function detached() { + var i = void 0; + var ii = void 0; + var children = void 0; + + if (this.isAttached) { + this.isAttached = false; + children = this.children; + for (i = 0, ii = children.length; i < ii; ++i) { + children[i].detached(); + } + } + }; + + ViewSlot.prototype.projectTo = function projectTo(slots) { + var _this6 = this; + + this.projectToSlots = slots; + this.add = this._projectionAdd; + this.insert = this._projectionInsert; + this.move = this._projectionMove; + this.remove = this._projectionRemove; + this.removeAt = this._projectionRemoveAt; + this.removeMany = this._projectionRemoveMany; + this.removeAll = this._projectionRemoveAll; + this.children.forEach(function (view) { + return ShadowDOM.distributeView(view, slots, _this6); + }); + }; + + ViewSlot.prototype._projectionAdd = function _projectionAdd(view) { + ShadowDOM.distributeView(view, this.projectToSlots, this); + + this.children.push(view); + + if (this.isAttached) { + view.attached(); + } + }; + + ViewSlot.prototype._projectionInsert = function _projectionInsert(index, view) { + if (index === 0 && !this.children.length || index >= this.children.length) { + this.add(view); + } else { + ShadowDOM.distributeView(view, this.projectToSlots, this, index); + + this.children.splice(index, 0, view); + + if (this.isAttached) { + view.attached(); + } + } + }; + + ViewSlot.prototype._projectionMove = function _projectionMove(sourceIndex, targetIndex) { + if (sourceIndex === targetIndex) { + return; + } + + var children = this.children; + var view = children[sourceIndex]; + + ShadowDOM.undistributeView(view, this.projectToSlots, this); + ShadowDOM.distributeView(view, this.projectToSlots, this, targetIndex); + + children.splice(sourceIndex, 1); + children.splice(targetIndex, 0, view); + }; + + ViewSlot.prototype._projectionRemove = function _projectionRemove(view, returnToCache) { + ShadowDOM.undistributeView(view, this.projectToSlots, this); + this.children.splice(this.children.indexOf(view), 1); + + if (this.isAttached) { + view.detached(); + } + if (returnToCache) { + view.returnToCache(); + } + }; + + ViewSlot.prototype._projectionRemoveAt = function _projectionRemoveAt(index, returnToCache) { + var view = this.children[index]; + + ShadowDOM.undistributeView(view, this.projectToSlots, this); + this.children.splice(index, 1); + + if (this.isAttached) { + view.detached(); + } + if (returnToCache) { + view.returnToCache(); + } + }; + + ViewSlot.prototype._projectionRemoveMany = function _projectionRemoveMany(viewsToRemove, returnToCache) { + var _this7 = this; + + viewsToRemove.forEach(function (view) { + return _this7.remove(view, returnToCache); + }); + }; + + ViewSlot.prototype._projectionRemoveAll = function _projectionRemoveAll(returnToCache) { + ShadowDOM.undistributeAll(this.projectToSlots, this); + + var children = this.children; + var ii = children.length; + + if (this.isAttached) { + for (var i = 0; i < ii; ++i) { + if (returnToCache) { + children[i].returnToCache(); + } else { + children[i].detached(); + } + } + } + + this.children = []; + }; + + return ViewSlot; + }(); + + var ProviderResolver = (0, _aureliaDependencyInjection.resolver)(_class11 = function () { + function ProviderResolver() { + + } + + ProviderResolver.prototype.get = function get(container, key) { + var id = key.__providerId__; + return id in container ? container[id] : container[id] = container.invoke(key); + }; + + return ProviderResolver; + }()) || _class11; + + var providerResolverInstance = new ProviderResolver(); + + function elementContainerGet(key) { + if (key === _aureliaPal.DOM.Element) { + return this.element; + } + + if (key === BoundViewFactory) { + if (this.boundViewFactory) { + return this.boundViewFactory; + } + + var factory = this.instruction.viewFactory; + var _partReplacements = this.partReplacements; + + if (_partReplacements) { + factory = _partReplacements[factory.part] || factory; + } + + this.boundViewFactory = new BoundViewFactory(this, factory, _partReplacements); + return this.boundViewFactory; + } + + if (key === ViewSlot) { + if (this.viewSlot === undefined) { + this.viewSlot = new ViewSlot(this.element, this.instruction.anchorIsContainer); + this.element.isContentProjectionSource = this.instruction.lifting; + this.children.push(this.viewSlot); + } + + return this.viewSlot; + } + + if (key === ElementEvents) { + return this.elementEvents || (this.elementEvents = new ElementEvents(this.element)); + } + + if (key === CompositionTransaction) { + return this.compositionTransaction || (this.compositionTransaction = this.parent.get(key)); + } + + if (key === ViewResources) { + return this.viewResources; + } + + if (key === TargetInstruction) { + return this.instruction; + } + + return this.superGet(key); + } + + function createElementContainer(parent, element, instruction, children, partReplacements, resources) { + var container = parent.createChild(); + var providers = void 0; + var i = void 0; + + container.element = element; + container.instruction = instruction; + container.children = children; + container.viewResources = resources; + container.partReplacements = partReplacements; + + providers = instruction.providers; + i = providers.length; + + while (i--) { + container._resolvers.set(providers[i], providerResolverInstance); + } + + container.superGet = container.get; + container.get = elementContainerGet; + + return container; + } + + function hasAttribute(name) { + return this._element.hasAttribute(name); + } + + function getAttribute(name) { + return this._element.getAttribute(name); + } + + function setAttribute(name, value) { + this._element.setAttribute(name, value); + } + + function makeElementIntoAnchor(element, elementInstruction) { + var anchor = _aureliaPal.DOM.createComment('anchor'); + + if (elementInstruction) { + var firstChild = element.firstChild; + + if (firstChild && firstChild.tagName === 'AU-CONTENT') { + anchor.contentElement = firstChild; + } + + anchor._element = element; + + anchor.hasAttribute = hasAttribute; + anchor.getAttribute = getAttribute; + anchor.setAttribute = setAttribute; + } + + _aureliaPal.DOM.replaceNode(anchor, element); + + return anchor; + } + + function applyInstructions(containers, element, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources) { + var behaviorInstructions = instruction.behaviorInstructions; + var expressions = instruction.expressions; + var elementContainer = void 0; + var i = void 0; + var ii = void 0; + var current = void 0; + var instance = void 0; + + if (instruction.contentExpression) { + bindings.push(instruction.contentExpression.createBinding(element.nextSibling)); + element.nextSibling.auInterpolationTarget = true; + element.parentNode.removeChild(element); + return; + } + + if (instruction.shadowSlot) { + var commentAnchor = _aureliaPal.DOM.createComment('slot'); + var slot = void 0; + + if (instruction.slotDestination) { + slot = new PassThroughSlot(commentAnchor, instruction.slotName, instruction.slotDestination, instruction.slotFallbackFactory); + } else { + slot = new ShadowSlot(commentAnchor, instruction.slotName, instruction.slotFallbackFactory); + } + + _aureliaPal.DOM.replaceNode(commentAnchor, element); + shadowSlots[instruction.slotName] = slot; + controllers.push(slot); + return; + } + + if (behaviorInstructions.length) { + if (!instruction.anchorIsContainer) { + element = makeElementIntoAnchor(element, instruction.elementInstruction); + } + + containers[instruction.injectorId] = elementContainer = createElementContainer(containers[instruction.parentInjectorId], element, instruction, children, partReplacements, resources); + + for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { + current = behaviorInstructions[i]; + instance = current.type.create(elementContainer, current, element, bindings); + controllers.push(instance); + } + } + + for (i = 0, ii = expressions.length; i < ii; ++i) { + bindings.push(expressions[i].createBinding(element)); + } + } + + function styleStringToObject(style, target) { + var attributes = style.split(';'); + var firstIndexOfColon = void 0; + var i = void 0; + var current = void 0; + var key = void 0; + var value = void 0; + + target = target || {}; + + for (i = 0; i < attributes.length; i++) { + current = attributes[i]; + firstIndexOfColon = current.indexOf(':'); + key = current.substring(0, firstIndexOfColon).trim(); + value = current.substring(firstIndexOfColon + 1).trim(); + target[key] = value; + } + + return target; + } + + function styleObjectToString(obj) { + var result = ''; + + for (var _key4 in obj) { + result += _key4 + ':' + obj[_key4] + ';'; + } + + return result; + } + + function applySurrogateInstruction(container, element, instruction, controllers, bindings, children) { + var behaviorInstructions = instruction.behaviorInstructions; + var expressions = instruction.expressions; + var providers = instruction.providers; + var values = instruction.values; + var i = void 0; + var ii = void 0; + var current = void 0; + var instance = void 0; + var currentAttributeValue = void 0; + + i = providers.length; + while (i--) { + container._resolvers.set(providers[i], providerResolverInstance); + } + + for (var _key5 in values) { + currentAttributeValue = element.getAttribute(_key5); + + if (currentAttributeValue) { + if (_key5 === 'class') { + element.setAttribute('class', currentAttributeValue + ' ' + values[_key5]); + } else if (_key5 === 'style') { + var styleObject = styleStringToObject(values[_key5]); + styleStringToObject(currentAttributeValue, styleObject); + element.setAttribute('style', styleObjectToString(styleObject)); + } + } else { + element.setAttribute(_key5, values[_key5]); + } + } + + if (behaviorInstructions.length) { + for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { + current = behaviorInstructions[i]; + instance = current.type.create(container, current, element, bindings); + + if (instance.contentView) { + children.push(instance.contentView); + } + + controllers.push(instance); + } + } + + for (i = 0, ii = expressions.length; i < ii; ++i) { + bindings.push(expressions[i].createBinding(element)); + } + } + + var BoundViewFactory = exports.BoundViewFactory = function () { + function BoundViewFactory(parentContainer, viewFactory, partReplacements) { + + + this.parentContainer = parentContainer; + this.viewFactory = viewFactory; + this.factoryCreateInstruction = { partReplacements: partReplacements }; + } + + BoundViewFactory.prototype.create = function create() { + var view = this.viewFactory.create(this.parentContainer.createChild(), this.factoryCreateInstruction); + view._isUserControlled = true; + return view; + }; + + BoundViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) { + this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet); + }; + + BoundViewFactory.prototype.getCachedView = function getCachedView() { + return this.viewFactory.getCachedView(); + }; + + BoundViewFactory.prototype.returnViewToCache = function returnViewToCache(view) { + this.viewFactory.returnViewToCache(view); + }; + + _createClass(BoundViewFactory, [{ + key: 'isCaching', + get: function get() { + return this.viewFactory.isCaching; + } + }]); + + return BoundViewFactory; + }(); + + var ViewFactory = exports.ViewFactory = function () { + function ViewFactory(template, instructions, resources) { + + + this.isCaching = false; + + this.template = template; + this.instructions = instructions; + this.resources = resources; + this.cacheSize = -1; + this.cache = null; + } + + ViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) { + if (size) { + if (size === '*') { + size = Number.MAX_VALUE; + } else if (typeof size === 'string') { + size = parseInt(size, 10); + } + } + + if (this.cacheSize === -1 || !doNotOverrideIfAlreadySet) { + this.cacheSize = size; + } + + if (this.cacheSize > 0) { + this.cache = []; + } else { + this.cache = null; + } + + this.isCaching = this.cacheSize > 0; + }; + + ViewFactory.prototype.getCachedView = function getCachedView() { + return this.cache !== null ? this.cache.pop() || null : null; + }; + + ViewFactory.prototype.returnViewToCache = function returnViewToCache(view) { + if (view.isAttached) { + view.detached(); + } + + if (view.isBound) { + view.unbind(); + } + + if (this.cache !== null && this.cache.length < this.cacheSize) { + view.fromCache = true; + this.cache.push(view); + } + }; + + ViewFactory.prototype.create = function create(container, createInstruction, element) { + createInstruction = createInstruction || BehaviorInstruction.normal; + + var cachedView = this.getCachedView(); + if (cachedView !== null) { + return cachedView; + } + + var fragment = createInstruction.enhance ? this.template : this.template.cloneNode(true); + var instructables = fragment.querySelectorAll('.au-target'); + var instructions = this.instructions; + var resources = this.resources; + var controllers = []; + var bindings = []; + var children = []; + var shadowSlots = Object.create(null); + var containers = { root: container }; + var partReplacements = createInstruction.partReplacements; + var i = void 0; + var ii = void 0; + var view = void 0; + var instructable = void 0; + var instruction = void 0; + + this.resources._invokeHook('beforeCreate', this, container, fragment, createInstruction); + + if (element && this.surrogateInstruction !== null) { + applySurrogateInstruction(container, element, this.surrogateInstruction, controllers, bindings, children); + } + + if (createInstruction.enhance && fragment.hasAttribute('au-target-id')) { + instructable = fragment; + instruction = instructions[instructable.getAttribute('au-target-id')]; + applyInstructions(containers, instructable, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources); + } + + for (i = 0, ii = instructables.length; i < ii; ++i) { + instructable = instructables[i]; + instruction = instructions[instructable.getAttribute('au-target-id')]; + applyInstructions(containers, instructable, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources); + } + + view = new View(container, this, fragment, controllers, bindings, children, shadowSlots); + + if (!createInstruction.initiatedByBehavior) { + view.created(); + } + + this.resources._invokeHook('afterCreate', view); + + return view; + }; + + return ViewFactory; + }(); + + var nextInjectorId = 0; + function getNextInjectorId() { + return ++nextInjectorId; + } + + var lastAUTargetID = 0; + function getNextAUTargetID() { + return (++lastAUTargetID).toString(); + } + + function makeIntoInstructionTarget(element) { + var value = element.getAttribute('class'); + var auTargetID = getNextAUTargetID(); + + element.setAttribute('class', value ? value + ' au-target' : 'au-target'); + element.setAttribute('au-target-id', auTargetID); + + return auTargetID; + } + + function makeShadowSlot(compiler, resources, node, instructions, parentInjectorId) { + var auShadowSlot = _aureliaPal.DOM.createElement('au-shadow-slot'); + _aureliaPal.DOM.replaceNode(auShadowSlot, node); + + var auTargetID = makeIntoInstructionTarget(auShadowSlot); + var instruction = TargetInstruction.shadowSlot(parentInjectorId); + + instruction.slotName = node.getAttribute('name') || ShadowDOM.defaultSlotKey; + instruction.slotDestination = node.getAttribute('slot'); + + if (node.innerHTML.trim()) { + var fragment = _aureliaPal.DOM.createDocumentFragment(); + var _child4 = void 0; + + while (_child4 = node.firstChild) { + fragment.appendChild(_child4); + } + + instruction.slotFallbackFactory = compiler.compile(fragment, resources); + } + + instructions[auTargetID] = instruction; + + return auShadowSlot; + } + + var ViewCompiler = exports.ViewCompiler = (_dec7 = (0, _aureliaDependencyInjection.inject)(BindingLanguage, ViewResources), _dec7(_class13 = function () { + function ViewCompiler(bindingLanguage, resources) { + + + this.bindingLanguage = bindingLanguage; + this.resources = resources; + } + + ViewCompiler.prototype.compile = function compile(source, resources, compileInstruction) { + resources = resources || this.resources; + compileInstruction = compileInstruction || ViewCompileInstruction.normal; + source = typeof source === 'string' ? _aureliaPal.DOM.createTemplateFromMarkup(source) : source; + + var content = void 0; + var part = void 0; + var cacheSize = void 0; + + if (source.content) { + part = source.getAttribute('part'); + cacheSize = source.getAttribute('view-cache'); + content = _aureliaPal.DOM.adoptNode(source.content); + } else { + content = source; + } + + compileInstruction.targetShadowDOM = compileInstruction.targetShadowDOM && _aureliaPal.FEATURE.shadowDOM; + resources._invokeHook('beforeCompile', content, resources, compileInstruction); + + var instructions = {}; + this._compileNode(content, resources, instructions, source, 'root', !compileInstruction.targetShadowDOM); + + var firstChild = content.firstChild; + if (firstChild && firstChild.nodeType === 1) { + var targetId = firstChild.getAttribute('au-target-id'); + if (targetId) { + var ins = instructions[targetId]; + + if (ins.shadowSlot || ins.lifting || ins.elementInstruction && !ins.elementInstruction.anchorIsContainer) { + content.insertBefore(_aureliaPal.DOM.createComment('view'), firstChild); + } + } + } + + var factory = new ViewFactory(content, instructions, resources); + + factory.surrogateInstruction = compileInstruction.compileSurrogate ? this._compileSurrogate(source, resources) : null; + factory.part = part; + + if (cacheSize) { + factory.setCacheSize(cacheSize); + } + + resources._invokeHook('afterCompile', factory); + + return factory; + }; + + ViewCompiler.prototype._compileNode = function _compileNode(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) { + switch (node.nodeType) { + case 1: + return this._compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM); + case 3: + var expression = resources.getBindingLanguage(this.bindingLanguage).inspectTextContent(resources, node.wholeText); + if (expression) { + var marker = _aureliaPal.DOM.createElement('au-marker'); + var auTargetID = makeIntoInstructionTarget(marker); + (node.parentNode || parentNode).insertBefore(marker, node); + node.textContent = ' '; + instructions[auTargetID] = TargetInstruction.contentExpression(expression); + + while (node.nextSibling && node.nextSibling.nodeType === 3) { + (node.parentNode || parentNode).removeChild(node.nextSibling); + } + } else { + while (node.nextSibling && node.nextSibling.nodeType === 3) { + node = node.nextSibling; + } + } + return node.nextSibling; + case 11: + var currentChild = node.firstChild; + while (currentChild) { + currentChild = this._compileNode(currentChild, resources, instructions, node, parentInjectorId, targetLightDOM); + } + break; + default: + break; + } + + return node.nextSibling; + }; + + ViewCompiler.prototype._compileSurrogate = function _compileSurrogate(node, resources) { + var tagName = node.tagName.toLowerCase(); + var attributes = node.attributes; + var bindingLanguage = resources.getBindingLanguage(this.bindingLanguage); + var knownAttribute = void 0; + var property = void 0; + var instruction = void 0; + var i = void 0; + var ii = void 0; + var attr = void 0; + var attrName = void 0; + var attrValue = void 0; + var info = void 0; + var type = void 0; + var expressions = []; + var expression = void 0; + var behaviorInstructions = []; + var values = {}; + var hasValues = false; + var providers = []; + + for (i = 0, ii = attributes.length; i < ii; ++i) { + attr = attributes[i]; + attrName = attr.name; + attrValue = attr.value; + + info = bindingLanguage.inspectAttribute(resources, tagName, attrName, attrValue); + type = resources.getAttribute(info.attrName); + + if (type) { + knownAttribute = resources.mapAttribute(info.attrName); + if (knownAttribute) { + property = type.attributes[knownAttribute]; + + if (property) { + info.defaultBindingMode = property.defaultBindingMode; + + if (!info.command && !info.expression) { + info.command = property.hasOptions ? 'options' : null; + } + + if (info.command && info.command !== 'options' && type.primaryProperty) { + var _primaryProperty = type.primaryProperty; + attrName = info.attrName = _primaryProperty.attribute; + + info.defaultBindingMode = _primaryProperty.defaultBindingMode; + } + } + } + } + + instruction = bindingLanguage.createAttributeInstruction(resources, node, info, undefined, type); + + if (instruction) { + if (instruction.alteredAttr) { + type = resources.getAttribute(instruction.attrName); + } + + if (instruction.discrete) { + expressions.push(instruction); + } else { + if (type) { + instruction.type = type; + this._configureProperties(instruction, resources); + + if (type.liftsContent) { + throw new Error('You cannot place a template controller on a surrogate element.'); + } else { + behaviorInstructions.push(instruction); + } + } else { + expressions.push(instruction.attributes[instruction.attrName]); + } + } + } else { + if (type) { + instruction = BehaviorInstruction.attribute(attrName, type); + instruction.attributes[resources.mapAttribute(attrName)] = attrValue; + + if (type.liftsContent) { + throw new Error('You cannot place a template controller on a surrogate element.'); + } else { + behaviorInstructions.push(instruction); + } + } else if (attrName !== 'id' && attrName !== 'part' && attrName !== 'replace-part') { + hasValues = true; + values[attrName] = attrValue; + } + } + } + + if (expressions.length || behaviorInstructions.length || hasValues) { + for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { + instruction = behaviorInstructions[i]; + instruction.type.compile(this, resources, node, instruction); + providers.push(instruction.type.target); + } + + for (i = 0, ii = expressions.length; i < ii; ++i) { + expression = expressions[i]; + if (expression.attrToRemove !== undefined) { + node.removeAttribute(expression.attrToRemove); + } + } + + return TargetInstruction.surrogate(providers, behaviorInstructions, expressions, values); + } + + return null; + }; + + ViewCompiler.prototype._compileElement = function _compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) { + var tagName = node.tagName.toLowerCase(); + var attributes = node.attributes; + var expressions = []; + var expression = void 0; + var behaviorInstructions = []; + var providers = []; + var bindingLanguage = resources.getBindingLanguage(this.bindingLanguage); + var liftingInstruction = void 0; + var viewFactory = void 0; + var type = void 0; + var elementInstruction = void 0; + var elementProperty = void 0; + var i = void 0; + var ii = void 0; + var attr = void 0; + var attrName = void 0; + var attrValue = void 0; + var originalAttrName = void 0; + var instruction = void 0; + var info = void 0; + var property = void 0; + var knownAttribute = void 0; + var auTargetID = void 0; + var injectorId = void 0; + + if (tagName === 'slot') { + if (targetLightDOM) { + node = makeShadowSlot(this, resources, node, instructions, parentInjectorId); + } + return node.nextSibling; + } else if (tagName === 'template') { + if (!('content' in node)) { + throw new Error('You cannot place a template element within ' + node.namespaceURI + ' namespace'); + } + viewFactory = this.compile(node, resources); + viewFactory.part = node.getAttribute('part'); + } else { + type = resources.getElement(node.getAttribute('as-element') || tagName); + if (type) { + elementInstruction = BehaviorInstruction.element(node, type); + type.processAttributes(this, resources, node, attributes, elementInstruction); + behaviorInstructions.push(elementInstruction); + } + } + + for (i = 0, ii = attributes.length; i < ii; ++i) { + attr = attributes[i]; + originalAttrName = attrName = attr.name; + attrValue = attr.value; + info = bindingLanguage.inspectAttribute(resources, tagName, attrName, attrValue); + + if (targetLightDOM && info.attrName === 'slot') { + info.attrName = attrName = 'au-slot'; + } + + type = resources.getAttribute(info.attrName); + elementProperty = null; + + if (type) { + knownAttribute = resources.mapAttribute(info.attrName); + if (knownAttribute) { + property = type.attributes[knownAttribute]; + + if (property) { + info.defaultBindingMode = property.defaultBindingMode; + + if (!info.command && !info.expression) { + info.command = property.hasOptions ? 'options' : null; + } + + if (info.command && info.command !== 'options' && type.primaryProperty) { + var _primaryProperty2 = type.primaryProperty; + attrName = info.attrName = _primaryProperty2.attribute; + + info.defaultBindingMode = _primaryProperty2.defaultBindingMode; + } + } + } + } else if (elementInstruction) { + elementProperty = elementInstruction.type.attributes[info.attrName]; + if (elementProperty) { + info.defaultBindingMode = elementProperty.defaultBindingMode; + } + } + + if (elementProperty) { + instruction = bindingLanguage.createAttributeInstruction(resources, node, info, elementInstruction); + } else { + instruction = bindingLanguage.createAttributeInstruction(resources, node, info, undefined, type); + } + + if (instruction) { + if (instruction.alteredAttr) { + type = resources.getAttribute(instruction.attrName); + } + + if (instruction.discrete) { + expressions.push(instruction); + } else { + if (type) { + instruction.type = type; + this._configureProperties(instruction, resources); + + if (type.liftsContent) { + instruction.originalAttrName = originalAttrName; + liftingInstruction = instruction; + break; + } else { + behaviorInstructions.push(instruction); + } + } else if (elementProperty) { + elementInstruction.attributes[info.attrName].targetProperty = elementProperty.name; + } else { + expressions.push(instruction.attributes[instruction.attrName]); + } + } + } else { + if (type) { + instruction = BehaviorInstruction.attribute(attrName, type); + instruction.attributes[resources.mapAttribute(attrName)] = attrValue; + + if (type.liftsContent) { + instruction.originalAttrName = originalAttrName; + liftingInstruction = instruction; + break; + } else { + behaviorInstructions.push(instruction); + } + } else if (elementProperty) { + elementInstruction.attributes[attrName] = attrValue; + } + } + } + + if (liftingInstruction) { + liftingInstruction.viewFactory = viewFactory; + node = liftingInstruction.type.compile(this, resources, node, liftingInstruction, parentNode); + auTargetID = makeIntoInstructionTarget(node); + instructions[auTargetID] = TargetInstruction.lifting(parentInjectorId, liftingInstruction); + } else { + var skipContentProcessing = false; + + if (expressions.length || behaviorInstructions.length) { + injectorId = behaviorInstructions.length ? getNextInjectorId() : false; + + for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { + instruction = behaviorInstructions[i]; + instruction.type.compile(this, resources, node, instruction, parentNode); + providers.push(instruction.type.target); + skipContentProcessing = skipContentProcessing || instruction.skipContentProcessing; + } + + for (i = 0, ii = expressions.length; i < ii; ++i) { + expression = expressions[i]; + if (expression.attrToRemove !== undefined) { + node.removeAttribute(expression.attrToRemove); + } + } + + auTargetID = makeIntoInstructionTarget(node); + instructions[auTargetID] = TargetInstruction.normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction); + } + + if (skipContentProcessing) { + return node.nextSibling; + } + + var currentChild = node.firstChild; + while (currentChild) { + currentChild = this._compileNode(currentChild, resources, instructions, node, injectorId || parentInjectorId, targetLightDOM); + } + } + + return node.nextSibling; + }; + + ViewCompiler.prototype._configureProperties = function _configureProperties(instruction, resources) { + var type = instruction.type; + var attrName = instruction.attrName; + var attributes = instruction.attributes; + var property = void 0; + var key = void 0; + var value = void 0; + + var knownAttribute = resources.mapAttribute(attrName); + if (knownAttribute && attrName in attributes && knownAttribute !== attrName) { + attributes[knownAttribute] = attributes[attrName]; + delete attributes[attrName]; + } + + for (key in attributes) { + value = attributes[key]; + + if (value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { + property = type.attributes[key]; + + if (property !== undefined) { + value.targetProperty = property.name; + } else { + value.targetProperty = key; + } + } + } + }; + + return ViewCompiler; + }()) || _class13); + + var ResourceModule = exports.ResourceModule = function () { + function ResourceModule(moduleId) { + + + this.id = moduleId; + this.moduleInstance = null; + this.mainResource = null; + this.resources = null; + this.viewStrategy = null; + this.isInitialized = false; + this.onLoaded = null; + this.loadContext = null; + } + + ResourceModule.prototype.initialize = function initialize(container) { + var current = this.mainResource; + var resources = this.resources; + var vs = this.viewStrategy; + + if (this.isInitialized) { + return; + } + + this.isInitialized = true; + + if (current !== undefined) { + current.metadata.viewStrategy = vs; + current.initialize(container); + } + + for (var i = 0, ii = resources.length; i < ii; ++i) { + current = resources[i]; + current.metadata.viewStrategy = vs; + current.initialize(container); + } + }; + + ResourceModule.prototype.register = function register(registry, name) { + var main = this.mainResource; + var resources = this.resources; + + if (main !== undefined) { + main.register(registry, name); + name = null; + } + + for (var i = 0, ii = resources.length; i < ii; ++i) { + resources[i].register(registry, name); + name = null; + } + }; + + ResourceModule.prototype.load = function load(container, loadContext) { + if (this.onLoaded !== null) { + return this.loadContext === loadContext ? Promise.resolve() : this.onLoaded; + } + + var main = this.mainResource; + var resources = this.resources; + var loads = void 0; + + if (main !== undefined) { + loads = new Array(resources.length + 1); + loads[0] = main.load(container, loadContext); + for (var i = 0, ii = resources.length; i < ii; ++i) { + loads[i + 1] = resources[i].load(container, loadContext); + } + } else { + loads = new Array(resources.length); + for (var _i2 = 0, _ii = resources.length; _i2 < _ii; ++_i2) { + loads[_i2] = resources[_i2].load(container, loadContext); + } + } + + this.loadContext = loadContext; + this.onLoaded = Promise.all(loads); + return this.onLoaded; + }; + + return ResourceModule; + }(); + + var ResourceDescription = exports.ResourceDescription = function () { + function ResourceDescription(key, exportedValue, resourceTypeMeta) { + + + if (!resourceTypeMeta) { + resourceTypeMeta = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.resource, exportedValue); + + if (!resourceTypeMeta) { + resourceTypeMeta = new HtmlBehaviorResource(); + resourceTypeMeta.elementName = _hyphenate(key); + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, resourceTypeMeta, exportedValue); + } + } + + if (resourceTypeMeta instanceof HtmlBehaviorResource) { + if (resourceTypeMeta.elementName === undefined) { + resourceTypeMeta.elementName = _hyphenate(key); + } else if (resourceTypeMeta.attributeName === undefined) { + resourceTypeMeta.attributeName = _hyphenate(key); + } else if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { + HtmlBehaviorResource.convention(key, resourceTypeMeta); + } + } else if (!resourceTypeMeta.name) { + resourceTypeMeta.name = _hyphenate(key); + } + + this.metadata = resourceTypeMeta; + this.value = exportedValue; + } + + ResourceDescription.prototype.initialize = function initialize(container) { + this.metadata.initialize(container, this.value); + }; + + ResourceDescription.prototype.register = function register(registry, name) { + this.metadata.register(registry, name); + }; + + ResourceDescription.prototype.load = function load(container, loadContext) { + return this.metadata.load(container, this.value, loadContext); + }; + + return ResourceDescription; + }(); + + var ModuleAnalyzer = exports.ModuleAnalyzer = function () { + function ModuleAnalyzer() { + + + this.cache = Object.create(null); + } + + ModuleAnalyzer.prototype.getAnalysis = function getAnalysis(moduleId) { + return this.cache[moduleId]; + }; + + ModuleAnalyzer.prototype.analyze = function analyze(moduleId, moduleInstance, mainResourceKey) { + var mainResource = void 0; + var fallbackValue = void 0; + var fallbackKey = void 0; + var resourceTypeMeta = void 0; + var key = void 0; + var exportedValue = void 0; + var resources = []; + var conventional = void 0; + var vs = void 0; + var resourceModule = void 0; + + resourceModule = this.cache[moduleId]; + if (resourceModule) { + return resourceModule; + } + + resourceModule = new ResourceModule(moduleId); + this.cache[moduleId] = resourceModule; + + if (typeof moduleInstance === 'function') { + moduleInstance = { 'default': moduleInstance }; + } + + if (mainResourceKey) { + mainResource = new ResourceDescription(mainResourceKey, moduleInstance[mainResourceKey]); + } + + for (key in moduleInstance) { + exportedValue = moduleInstance[key]; + + if (key === mainResourceKey || typeof exportedValue !== 'function') { + continue; + } + + resourceTypeMeta = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.resource, exportedValue); + + if (resourceTypeMeta) { + if (resourceTypeMeta instanceof HtmlBehaviorResource) { + ViewResources.convention(exportedValue, resourceTypeMeta); + + if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { + HtmlBehaviorResource.convention(key, resourceTypeMeta); + } + + if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { + resourceTypeMeta.elementName = _hyphenate(key); + } + } + + if (!mainResource && resourceTypeMeta instanceof HtmlBehaviorResource && resourceTypeMeta.elementName !== null) { + mainResource = new ResourceDescription(key, exportedValue, resourceTypeMeta); + } else { + resources.push(new ResourceDescription(key, exportedValue, resourceTypeMeta)); + } + } else if (viewStrategy.decorates(exportedValue)) { + vs = exportedValue; + } else if (exportedValue instanceof _aureliaLoader.TemplateRegistryEntry) { + vs = new TemplateRegistryViewStrategy(moduleId, exportedValue); + } else { + if (conventional = ViewResources.convention(exportedValue)) { + if (conventional.elementName !== null && !mainResource) { + mainResource = new ResourceDescription(key, exportedValue, conventional); + } else { + resources.push(new ResourceDescription(key, exportedValue, conventional)); + } + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue); + } else if (conventional = HtmlBehaviorResource.convention(key)) { + if (conventional.elementName !== null && !mainResource) { + mainResource = new ResourceDescription(key, exportedValue, conventional); + } else { + resources.push(new ResourceDescription(key, exportedValue, conventional)); + } + + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue); + } else if (conventional = _aureliaBinding.ValueConverterResource.convention(key) || _aureliaBinding.BindingBehaviorResource.convention(key) || ViewEngineHooksResource.convention(key)) { + resources.push(new ResourceDescription(key, exportedValue, conventional)); + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue); + } else if (!fallbackValue) { + fallbackValue = exportedValue; + fallbackKey = key; + } + } + } + + if (!mainResource && fallbackValue) { + mainResource = new ResourceDescription(fallbackKey, fallbackValue); + } + + resourceModule.moduleInstance = moduleInstance; + resourceModule.mainResource = mainResource; + resourceModule.resources = resources; + resourceModule.viewStrategy = vs; + + return resourceModule; + }; + + return ModuleAnalyzer; + }(); + + var logger = LogManager.getLogger('templating'); + + function ensureRegistryEntry(loader, urlOrRegistryEntry) { + if (urlOrRegistryEntry instanceof _aureliaLoader.TemplateRegistryEntry) { + return Promise.resolve(urlOrRegistryEntry); + } + + return loader.loadTemplate(urlOrRegistryEntry); + } + + var ProxyViewFactory = function () { + function ProxyViewFactory(promise) { + var _this8 = this; + + + + promise.then(function (x) { + return _this8.viewFactory = x; + }); + } + + ProxyViewFactory.prototype.create = function create(container, bindingContext, createInstruction, element) { + return this.viewFactory.create(container, bindingContext, createInstruction, element); + }; + + ProxyViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) { + this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet); + }; + + ProxyViewFactory.prototype.getCachedView = function getCachedView() { + return this.viewFactory.getCachedView(); + }; + + ProxyViewFactory.prototype.returnViewToCache = function returnViewToCache(view) { + this.viewFactory.returnViewToCache(view); + }; + + _createClass(ProxyViewFactory, [{ + key: 'isCaching', + get: function get() { + return this.viewFactory.isCaching; + } + }]); + + return ProxyViewFactory; + }(); + + var auSlotBehavior = null; + + var ViewEngine = exports.ViewEngine = (_dec8 = (0, _aureliaDependencyInjection.inject)(_aureliaLoader.Loader, _aureliaDependencyInjection.Container, ViewCompiler, ModuleAnalyzer, ViewResources), _dec8(_class14 = (_temp4 = _class15 = function () { + function ViewEngine(loader, container, viewCompiler, moduleAnalyzer, appResources) { + + + this.loader = loader; + this.container = container; + this.viewCompiler = viewCompiler; + this.moduleAnalyzer = moduleAnalyzer; + this.appResources = appResources; + this._pluginMap = {}; + + if (auSlotBehavior === null) { + auSlotBehavior = new HtmlBehaviorResource(); + auSlotBehavior.attributeName = 'au-slot'; + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, auSlotBehavior, SlotCustomAttribute); + } + + auSlotBehavior.initialize(container, SlotCustomAttribute); + auSlotBehavior.register(appResources); + } + + ViewEngine.prototype.addResourcePlugin = function addResourcePlugin(extension, implementation) { + var name = extension.replace('.', '') + '-resource-plugin'; + this._pluginMap[extension] = name; + this.loader.addPlugin(name, implementation); + }; + + ViewEngine.prototype.loadViewFactory = function loadViewFactory(urlOrRegistryEntry, compileInstruction, loadContext, target) { + var _this9 = this; + + loadContext = loadContext || new ResourceLoadContext(); + + return ensureRegistryEntry(this.loader, urlOrRegistryEntry).then(function (registryEntry) { + var url = registryEntry.address; + + if (registryEntry.onReady) { + if (!loadContext.hasDependency(url)) { + loadContext.addDependency(url); + return registryEntry.onReady; + } + + if (registryEntry.template === null) { + return registryEntry.onReady; + } + + return Promise.resolve(new ProxyViewFactory(registryEntry.onReady)); + } + + loadContext.addDependency(url); + + registryEntry.onReady = _this9.loadTemplateResources(registryEntry, compileInstruction, loadContext, target).then(function (resources) { + registryEntry.resources = resources; + + if (registryEntry.template === null) { + return registryEntry.factory = null; + } + + var viewFactory = _this9.viewCompiler.compile(registryEntry.template, resources, compileInstruction); + return registryEntry.factory = viewFactory; + }); + + return registryEntry.onReady; + }); + }; + + ViewEngine.prototype.loadTemplateResources = function loadTemplateResources(registryEntry, compileInstruction, loadContext, target) { + var resources = new ViewResources(this.appResources, registryEntry.address); + var dependencies = registryEntry.dependencies; + var importIds = void 0; + var names = void 0; + + compileInstruction = compileInstruction || ViewCompileInstruction.normal; + + if (dependencies.length === 0 && !compileInstruction.associatedModuleId) { + return Promise.resolve(resources); + } + + importIds = dependencies.map(function (x) { + return x.src; + }); + names = dependencies.map(function (x) { + return x.name; + }); + logger.debug('importing resources for ' + registryEntry.address, importIds); + + if (target) { + var viewModelRequires = _aureliaMetadata.metadata.get(ViewEngine.viewModelRequireMetadataKey, target); + if (viewModelRequires) { + var templateImportCount = importIds.length; + for (var i = 0, ii = viewModelRequires.length; i < ii; ++i) { + var req = viewModelRequires[i]; + var importId = typeof req === 'function' ? _aureliaMetadata.Origin.get(req).moduleId : (0, _aureliaPath.relativeToFile)(req.src || req, registryEntry.address); + + if (importIds.indexOf(importId) === -1) { + importIds.push(importId); + names.push(req.as); + } + } + logger.debug('importing ViewModel resources for ' + compileInstruction.associatedModuleId, importIds.slice(templateImportCount)); + } + } + + return this.importViewResources(importIds, names, resources, compileInstruction, loadContext); + }; + + ViewEngine.prototype.importViewModelResource = function importViewModelResource(moduleImport, moduleMember) { + var _this10 = this; + + return this.loader.loadModule(moduleImport).then(function (viewModelModule) { + var normalizedId = _aureliaMetadata.Origin.get(viewModelModule).moduleId; + var resourceModule = _this10.moduleAnalyzer.analyze(normalizedId, viewModelModule, moduleMember); + + if (!resourceModule.mainResource) { + throw new Error('No view model found in module "' + moduleImport + '".'); + } + + resourceModule.initialize(_this10.container); + + return resourceModule.mainResource; + }); + }; + + ViewEngine.prototype.importViewResources = function importViewResources(moduleIds, names, resources, compileInstruction, loadContext) { + var _this11 = this; + + loadContext = loadContext || new ResourceLoadContext(); + compileInstruction = compileInstruction || ViewCompileInstruction.normal; + + moduleIds = moduleIds.map(function (x) { + return _this11._applyLoaderPlugin(x); + }); + + return this.loader.loadAllModules(moduleIds).then(function (imports) { + var i = void 0; + var ii = void 0; + var analysis = void 0; + var normalizedId = void 0; + var current = void 0; + var associatedModule = void 0; + var container = _this11.container; + var moduleAnalyzer = _this11.moduleAnalyzer; + var allAnalysis = new Array(imports.length); + + for (i = 0, ii = imports.length; i < ii; ++i) { + current = imports[i]; + normalizedId = _aureliaMetadata.Origin.get(current).moduleId; + + analysis = moduleAnalyzer.analyze(normalizedId, current); + analysis.initialize(container); + analysis.register(resources, names[i]); + + allAnalysis[i] = analysis; + } + + if (compileInstruction.associatedModuleId) { + associatedModule = moduleAnalyzer.getAnalysis(compileInstruction.associatedModuleId); + + if (associatedModule) { + associatedModule.register(resources); + } + } + + for (i = 0, ii = allAnalysis.length; i < ii; ++i) { + allAnalysis[i] = allAnalysis[i].load(container, loadContext); + } + + return Promise.all(allAnalysis).then(function () { + return resources; + }); + }); + }; + + ViewEngine.prototype._applyLoaderPlugin = function _applyLoaderPlugin(id) { + var index = id.lastIndexOf('.'); + if (index !== -1) { + var ext = id.substring(index); + var pluginName = this._pluginMap[ext]; + + if (pluginName === undefined) { + return id; + } + + return this.loader.applyPluginToUrl(id, pluginName); + } + + return id; + }; + + return ViewEngine; + }(), _class15.viewModelRequireMetadataKey = 'aurelia:view-model-require', _temp4)) || _class14); + + var Controller = exports.Controller = function () { + function Controller(behavior, instruction, viewModel, container) { + + + this.behavior = behavior; + this.instruction = instruction; + this.viewModel = viewModel; + this.isAttached = false; + this.view = null; + this.isBound = false; + this.scope = null; + this.container = container; + this.elementEvents = container.elementEvents || null; + + var observerLookup = behavior.observerLocator.getOrCreateObserversLookup(viewModel); + var handlesBind = behavior.handlesBind; + var attributes = instruction.attributes; + var boundProperties = this.boundProperties = []; + var properties = behavior.properties; + var i = void 0; + var ii = void 0; + + behavior._ensurePropertiesDefined(viewModel, observerLookup); + + for (i = 0, ii = properties.length; i < ii; ++i) { + properties[i]._initialize(viewModel, observerLookup, attributes, handlesBind, boundProperties); + } + } + + Controller.prototype.created = function created(owningView) { + if (this.behavior.handlesCreated) { + this.viewModel.created(owningView, this.view); + } + }; + + Controller.prototype.automate = function automate(overrideContext, owningView) { + this.view.bindingContext = this.viewModel; + this.view.overrideContext = overrideContext || (0, _aureliaBinding.createOverrideContext)(this.viewModel); + this.view._isUserControlled = true; + + if (this.behavior.handlesCreated) { + this.viewModel.created(owningView || null, this.view); + } + + this.bind(this.view); + }; + + Controller.prototype.bind = function bind(scope) { + var skipSelfSubscriber = this.behavior.handlesBind; + var boundProperties = this.boundProperties; + var i = void 0; + var ii = void 0; + var x = void 0; + var observer = void 0; + var selfSubscriber = void 0; + + if (this.isBound) { + if (this.scope === scope) { + return; + } + + this.unbind(); + } + + this.isBound = true; + this.scope = scope; + + for (i = 0, ii = boundProperties.length; i < ii; ++i) { + x = boundProperties[i]; + observer = x.observer; + selfSubscriber = observer.selfSubscriber; + observer.publishing = false; + + if (skipSelfSubscriber) { + observer.selfSubscriber = null; + } + + x.binding.bind(scope); + observer.call(); + + observer.publishing = true; + observer.selfSubscriber = selfSubscriber; + } + + var overrideContext = void 0; + if (this.view !== null) { + if (skipSelfSubscriber) { + this.view.viewModelScope = scope; + } + + if (this.viewModel === scope.overrideContext.bindingContext) { + overrideContext = scope.overrideContext; + } else if (this.instruction.inheritBindingContext) { + overrideContext = (0, _aureliaBinding.createOverrideContext)(this.viewModel, scope.overrideContext); + } else { + overrideContext = (0, _aureliaBinding.createOverrideContext)(this.viewModel); + overrideContext.__parentOverrideContext = scope.overrideContext; + } + + this.view.bind(this.viewModel, overrideContext); + } else if (skipSelfSubscriber) { + overrideContext = scope.overrideContext; + + if (scope.overrideContext.__parentOverrideContext !== undefined && this.viewModel.viewFactory && this.viewModel.viewFactory.factoryCreateInstruction.partReplacements) { + overrideContext = Object.assign({}, scope.overrideContext); + overrideContext.parentOverrideContext = scope.overrideContext.__parentOverrideContext; + } + this.viewModel.bind(scope.bindingContext, overrideContext); + } + }; + + Controller.prototype.unbind = function unbind() { + if (this.isBound) { + var _boundProperties = this.boundProperties; + var _i3 = void 0; + var _ii2 = void 0; + + this.isBound = false; + this.scope = null; + + if (this.view !== null) { + this.view.unbind(); + } + + if (this.behavior.handlesUnbind) { + this.viewModel.unbind(); + } + + if (this.elementEvents !== null) { + this.elementEvents.disposeAll(); + } + + for (_i3 = 0, _ii2 = _boundProperties.length; _i3 < _ii2; ++_i3) { + _boundProperties[_i3].binding.unbind(); + } + } + }; + + Controller.prototype.attached = function attached() { + if (this.isAttached) { + return; + } + + this.isAttached = true; + + if (this.behavior.handlesAttached) { + this.viewModel.attached(); + } + + if (this.view !== null) { + this.view.attached(); + } + }; + + Controller.prototype.detached = function detached() { + if (this.isAttached) { + this.isAttached = false; + + if (this.view !== null) { + this.view.detached(); + } + + if (this.behavior.handlesDetached) { + this.viewModel.detached(); + } + } + }; + + return Controller; + }(); + + var BehaviorPropertyObserver = exports.BehaviorPropertyObserver = (_dec9 = (0, _aureliaBinding.subscriberCollection)(), _dec9(_class16 = function () { + function BehaviorPropertyObserver(taskQueue, obj, propertyName, selfSubscriber, initialValue) { + + + this.taskQueue = taskQueue; + this.obj = obj; + this.propertyName = propertyName; + this.notqueued = true; + this.publishing = false; + this.selfSubscriber = selfSubscriber; + this.currentValue = this.oldValue = initialValue; + } + + BehaviorPropertyObserver.prototype.getValue = function getValue() { + return this.currentValue; + }; + + BehaviorPropertyObserver.prototype.setValue = function setValue(newValue) { + var oldValue = this.currentValue; + + if (!Object.is(newValue, oldValue)) { + this.oldValue = oldValue; + this.currentValue = newValue; + + if (this.publishing && this.notqueued) { + if (this.taskQueue.flushing) { + this.call(); + } else { + this.notqueued = false; + this.taskQueue.queueMicroTask(this); + } + } + } + }; + + BehaviorPropertyObserver.prototype.call = function call() { + var oldValue = this.oldValue; + var newValue = this.currentValue; + + this.notqueued = true; + + if (Object.is(newValue, oldValue)) { + return; + } + + if (this.selfSubscriber) { + this.selfSubscriber(newValue, oldValue); + } + + this.callSubscribers(newValue, oldValue); + this.oldValue = newValue; + }; + + BehaviorPropertyObserver.prototype.subscribe = function subscribe(context, callable) { + this.addSubscriber(context, callable); + }; + + BehaviorPropertyObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + this.removeSubscriber(context, callable); + }; + + return BehaviorPropertyObserver; + }()) || _class16); + + + function getObserver(instance, name) { + var lookup = instance.__observers__; + + if (lookup === undefined) { + var ctor = Object.getPrototypeOf(instance).constructor; + var _behavior = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.resource, ctor); + if (!_behavior.isInitialized) { + _behavior.initialize(_aureliaDependencyInjection.Container.instance || new _aureliaDependencyInjection.Container(), instance.constructor); + } + + lookup = _behavior.observerLocator.getOrCreateObserversLookup(instance); + _behavior._ensurePropertiesDefined(instance, lookup); + } + + return lookup[name]; + } + + var BindableProperty = exports.BindableProperty = function () { + function BindableProperty(nameOrConfig) { + + + if (typeof nameOrConfig === 'string') { + this.name = nameOrConfig; + } else { + Object.assign(this, nameOrConfig); + } + + this.attribute = this.attribute || _hyphenate(this.name); + var defaultBindingMode = this.defaultBindingMode; + if (defaultBindingMode === null || defaultBindingMode === undefined) { + this.defaultBindingMode = _aureliaBinding.bindingMode.oneWay; + } else if (typeof defaultBindingMode === 'string') { + this.defaultBindingMode = _aureliaBinding.bindingMode[defaultBindingMode] || _aureliaBinding.bindingMode.oneWay; + } + this.changeHandler = this.changeHandler || null; + this.owner = null; + this.descriptor = null; + } + + BindableProperty.prototype.registerWith = function registerWith(target, behavior, descriptor) { + behavior.properties.push(this); + behavior.attributes[this.attribute] = this; + this.owner = behavior; + + if (descriptor) { + this.descriptor = descriptor; + return this._configureDescriptor(descriptor); + } + + return undefined; + }; + + BindableProperty.prototype._configureDescriptor = function _configureDescriptor(descriptor) { + var name = this.name; + + descriptor.configurable = true; + descriptor.enumerable = true; + + if ('initializer' in descriptor) { + this.defaultValue = descriptor.initializer; + delete descriptor.initializer; + delete descriptor.writable; + } + + if ('value' in descriptor) { + this.defaultValue = descriptor.value; + delete descriptor.value; + delete descriptor.writable; + } + + descriptor.get = function () { + return getObserver(this, name).getValue(); + }; + + descriptor.set = function (value) { + getObserver(this, name).setValue(value); + }; + + descriptor.get.getObserver = function (obj) { + return getObserver(obj, name); + }; + + return descriptor; + }; + + BindableProperty.prototype.defineOn = function defineOn(target, behavior) { + var name = this.name; + var handlerName = void 0; + + if (this.changeHandler === null) { + handlerName = name + 'Changed'; + if (handlerName in target.prototype) { + this.changeHandler = handlerName; + } + } + + if (this.descriptor === null) { + Object.defineProperty(target.prototype, name, this._configureDescriptor(behavior, {})); + } + }; + + BindableProperty.prototype.createObserver = function createObserver(viewModel) { + var selfSubscriber = null; + var defaultValue = this.defaultValue; + var changeHandlerName = this.changeHandler; + var name = this.name; + var initialValue = void 0; + + if (this.hasOptions) { + return undefined; + } + + if (changeHandlerName in viewModel) { + if ('propertyChanged' in viewModel) { + selfSubscriber = function selfSubscriber(newValue, oldValue) { + viewModel[changeHandlerName](newValue, oldValue); + viewModel.propertyChanged(name, newValue, oldValue); + }; + } else { + selfSubscriber = function selfSubscriber(newValue, oldValue) { + return viewModel[changeHandlerName](newValue, oldValue); + }; + } + } else if ('propertyChanged' in viewModel) { + selfSubscriber = function selfSubscriber(newValue, oldValue) { + return viewModel.propertyChanged(name, newValue, oldValue); + }; + } else if (changeHandlerName !== null) { + throw new Error('Change handler ' + changeHandlerName + ' was specified but not declared on the class.'); + } + + if (defaultValue !== undefined) { + initialValue = typeof defaultValue === 'function' ? defaultValue.call(viewModel) : defaultValue; + } + + return new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, this.name, selfSubscriber, initialValue); + }; + + BindableProperty.prototype._initialize = function _initialize(viewModel, observerLookup, attributes, behaviorHandlesBind, boundProperties) { + var selfSubscriber = void 0; + var observer = void 0; + var attribute = void 0; + var defaultValue = this.defaultValue; + + if (this.isDynamic) { + for (var _key6 in attributes) { + this._createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, _key6, attributes[_key6], boundProperties); + } + } else if (!this.hasOptions) { + observer = observerLookup[this.name]; + + if (attributes !== null) { + selfSubscriber = observer.selfSubscriber; + attribute = attributes[this.attribute]; + + if (behaviorHandlesBind) { + observer.selfSubscriber = null; + } + + if (typeof attribute === 'string') { + viewModel[this.name] = attribute; + observer.call(); + } else if (attribute) { + boundProperties.push({ observer: observer, binding: attribute.createBinding(viewModel) }); + } else if (defaultValue !== undefined) { + observer.call(); + } + + observer.selfSubscriber = selfSubscriber; + } + + observer.publishing = true; + } + }; + + BindableProperty.prototype._createDynamicProperty = function _createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, name, attribute, boundProperties) { + var changeHandlerName = name + 'Changed'; + var selfSubscriber = null; + var observer = void 0; + var info = void 0; + + if (changeHandlerName in viewModel) { + if ('propertyChanged' in viewModel) { + selfSubscriber = function selfSubscriber(newValue, oldValue) { + viewModel[changeHandlerName](newValue, oldValue); + viewModel.propertyChanged(name, newValue, oldValue); + }; + } else { + selfSubscriber = function selfSubscriber(newValue, oldValue) { + return viewModel[changeHandlerName](newValue, oldValue); + }; + } + } else if ('propertyChanged' in viewModel) { + selfSubscriber = function selfSubscriber(newValue, oldValue) { + return viewModel.propertyChanged(name, newValue, oldValue); + }; + } + + observer = observerLookup[name] = new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, name, selfSubscriber); + + Object.defineProperty(viewModel, name, { + configurable: true, + enumerable: true, + get: observer.getValue.bind(observer), + set: observer.setValue.bind(observer) + }); + + if (behaviorHandlesBind) { + observer.selfSubscriber = null; + } + + if (typeof attribute === 'string') { + viewModel[name] = attribute; + observer.call(); + } else if (attribute) { + info = { observer: observer, binding: attribute.createBinding(viewModel) }; + boundProperties.push(info); + } + + observer.publishing = true; + observer.selfSubscriber = selfSubscriber; + }; + + return BindableProperty; + }(); + + var lastProviderId = 0; + + function nextProviderId() { + return ++lastProviderId; + } + + function doProcessContent() { + return true; + } + function doProcessAttributes() {} + + var HtmlBehaviorResource = exports.HtmlBehaviorResource = function () { + function HtmlBehaviorResource() { + + + this.elementName = null; + this.attributeName = null; + this.attributeDefaultBindingMode = undefined; + this.liftsContent = false; + this.targetShadowDOM = false; + this.shadowDOMOptions = null; + this.processAttributes = doProcessAttributes; + this.processContent = doProcessContent; + this.usesShadowDOM = false; + this.childBindings = null; + this.hasDynamicOptions = false; + this.containerless = false; + this.properties = []; + this.attributes = {}; + this.isInitialized = false; + this.primaryProperty = null; + } + + HtmlBehaviorResource.convention = function convention(name, existing) { + var behavior = void 0; + + if (name.endsWith('CustomAttribute')) { + behavior = existing || new HtmlBehaviorResource(); + behavior.attributeName = _hyphenate(name.substring(0, name.length - 15)); + } + + if (name.endsWith('CustomElement')) { + behavior = existing || new HtmlBehaviorResource(); + behavior.elementName = _hyphenate(name.substring(0, name.length - 13)); + } + + return behavior; + }; + + HtmlBehaviorResource.prototype.addChildBinding = function addChildBinding(behavior) { + if (this.childBindings === null) { + this.childBindings = []; + } + + this.childBindings.push(behavior); + }; + + HtmlBehaviorResource.prototype.initialize = function initialize(container, target) { + var proto = target.prototype; + var properties = this.properties; + var attributeName = this.attributeName; + var attributeDefaultBindingMode = this.attributeDefaultBindingMode; + var i = void 0; + var ii = void 0; + var current = void 0; + + if (this.isInitialized) { + return; + } + + this.isInitialized = true; + target.__providerId__ = nextProviderId(); + + this.observerLocator = container.get(_aureliaBinding.ObserverLocator); + this.taskQueue = container.get(_aureliaTaskQueue.TaskQueue); + + this.target = target; + this.usesShadowDOM = this.targetShadowDOM && _aureliaPal.FEATURE.shadowDOM; + this.handlesCreated = 'created' in proto; + this.handlesBind = 'bind' in proto; + this.handlesUnbind = 'unbind' in proto; + this.handlesAttached = 'attached' in proto; + this.handlesDetached = 'detached' in proto; + this.htmlName = this.elementName || this.attributeName; + + if (attributeName !== null) { + if (properties.length === 0) { + new BindableProperty({ + name: 'value', + changeHandler: 'valueChanged' in proto ? 'valueChanged' : null, + attribute: attributeName, + defaultBindingMode: attributeDefaultBindingMode + }).registerWith(target, this); + } + + current = properties[0]; + + if (properties.length === 1 && current.name === 'value') { + current.isDynamic = current.hasOptions = this.hasDynamicOptions; + current.defineOn(target, this); + } else { + for (i = 0, ii = properties.length; i < ii; ++i) { + properties[i].defineOn(target, this); + if (properties[i].primaryProperty) { + if (this.primaryProperty) { + throw new Error('Only one bindable property on a custom element can be defined as the default'); + } + this.primaryProperty = properties[i]; + } + } + + current = new BindableProperty({ + name: 'value', + changeHandler: 'valueChanged' in proto ? 'valueChanged' : null, + attribute: attributeName, + defaultBindingMode: attributeDefaultBindingMode + }); + + current.hasOptions = true; + current.registerWith(target, this); + } + } else { + for (i = 0, ii = properties.length; i < ii; ++i) { + properties[i].defineOn(target, this); + } + + this._copyInheritedProperties(container, target); + } + }; + + HtmlBehaviorResource.prototype.register = function register(registry, name) { + var _this12 = this; + + if (this.attributeName !== null) { + registry.registerAttribute(name || this.attributeName, this, this.attributeName); + + if (Array.isArray(this.aliases)) { + this.aliases.forEach(function (alias) { + registry.registerAttribute(alias, _this12, _this12.attributeName); + }); + } + } + + if (this.elementName !== null) { + registry.registerElement(name || this.elementName, this); + } + }; + + HtmlBehaviorResource.prototype.load = function load(container, target, loadContext, viewStrategy, transientView) { + var _this13 = this; + + var options = void 0; + + if (this.elementName !== null) { + viewStrategy = container.get(ViewLocator).getViewStrategy(viewStrategy || this.viewStrategy || target); + options = new ViewCompileInstruction(this.targetShadowDOM, true); + + if (!viewStrategy.moduleId) { + viewStrategy.moduleId = _aureliaMetadata.Origin.get(target).moduleId; + } + + return viewStrategy.loadViewFactory(container.get(ViewEngine), options, loadContext, target).then(function (viewFactory) { + if (!transientView || !_this13.viewFactory) { + _this13.viewFactory = viewFactory; + } + + return viewFactory; + }); + } + + return Promise.resolve(this); + }; + + HtmlBehaviorResource.prototype.compile = function compile(compiler, resources, node, instruction, parentNode) { + if (this.liftsContent) { + if (!instruction.viewFactory) { + var _template = _aureliaPal.DOM.createElement('template'); + var fragment = _aureliaPal.DOM.createDocumentFragment(); + var cacheSize = node.getAttribute('view-cache'); + var part = node.getAttribute('part'); + + node.removeAttribute(instruction.originalAttrName); + _aureliaPal.DOM.replaceNode(_template, node, parentNode); + fragment.appendChild(node); + instruction.viewFactory = compiler.compile(fragment, resources); + + if (part) { + instruction.viewFactory.part = part; + node.removeAttribute('part'); + } + + if (cacheSize) { + instruction.viewFactory.setCacheSize(cacheSize); + node.removeAttribute('view-cache'); + } + + node = _template; + } + } else if (this.elementName !== null) { + var _partReplacements2 = {}; + + if (this.processContent(compiler, resources, node, instruction) && node.hasChildNodes()) { + var currentChild = node.firstChild; + var contentElement = this.usesShadowDOM ? null : _aureliaPal.DOM.createElement('au-content'); + var nextSibling = void 0; + var toReplace = void 0; + + while (currentChild) { + nextSibling = currentChild.nextSibling; + + if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) { + _partReplacements2[toReplace] = compiler.compile(currentChild, resources); + _aureliaPal.DOM.removeNode(currentChild, parentNode); + instruction.partReplacements = _partReplacements2; + } else if (contentElement !== null) { + if (currentChild.nodeType === 3 && _isAllWhitespace(currentChild)) { + _aureliaPal.DOM.removeNode(currentChild, parentNode); + } else { + contentElement.appendChild(currentChild); + } + } + + currentChild = nextSibling; + } + + if (contentElement !== null && contentElement.hasChildNodes()) { + node.appendChild(contentElement); + } + + instruction.skipContentProcessing = false; + } else { + instruction.skipContentProcessing = true; + } + } else if (!this.processContent(compiler, resources, node, instruction)) { + instruction.skipContentProcessing = true; + } + + return node; + }; + + HtmlBehaviorResource.prototype.create = function create(container, instruction, element, bindings) { + var viewHost = void 0; + var au = null; + + instruction = instruction || BehaviorInstruction.normal; + element = element || null; + bindings = bindings || null; + + if (this.elementName !== null && element) { + if (this.usesShadowDOM) { + viewHost = element.attachShadow(this.shadowDOMOptions); + container.registerInstance(_aureliaPal.DOM.boundary, viewHost); + } else { + viewHost = element; + if (this.targetShadowDOM) { + container.registerInstance(_aureliaPal.DOM.boundary, viewHost); + } + } + } + + if (element !== null) { + element.au = au = element.au || {}; + } + + var viewModel = instruction.viewModel || container.get(this.target); + var controller = new Controller(this, instruction, viewModel, container); + var childBindings = this.childBindings; + var viewFactory = void 0; + + if (this.liftsContent) { + au.controller = controller; + } else if (this.elementName !== null) { + viewFactory = instruction.viewFactory || this.viewFactory; + container.viewModel = viewModel; + + if (viewFactory) { + controller.view = viewFactory.create(container, instruction, element); + } + + if (element !== null) { + au.controller = controller; + + if (controller.view) { + if (!this.usesShadowDOM && (element.childNodes.length === 1 || element.contentElement)) { + var contentElement = element.childNodes[0] || element.contentElement; + controller.view.contentView = { fragment: contentElement }; + contentElement.parentNode && _aureliaPal.DOM.removeNode(contentElement); + } + + if (instruction.anchorIsContainer) { + if (childBindings !== null) { + for (var _i4 = 0, _ii3 = childBindings.length; _i4 < _ii3; ++_i4) { + controller.view.addBinding(childBindings[_i4].create(element, viewModel, controller)); + } + } + + controller.view.appendNodesTo(viewHost); + } else { + controller.view.insertNodesBefore(viewHost); + } + } else if (childBindings !== null) { + for (var _i5 = 0, _ii4 = childBindings.length; _i5 < _ii4; ++_i5) { + bindings.push(childBindings[_i5].create(element, viewModel, controller)); + } + } + } else if (controller.view) { + controller.view.controller = controller; + + if (childBindings !== null) { + for (var _i6 = 0, _ii5 = childBindings.length; _i6 < _ii5; ++_i6) { + controller.view.addBinding(childBindings[_i6].create(instruction.host, viewModel, controller)); + } + } + } else if (childBindings !== null) { + for (var _i7 = 0, _ii6 = childBindings.length; _i7 < _ii6; ++_i7) { + bindings.push(childBindings[_i7].create(instruction.host, viewModel, controller)); + } + } + } else if (childBindings !== null) { + for (var _i8 = 0, _ii7 = childBindings.length; _i8 < _ii7; ++_i8) { + bindings.push(childBindings[_i8].create(element, viewModel, controller)); + } + } + + if (au !== null) { + au[this.htmlName] = controller; + } + + if (instruction.initiatedByBehavior && viewFactory) { + controller.view.created(); + } + + return controller; + }; + + HtmlBehaviorResource.prototype._ensurePropertiesDefined = function _ensurePropertiesDefined(instance, lookup) { + var properties = void 0; + var i = void 0; + var ii = void 0; + var observer = void 0; + + if ('__propertiesDefined__' in lookup) { + return; + } + + lookup.__propertiesDefined__ = true; + properties = this.properties; + + for (i = 0, ii = properties.length; i < ii; ++i) { + observer = properties[i].createObserver(instance); + + if (observer !== undefined) { + lookup[observer.propertyName] = observer; + } + } + }; + + HtmlBehaviorResource.prototype._copyInheritedProperties = function _copyInheritedProperties(container, target) { + var _this14 = this; + + var behavior = void 0; + var derived = target; + + while (true) { + var proto = Object.getPrototypeOf(target.prototype); + target = proto && proto.constructor; + if (!target) { + return; + } + behavior = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.resource, target); + if (behavior) { + break; + } + } + behavior.initialize(container, target); + + var _loop = function _loop(_i9, _ii8) { + var prop = behavior.properties[_i9]; + + if (_this14.properties.some(function (p) { + return p.name === prop.name; + })) { + return 'continue'; + } + + new BindableProperty(prop).registerWith(derived, _this14); + }; + + for (var _i9 = 0, _ii8 = behavior.properties.length; _i9 < _ii8; ++_i9) { + var _ret = _loop(_i9, _ii8); + + if (_ret === 'continue') continue; + } + }; + + return HtmlBehaviorResource; + }(); + + function createChildObserverDecorator(selectorOrConfig, all) { + return function (target, key, descriptor) { + var actualTarget = typeof key === 'string' ? target.constructor : target; + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, actualTarget); + + if (typeof selectorOrConfig === 'string') { + selectorOrConfig = { + selector: selectorOrConfig, + name: key + }; + } + + if (descriptor) { + descriptor.writable = true; + descriptor.configurable = true; + } + + selectorOrConfig.all = all; + r.addChildBinding(new ChildObserver(selectorOrConfig)); + }; + } + + function children(selectorOrConfig) { + return createChildObserverDecorator(selectorOrConfig, true); + } + + function child(selectorOrConfig) { + return createChildObserverDecorator(selectorOrConfig, false); + } + + var ChildObserver = function () { + function ChildObserver(config) { + + + this.name = config.name; + this.changeHandler = config.changeHandler || this.name + 'Changed'; + this.selector = config.selector; + this.all = config.all; + } + + ChildObserver.prototype.create = function create(viewHost, viewModel, controller) { + return new ChildObserverBinder(this.selector, viewHost, this.name, viewModel, controller, this.changeHandler, this.all); + }; + + return ChildObserver; + }(); + + var noMutations = []; + + function trackMutation(groupedMutations, binder, record) { + var mutations = groupedMutations.get(binder); + + if (!mutations) { + mutations = []; + groupedMutations.set(binder, mutations); + } + + mutations.push(record); + } + + function onChildChange(mutations, observer) { + var binders = observer.binders; + var bindersLength = binders.length; + var groupedMutations = new Map(); + + for (var _i10 = 0, _ii9 = mutations.length; _i10 < _ii9; ++_i10) { + var record = mutations[_i10]; + var added = record.addedNodes; + var removed = record.removedNodes; + + for (var j = 0, jj = removed.length; j < jj; ++j) { + var _node = removed[j]; + if (_node.nodeType === 1) { + for (var k = 0; k < bindersLength; ++k) { + var binder = binders[k]; + if (binder.onRemove(_node)) { + trackMutation(groupedMutations, binder, record); + } + } + } + } + + for (var _j = 0, _jj = added.length; _j < _jj; ++_j) { + var _node2 = added[_j]; + if (_node2.nodeType === 1) { + for (var _k = 0; _k < bindersLength; ++_k) { + var _binder = binders[_k]; + if (_binder.onAdd(_node2)) { + trackMutation(groupedMutations, _binder, record); + } + } + } + } + } + + groupedMutations.forEach(function (value, key) { + if (key.changeHandler !== null) { + key.viewModel[key.changeHandler](value); + } + }); + } + + var ChildObserverBinder = function () { + function ChildObserverBinder(selector, viewHost, property, viewModel, controller, changeHandler, all) { + + + this.selector = selector; + this.viewHost = viewHost; + this.property = property; + this.viewModel = viewModel; + this.controller = controller; + this.changeHandler = changeHandler in viewModel ? changeHandler : null; + this.usesShadowDOM = controller.behavior.usesShadowDOM; + this.all = all; + + if (!this.usesShadowDOM && controller.view && controller.view.contentView) { + this.contentView = controller.view.contentView; + } else { + this.contentView = null; + } + } + + ChildObserverBinder.prototype.matches = function matches(element) { + if (element.matches(this.selector)) { + if (this.contentView === null) { + return true; + } + + var contentView = this.contentView; + var assignedSlot = element.auAssignedSlot; + + if (assignedSlot && assignedSlot.projectFromAnchors) { + var anchors = assignedSlot.projectFromAnchors; + + for (var _i11 = 0, _ii10 = anchors.length; _i11 < _ii10; ++_i11) { + if (anchors[_i11].auOwnerView === contentView) { + return true; + } + } + + return false; + } + + return element.auOwnerView === contentView; + } + + return false; + }; + + ChildObserverBinder.prototype.bind = function bind(source) { + var viewHost = this.viewHost; + var viewModel = this.viewModel; + var observer = viewHost.__childObserver__; + + if (!observer) { + observer = viewHost.__childObserver__ = _aureliaPal.DOM.createMutationObserver(onChildChange); + + var options = { + childList: true, + subtree: !this.usesShadowDOM + }; + + observer.observe(viewHost, options); + observer.binders = []; + } + + observer.binders.push(this); + + if (this.usesShadowDOM) { + var current = viewHost.firstElementChild; + + if (this.all) { + var items = viewModel[this.property]; + if (!items) { + items = viewModel[this.property] = []; + } else { + items.splice(0); + } + + while (current) { + if (this.matches(current)) { + items.push(current.au && current.au.controller ? current.au.controller.viewModel : current); + } + + current = current.nextElementSibling; + } + + if (this.changeHandler !== null) { + this.viewModel[this.changeHandler](noMutations); + } + } else { + while (current) { + if (this.matches(current)) { + var value = current.au && current.au.controller ? current.au.controller.viewModel : current; + this.viewModel[this.property] = value; + + if (this.changeHandler !== null) { + this.viewModel[this.changeHandler](value); + } + + break; + } + + current = current.nextElementSibling; + } + } + } + }; + + ChildObserverBinder.prototype.onRemove = function onRemove(element) { + if (this.matches(element)) { + var value = element.au && element.au.controller ? element.au.controller.viewModel : element; + + if (this.all) { + var items = this.viewModel[this.property] || (this.viewModel[this.property] = []); + var index = items.indexOf(value); + + if (index !== -1) { + items.splice(index, 1); + } + + return true; + } + + return false; + } + + return false; + }; + + ChildObserverBinder.prototype.onAdd = function onAdd(element) { + if (this.matches(element)) { + var value = element.au && element.au.controller ? element.au.controller.viewModel : element; + + if (this.all) { + var items = this.viewModel[this.property] || (this.viewModel[this.property] = []); + + if (this.selector === '*') { + items.push(value); + return true; + } + + var index = 0; + var prev = element.previousElementSibling; + + while (prev) { + if (this.matches(prev)) { + index++; + } + + prev = prev.previousElementSibling; + } + + items.splice(index, 0, value); + return true; + } + + this.viewModel[this.property] = value; + + if (this.changeHandler !== null) { + this.viewModel[this.changeHandler](value); + } + } + + return false; + }; + + ChildObserverBinder.prototype.unbind = function unbind() { + if (this.viewHost.__childObserver__) { + this.viewHost.__childObserver__.disconnect(); + this.viewHost.__childObserver__ = null; + this.viewModel[this.property] = null; + } + }; + + return ChildObserverBinder; + }(); + + function remove(viewSlot, previous) { + return Array.isArray(previous) ? viewSlot.removeMany(previous, true) : viewSlot.remove(previous, true); + } + + var SwapStrategies = exports.SwapStrategies = { + before: function before(viewSlot, previous, callback) { + return previous === undefined ? callback() : callback().then(function () { + return remove(viewSlot, previous); + }); + }, + with: function _with(viewSlot, previous, callback) { + return previous === undefined ? callback() : Promise.all([remove(viewSlot, previous), callback()]); + }, + after: function after(viewSlot, previous, callback) { + return Promise.resolve(viewSlot.removeAll(true)).then(callback); + } + }; + + function tryActivateViewModel(context) { + if (context.skipActivation || typeof context.viewModel.activate !== 'function') { + return Promise.resolve(); + } + + return context.viewModel.activate(context.model) || Promise.resolve(); + } + + var CompositionEngine = exports.CompositionEngine = (_dec10 = (0, _aureliaDependencyInjection.inject)(ViewEngine, ViewLocator), _dec10(_class17 = function () { + function CompositionEngine(viewEngine, viewLocator) { + + + this.viewEngine = viewEngine; + this.viewLocator = viewLocator; + } + + CompositionEngine.prototype._swap = function _swap(context, view) { + var swapStrategy = SwapStrategies[context.swapOrder] || SwapStrategies.after; + var previousViews = context.viewSlot.children.slice(); + + return swapStrategy(context.viewSlot, previousViews, function () { + return Promise.resolve(context.viewSlot.add(view)).then(function () { + if (context.currentController) { + context.currentController.unbind(); + } + }); + }).then(function () { + if (context.compositionTransactionNotifier) { + context.compositionTransactionNotifier.done(); + } + }); + }; + + CompositionEngine.prototype._createControllerAndSwap = function _createControllerAndSwap(context) { + var _this15 = this; + + return this.createController(context).then(function (controller) { + if (context.compositionTransactionOwnershipToken) { + return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(function () { + controller.automate(context.overrideContext, context.owningView); + + return _this15._swap(context, controller.view); + }).then(function () { + return controller; + }); + } + + controller.automate(context.overrideContext, context.owningView); + + return _this15._swap(context, controller.view).then(function () { + return controller; + }); + }); + }; + + CompositionEngine.prototype.createController = function createController(context) { + var _this16 = this; + + var childContainer = void 0; + var viewModel = void 0; + var viewModelResource = void 0; + + var m = void 0; + + return this.ensureViewModel(context).then(tryActivateViewModel).then(function () { + childContainer = context.childContainer; + viewModel = context.viewModel; + viewModelResource = context.viewModelResource; + m = viewModelResource.metadata; + + var viewStrategy = _this16.viewLocator.getViewStrategy(context.view || viewModel); + + if (context.viewResources) { + viewStrategy.makeRelativeTo(context.viewResources.viewUrl); + } + + return m.load(childContainer, viewModelResource.value, null, viewStrategy, true); + }).then(function (viewFactory) { + return m.create(childContainer, BehaviorInstruction.dynamic(context.host, viewModel, viewFactory)); + }); + }; + + CompositionEngine.prototype.ensureViewModel = function ensureViewModel(context) { + var childContainer = context.childContainer = context.childContainer || context.container.createChild(); + + if (typeof context.viewModel === 'string') { + context.viewModel = context.viewResources ? context.viewResources.relativeToView(context.viewModel) : context.viewModel; + + return this.viewEngine.importViewModelResource(context.viewModel).then(function (viewModelResource) { + childContainer.autoRegister(viewModelResource.value); + + if (context.host) { + childContainer.registerInstance(_aureliaPal.DOM.Element, context.host); + } + + context.viewModel = childContainer.viewModel = childContainer.get(viewModelResource.value); + context.viewModelResource = viewModelResource; + return context; + }); + } + + var ctor = context.viewModel.constructor; + var isClass = typeof context.viewModel === 'function'; + if (isClass) { + ctor = context.viewModel; + childContainer.autoRegister(ctor); + } + var m = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, ctor); + + m.elementName = m.elementName || 'dynamic-element'; + + m.initialize(isClass ? childContainer : context.container || childContainer, ctor); + + context.viewModelResource = { metadata: m, value: ctor }; + + if (context.host) { + childContainer.registerInstance(_aureliaPal.DOM.Element, context.host); + } + childContainer.viewModel = context.viewModel = isClass ? childContainer.get(ctor) : context.viewModel; + return Promise.resolve(context); + }; + + CompositionEngine.prototype.compose = function compose(context) { + var _this17 = this; + + context.childContainer = context.childContainer || context.container.createChild(); + context.view = this.viewLocator.getViewStrategy(context.view); + + var transaction = context.childContainer.get(CompositionTransaction); + var compositionTransactionOwnershipToken = transaction.tryCapture(); + + if (compositionTransactionOwnershipToken) { + context.compositionTransactionOwnershipToken = compositionTransactionOwnershipToken; + } else { + context.compositionTransactionNotifier = transaction.enlist(); + } + + if (context.viewModel) { + return this._createControllerAndSwap(context); + } else if (context.view) { + if (context.viewResources) { + context.view.makeRelativeTo(context.viewResources.viewUrl); + } + + return context.view.loadViewFactory(this.viewEngine, new ViewCompileInstruction()).then(function (viewFactory) { + var result = viewFactory.create(context.childContainer); + result.bind(context.bindingContext, context.overrideContext); + + if (context.compositionTransactionOwnershipToken) { + return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(function () { + return _this17._swap(context, result); + }).then(function () { + return result; + }); + } + + return _this17._swap(context, result).then(function () { + return result; + }); + }); + } else if (context.viewSlot) { + context.viewSlot.removeAll(); + + if (context.compositionTransactionNotifier) { + context.compositionTransactionNotifier.done(); + } + + return Promise.resolve(null); + } + + return Promise.resolve(null); + }; + + return CompositionEngine; + }()) || _class17); + + var ElementConfigResource = exports.ElementConfigResource = function () { + function ElementConfigResource() { + + } + + ElementConfigResource.prototype.initialize = function initialize(container, target) {}; + + ElementConfigResource.prototype.register = function register(registry, name) {}; + + ElementConfigResource.prototype.load = function load(container, target) { + var config = new target(); + var eventManager = container.get(_aureliaBinding.EventManager); + eventManager.registerElementConfig(config); + }; + + return ElementConfigResource; + }(); + + function resource(instanceOrConfig) { + return function (target) { + var isConfig = typeof instanceOrConfig === 'string' || Object.getPrototypeOf(instanceOrConfig) === Object.prototype; + if (isConfig) { + target.$resource = instanceOrConfig; + } else { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, instanceOrConfig, target); + } + }; + } + + function behavior(override) { + return function (target) { + if (override instanceof HtmlBehaviorResource) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, override, target); + } else { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target); + Object.assign(r, override); + } + }; + } + + function customElement(name) { + return function (target) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target); + r.elementName = validateBehaviorName(name, 'custom element'); + }; + } + + function customAttribute(name, defaultBindingMode, aliases) { + return function (target) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target); + r.attributeName = validateBehaviorName(name, 'custom attribute'); + r.attributeDefaultBindingMode = defaultBindingMode; + r.aliases = aliases; + }; + } + + function templateController(target) { + var deco = function deco(t) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); + r.liftsContent = true; + }; + + return target ? deco(target) : deco; + } + + function bindable(nameOrConfigOrTarget, key, descriptor) { + var deco = function deco(target, key2, descriptor2) { + var actualTarget = key2 ? target.constructor : target; + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, actualTarget); + var prop = void 0; + + if (key2) { + nameOrConfigOrTarget = nameOrConfigOrTarget || {}; + nameOrConfigOrTarget.name = key2; + } + + prop = new BindableProperty(nameOrConfigOrTarget); + return prop.registerWith(actualTarget, r, descriptor2); + }; + + if (!nameOrConfigOrTarget) { + return deco; + } + + if (key) { + var _target = nameOrConfigOrTarget; + nameOrConfigOrTarget = null; + return deco(_target, key, descriptor); + } + + return deco; + } + + function dynamicOptions(target) { + var deco = function deco(t) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); + r.hasDynamicOptions = true; + }; + + return target ? deco(target) : deco; + } + + var defaultShadowDOMOptions = { mode: 'open' }; + function useShadowDOM(targetOrOptions) { + var options = typeof targetOrOptions === 'function' || !targetOrOptions ? defaultShadowDOMOptions : targetOrOptions; + + var deco = function deco(t) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); + r.targetShadowDOM = true; + r.shadowDOMOptions = options; + }; + + return typeof targetOrOptions === 'function' ? deco(targetOrOptions) : deco; + } + + function processAttributes(processor) { + return function (t) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); + r.processAttributes = function (compiler, resources, node, attributes, elementInstruction) { + try { + processor(compiler, resources, node, attributes, elementInstruction); + } catch (error) { + LogManager.getLogger('templating').error(error); + } + }; + }; + } + + function doNotProcessContent() { + return false; + } + + function processContent(processor) { + return function (t) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); + r.processContent = processor ? function (compiler, resources, node, instruction) { + try { + return processor(compiler, resources, node, instruction); + } catch (error) { + LogManager.getLogger('templating').error(error); + return false; + } + } : doNotProcessContent; + }; + } + + function containerless(target) { + var deco = function deco(t) { + var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); + r.containerless = true; + }; + + return target ? deco(target) : deco; + } + + function useViewStrategy(strategy) { + return function (target) { + _aureliaMetadata.metadata.define(ViewLocator.viewStrategyMetadataKey, strategy, target); + }; + } + + function useView(path) { + return useViewStrategy(new RelativeViewStrategy(path)); + } + + function inlineView(markup, dependencies, dependencyBaseUrl) { + return useViewStrategy(new InlineViewStrategy(markup, dependencies, dependencyBaseUrl)); + } + + function noView(targetOrDependencies, dependencyBaseUrl) { + var target = void 0; + var dependencies = void 0; + if (typeof targetOrDependencies === 'function') { + target = targetOrDependencies; + } else { + dependencies = targetOrDependencies; + target = undefined; + } + + var deco = function deco(t) { + _aureliaMetadata.metadata.define(ViewLocator.viewStrategyMetadataKey, new NoViewStrategy(dependencies, dependencyBaseUrl), t); + }; + + return target ? deco(target) : deco; + } + + function view(templateOrConfig) { + return function (target) { + target.$view = templateOrConfig; + }; + } + + function elementConfig(target) { + var deco = function deco(t) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ElementConfigResource(), t); + }; + + return target ? deco(target) : deco; + } + + function viewResources() { + for (var _len = arguments.length, resources = Array(_len), _key7 = 0; _key7 < _len; _key7++) { + resources[_key7] = arguments[_key7]; + } + + return function (target) { + _aureliaMetadata.metadata.define(ViewEngine.viewModelRequireMetadataKey, resources, target); + }; + } + + var TemplatingEngine = exports.TemplatingEngine = (_dec11 = (0, _aureliaDependencyInjection.inject)(_aureliaDependencyInjection.Container, ModuleAnalyzer, ViewCompiler, CompositionEngine), _dec11(_class18 = function () { + function TemplatingEngine(container, moduleAnalyzer, viewCompiler, compositionEngine) { + + + this._container = container; + this._moduleAnalyzer = moduleAnalyzer; + this._viewCompiler = viewCompiler; + this._compositionEngine = compositionEngine; + container.registerInstance(Animator, Animator.instance = new Animator()); + } + + TemplatingEngine.prototype.configureAnimator = function configureAnimator(animator) { + this._container.unregister(Animator); + this._container.registerInstance(Animator, Animator.instance = animator); + }; + + TemplatingEngine.prototype.compose = function compose(context) { + return this._compositionEngine.compose(context); + }; + + TemplatingEngine.prototype.enhance = function enhance(instruction) { + if (instruction instanceof _aureliaPal.DOM.Element) { + instruction = { element: instruction }; + } + + var compilerInstructions = {}; + var resources = instruction.resources || this._container.get(ViewResources); + + this._viewCompiler._compileNode(instruction.element, resources, compilerInstructions, instruction.element.parentNode, 'root', true); + + var factory = new ViewFactory(instruction.element, compilerInstructions, resources); + var container = instruction.container || this._container.createChild(); + var view = factory.create(container, BehaviorInstruction.enhance()); + + view.bind(instruction.bindingContext || {}, instruction.overrideContext); + + view.firstChild = view.lastChild = view.fragment; + view.fragment = _aureliaPal.DOM.createDocumentFragment(); + view.attached(); + + return view; + }; + + return TemplatingEngine; + }()) || _class18); +}); +define('aurelia-templating-router/router-view',['exports', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-templating', 'aurelia-router', 'aurelia-metadata', 'aurelia-pal'], function (exports, _aureliaDependencyInjection, _aureliaBinding, _aureliaTemplating, _aureliaRouter, _aureliaMetadata, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.RouterViewLocator = exports.RouterView = undefined; + + function _initDefineProp(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); + } + + + + function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } + + return desc; + } + + function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.'); + } + + var _dec, _dec2, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4; + + var RouterView = exports.RouterView = (_dec = (0, _aureliaTemplating.customElement)('router-view'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaDependencyInjection.Container, _aureliaTemplating.ViewSlot, _aureliaRouter.Router, _aureliaTemplating.ViewLocator, _aureliaTemplating.CompositionTransaction, _aureliaTemplating.CompositionEngine), _dec(_class = (0, _aureliaTemplating.noView)(_class = _dec2(_class = (_class2 = function () { + function RouterView(element, container, viewSlot, router, viewLocator, compositionTransaction, compositionEngine) { + + + _initDefineProp(this, 'swapOrder', _descriptor, this); + + _initDefineProp(this, 'layoutView', _descriptor2, this); + + _initDefineProp(this, 'layoutViewModel', _descriptor3, this); + + _initDefineProp(this, 'layoutModel', _descriptor4, this); + + this.element = element; + this.container = container; + this.viewSlot = viewSlot; + this.router = router; + this.viewLocator = viewLocator; + this.compositionTransaction = compositionTransaction; + this.compositionEngine = compositionEngine; + this.router.registerViewPort(this, this.element.getAttribute('name')); + + if (!('initialComposition' in compositionTransaction)) { + compositionTransaction.initialComposition = true; + this.compositionTransactionNotifier = compositionTransaction.enlist(); + } + } + + RouterView.prototype.created = function created(owningView) { + this.owningView = owningView; + }; + + RouterView.prototype.bind = function bind(bindingContext, overrideContext) { + this.container.viewModel = bindingContext; + this.overrideContext = overrideContext; + }; + + RouterView.prototype.process = function process(viewPortInstruction, waitToSwap) { + var _this = this; + + var component = viewPortInstruction.component; + var childContainer = component.childContainer; + var viewModel = component.viewModel; + var viewModelResource = component.viewModelResource; + var metadata = viewModelResource.metadata; + var config = component.router.currentInstruction.config; + var viewPort = config.viewPorts ? config.viewPorts[viewPortInstruction.name] || {} : {}; + + childContainer.get(RouterViewLocator)._notify(this); + + var layoutInstruction = { + viewModel: viewPort.layoutViewModel || config.layoutViewModel || this.layoutViewModel, + view: viewPort.layoutView || config.layoutView || this.layoutView, + model: viewPort.layoutModel || config.layoutModel || this.layoutModel, + router: viewPortInstruction.component.router, + childContainer: childContainer, + viewSlot: this.viewSlot + }; + + var viewStrategy = this.viewLocator.getViewStrategy(component.view || viewModel); + if (viewStrategy && component.view) { + viewStrategy.makeRelativeTo(_aureliaMetadata.Origin.get(component.router.container.viewModel.constructor).moduleId); + } + + return metadata.load(childContainer, viewModelResource.value, null, viewStrategy, true).then(function (viewFactory) { + if (!_this.compositionTransactionNotifier) { + _this.compositionTransactionOwnershipToken = _this.compositionTransaction.tryCapture(); + } + + if (layoutInstruction.viewModel || layoutInstruction.view) { + viewPortInstruction.layoutInstruction = layoutInstruction; + } + + viewPortInstruction.controller = metadata.create(childContainer, _aureliaTemplating.BehaviorInstruction.dynamic(_this.element, viewModel, viewFactory)); + + if (waitToSwap) { + return null; + } + + _this.swap(viewPortInstruction); + }); + }; + + RouterView.prototype.swap = function swap(viewPortInstruction) { + var _this2 = this; + + var layoutInstruction = viewPortInstruction.layoutInstruction; + var previousView = this.view; + + var work = function work() { + var swapStrategy = _aureliaTemplating.SwapStrategies[_this2.swapOrder] || _aureliaTemplating.SwapStrategies.after; + var viewSlot = _this2.viewSlot; + + swapStrategy(viewSlot, previousView, function () { + return Promise.resolve(viewSlot.add(_this2.view)); + }).then(function () { + _this2._notify(); + }); + }; + + var ready = function ready(owningView) { + viewPortInstruction.controller.automate(_this2.overrideContext, owningView); + if (_this2.compositionTransactionOwnershipToken) { + return _this2.compositionTransactionOwnershipToken.waitForCompositionComplete().then(function () { + _this2.compositionTransactionOwnershipToken = null; + return work(); + }); + } + + return work(); + }; + + if (layoutInstruction) { + if (!layoutInstruction.viewModel) { + layoutInstruction.viewModel = {}; + } + + return this.compositionEngine.createController(layoutInstruction).then(function (controller) { + _aureliaTemplating.ShadowDOM.distributeView(viewPortInstruction.controller.view, controller.slots || controller.view.slots); + controller.automate((0, _aureliaBinding.createOverrideContext)(layoutInstruction.viewModel), _this2.owningView); + controller.view.children.push(viewPortInstruction.controller.view); + return controller.view || controller; + }).then(function (newView) { + _this2.view = newView; + return ready(newView); + }); + } + + this.view = viewPortInstruction.controller.view; + + return ready(this.owningView); + }; + + RouterView.prototype._notify = function _notify() { + if (this.compositionTransactionNotifier) { + this.compositionTransactionNotifier.done(); + this.compositionTransactionNotifier = null; + } + }; + + return RouterView; + }(), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'swapOrder', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'layoutView', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'layoutViewModel', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'layoutModel', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + })), _class2)) || _class) || _class) || _class); + + var RouterViewLocator = exports.RouterViewLocator = function () { + function RouterViewLocator() { + var _this3 = this; + + + + this.promise = new Promise(function (resolve) { + return _this3.resolve = resolve; + }); + } + + RouterViewLocator.prototype.findNearest = function findNearest() { + return this.promise; + }; + + RouterViewLocator.prototype._notify = function _notify(routerView) { + this.resolve(routerView); + }; + + return RouterViewLocator; + }(); +}); +define('aurelia-templating-router/route-loader',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-router', 'aurelia-path', 'aurelia-metadata', './router-view'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaRouter, _aureliaPath, _aureliaMetadata, _routerView) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TemplatingRouteLoader = undefined; + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + + + var _dec, _class, _dec2, _class2; + + var EmptyClass = (_dec = (0, _aureliaTemplating.inlineView)(''), _dec(_class = function EmptyClass() { + + }) || _class); + var TemplatingRouteLoader = exports.TemplatingRouteLoader = (_dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.CompositionEngine), _dec2(_class2 = function (_RouteLoader) { + _inherits(TemplatingRouteLoader, _RouteLoader); + + function TemplatingRouteLoader(compositionEngine) { + + + var _this = _possibleConstructorReturn(this, _RouteLoader.call(this)); + + _this.compositionEngine = compositionEngine; + return _this; + } + + TemplatingRouteLoader.prototype.loadRoute = function loadRoute(router, config) { + var childContainer = router.container.createChild(); + + var viewModel = void 0; + if (config.moduleId === null) { + viewModel = EmptyClass; + } else if (/\.html/i.test(config.moduleId)) { + viewModel = createDynamicClass(config.moduleId); + } else { + viewModel = (0, _aureliaPath.relativeToFile)(config.moduleId, _aureliaMetadata.Origin.get(router.container.viewModel.constructor).moduleId); + } + + var instruction = { + viewModel: viewModel, + childContainer: childContainer, + view: config.view || config.viewStrategy, + router: router + }; + + childContainer.registerSingleton(_routerView.RouterViewLocator); + + childContainer.getChildRouter = function () { + var childRouter = void 0; + + childContainer.registerHandler(_aureliaRouter.Router, function (c) { + return childRouter || (childRouter = router.createChild(childContainer)); + }); + + return childContainer.get(_aureliaRouter.Router); + }; + + return this.compositionEngine.ensureViewModel(instruction); + }; + + return TemplatingRouteLoader; + }(_aureliaRouter.RouteLoader)) || _class2); + + + function createDynamicClass(moduleId) { + var _dec3, _dec4, _class3; + + var name = /([^\/^\?]+)\.html/i.exec(moduleId)[1]; + + var DynamicClass = (_dec3 = (0, _aureliaTemplating.customElement)(name), _dec4 = (0, _aureliaTemplating.useView)(moduleId), _dec3(_class3 = _dec4(_class3 = function () { + function DynamicClass() { + + } + + DynamicClass.prototype.bind = function bind(bindingContext) { + this.$parent = bindingContext; + }; + + return DynamicClass; + }()) || _class3) || _class3); + + + return DynamicClass; + } +}); +define('aurelia-templating-router/route-href',['exports', 'aurelia-templating', 'aurelia-dependency-injection', 'aurelia-router', 'aurelia-pal', 'aurelia-logging'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _aureliaRouter, _aureliaPal, _aureliaLogging) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.RouteHref = undefined; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + + + var _dec, _dec2, _dec3, _dec4, _dec5, _class; + + var logger = LogManager.getLogger('route-href'); + + var RouteHref = exports.RouteHref = (_dec = (0, _aureliaTemplating.customAttribute)('route-href'), _dec2 = (0, _aureliaTemplating.bindable)({ name: 'route', changeHandler: 'processChange', primaryProperty: true }), _dec3 = (0, _aureliaTemplating.bindable)({ name: 'params', changeHandler: 'processChange' }), _dec4 = (0, _aureliaTemplating.bindable)({ name: 'attribute', defaultValue: 'href' }), _dec5 = (0, _aureliaDependencyInjection.inject)(_aureliaRouter.Router, _aureliaPal.DOM.Element), _dec(_class = _dec2(_class = _dec3(_class = _dec4(_class = _dec5(_class = function () { + function RouteHref(router, element) { + + + this.router = router; + this.element = element; + } + + RouteHref.prototype.bind = function bind() { + this.isActive = true; + this.processChange(); + }; + + RouteHref.prototype.unbind = function unbind() { + this.isActive = false; + }; + + RouteHref.prototype.attributeChanged = function attributeChanged(value, previous) { + if (previous) { + this.element.removeAttribute(previous); + } + + this.processChange(); + }; + + RouteHref.prototype.processChange = function processChange() { + var _this = this; + + return this.router.ensureConfigured().then(function () { + if (!_this.isActive) { + return null; + } + + var href = _this.router.generate(_this.route, _this.params); + + if (_this.element.au.controller) { + _this.element.au.controller.viewModel[_this.attribute] = href; + } else { + _this.element.setAttribute(_this.attribute, href); + } + + return null; + }).catch(function (reason) { + logger.error(reason); + }); + }; + + return RouteHref; + }()) || _class) || _class) || _class) || _class) || _class); +}); +define('aurelia-templating-router/aurelia-templating-router',['exports', 'aurelia-router', './route-loader', './router-view', './route-href'], function (exports, _aureliaRouter, _routeLoader, _routerView, _routeHref) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.configure = exports.RouteHref = exports.RouterView = exports.TemplatingRouteLoader = undefined; + + + function configure(config) { + config.singleton(_aureliaRouter.RouteLoader, _routeLoader.TemplatingRouteLoader).singleton(_aureliaRouter.Router, _aureliaRouter.AppRouter).globalResources(_routerView.RouterView, _routeHref.RouteHref); + + config.container.registerAlias(_aureliaRouter.Router, _aureliaRouter.AppRouter); + } + + exports.TemplatingRouteLoader = _routeLoader.TemplatingRouteLoader; + exports.RouterView = _routerView.RouterView; + exports.RouteHref = _routeHref.RouteHref; + exports.configure = configure; +}); +;define('aurelia-templating-router', ['aurelia-templating-router/aurelia-templating-router'], function (main) { return main; }); + +define('aurelia-templating-resources/with',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-binding'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.With = undefined; + + + + var _dec, _dec2, _class; + + var With = exports.With = (_dec = (0, _aureliaTemplating.customAttribute)('with'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = function () { + function With(viewFactory, viewSlot) { + + + this.viewFactory = viewFactory; + this.viewSlot = viewSlot; + this.parentOverrideContext = null; + this.view = null; + } + + With.prototype.bind = function bind(bindingContext, overrideContext) { + this.parentOverrideContext = overrideContext; + this.valueChanged(this.value); + }; + + With.prototype.valueChanged = function valueChanged(newValue) { + var overrideContext = (0, _aureliaBinding.createOverrideContext)(newValue, this.parentOverrideContext); + if (!this.view) { + this.view = this.viewFactory.create(); + this.view.bind(newValue, overrideContext); + this.viewSlot.add(this.view); + } else { + this.view.bind(newValue, overrideContext); + } + }; + + With.prototype.unbind = function unbind() { + this.parentOverrideContext = null; + + if (this.view) { + this.view.unbind(); + } + }; + + return With; + }()) || _class) || _class) || _class); +}); +define('aurelia-templating-resources/update-trigger-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.UpdateTriggerBindingBehavior = undefined; + + + + var _dec, _class; + + var eventNamesRequired = 'The updateTrigger binding behavior requires at least one event name argument: eg '; + var notApplicableMessage = 'The updateTrigger binding behavior can only be applied to two-way/ from-view bindings on input/select elements.'; + + var UpdateTriggerBindingBehavior = exports.UpdateTriggerBindingBehavior = (_dec = (0, _aureliaBinding.bindingBehavior)('updateTrigger'), _dec(_class = function () { + function UpdateTriggerBindingBehavior() { + + } + + UpdateTriggerBindingBehavior.prototype.bind = function bind(binding, source) { + for (var _len = arguments.length, events = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + events[_key - 2] = arguments[_key]; + } + + if (events.length === 0) { + throw new Error(eventNamesRequired); + } + if (binding.mode !== _aureliaBinding.bindingMode.twoWay && binding.mode !== _aureliaBinding.bindingMode.fromView) { + throw new Error(notApplicableMessage); + } + + var targetObserver = binding.observerLocator.getObserver(binding.target, binding.targetProperty); + if (!targetObserver.handler) { + throw new Error(notApplicableMessage); + } + binding.targetObserver = targetObserver; + + targetObserver.originalHandler = binding.targetObserver.handler; + + var handler = new _aureliaBinding.EventSubscriber(events); + targetObserver.handler = handler; + }; + + UpdateTriggerBindingBehavior.prototype.unbind = function unbind(binding, source) { + binding.targetObserver.handler.dispose(); + binding.targetObserver.handler = binding.targetObserver.originalHandler; + binding.targetObserver.originalHandler = null; + }; + + return UpdateTriggerBindingBehavior; + }()) || _class); +}); +define('aurelia-templating-resources/throttle-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ThrottleBindingBehavior = undefined; + + + + var _dec, _class; + + function throttle(newValue) { + var _this = this; + + var state = this.throttleState; + var elapsed = +new Date() - state.last; + if (elapsed >= state.delay) { + clearTimeout(state.timeoutId); + state.timeoutId = null; + state.last = +new Date(); + this.throttledMethod(newValue); + return; + } + state.newValue = newValue; + if (state.timeoutId === null) { + state.timeoutId = setTimeout(function () { + state.timeoutId = null; + state.last = +new Date(); + _this.throttledMethod(state.newValue); + }, state.delay - elapsed); + } + } + + var ThrottleBindingBehavior = exports.ThrottleBindingBehavior = (_dec = (0, _aureliaBinding.bindingBehavior)('throttle'), _dec(_class = function () { + function ThrottleBindingBehavior() { + + } + + ThrottleBindingBehavior.prototype.bind = function bind(binding, source) { + var delay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 200; + + var methodToThrottle = 'updateTarget'; + if (binding.callSource) { + methodToThrottle = 'callSource'; + } else if (binding.updateSource && binding.mode === _aureliaBinding.bindingMode.twoWay) { + methodToThrottle = 'updateSource'; + } + + binding.throttledMethod = binding[methodToThrottle]; + binding.throttledMethod.originalName = methodToThrottle; + + binding[methodToThrottle] = throttle; + + binding.throttleState = { + delay: delay, + last: 0, + timeoutId: null + }; + }; + + ThrottleBindingBehavior.prototype.unbind = function unbind(binding, source) { + var methodToRestore = binding.throttledMethod.originalName; + binding[methodToRestore] = binding.throttledMethod; + binding.throttledMethod = null; + clearTimeout(binding.throttleState.timeoutId); + binding.throttleState = null; + }; + + return ThrottleBindingBehavior; + }()) || _class); +}); +define('aurelia-templating-resources/signal-binding-behavior',['exports', 'aurelia-binding', './binding-signaler'], function (exports, _aureliaBinding, _bindingSignaler) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.SignalBindingBehavior = undefined; + + + + var _dec, _class; + + var SignalBindingBehavior = exports.SignalBindingBehavior = (_dec = (0, _aureliaBinding.bindingBehavior)('signal'), _dec(_class = function () { + SignalBindingBehavior.inject = function inject() { + return [_bindingSignaler.BindingSignaler]; + }; + + function SignalBindingBehavior(bindingSignaler) { + + + this.signals = bindingSignaler.signals; + } + + SignalBindingBehavior.prototype.bind = function bind(binding, source) { + if (!binding.updateTarget) { + throw new Error('Only property bindings and string interpolation bindings can be signaled. Trigger, delegate and call bindings cannot be signaled.'); + } + if (arguments.length === 3) { + var name = arguments[2]; + var bindings = this.signals[name] || (this.signals[name] = []); + bindings.push(binding); + binding.signalName = name; + } else if (arguments.length > 3) { + var names = Array.prototype.slice.call(arguments, 2); + var i = names.length; + while (i--) { + var _name = names[i]; + var _bindings = this.signals[_name] || (this.signals[_name] = []); + _bindings.push(binding); + } + binding.signalName = names; + } else { + throw new Error('Signal name is required.'); + } + }; + + SignalBindingBehavior.prototype.unbind = function unbind(binding, source) { + var name = binding.signalName; + binding.signalName = null; + if (Array.isArray(name)) { + var names = name; + var i = names.length; + while (i--) { + var n = names[i]; + var bindings = this.signals[n]; + bindings.splice(bindings.indexOf(binding), 1); + } + } else { + var _bindings2 = this.signals[name]; + _bindings2.splice(_bindings2.indexOf(binding), 1); + } + }; + + return SignalBindingBehavior; + }()) || _class); +}); +define('aurelia-templating-resources/show',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-pal', './aurelia-hide-style'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaPal, _aureliaHideStyle) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Show = undefined; + + + + var _dec, _class; + + var Show = exports.Show = (_dec = (0, _aureliaTemplating.customAttribute)('show'), _dec(_class = function () { + Show.inject = function inject() { + return [_aureliaPal.DOM.Element, _aureliaTemplating.Animator, _aureliaDependencyInjection.Optional.of(_aureliaPal.DOM.boundary, true)]; + }; + + function Show(element, animator, domBoundary) { + + + this.element = element; + this.animator = animator; + this.domBoundary = domBoundary; + } + + Show.prototype.created = function created() { + (0, _aureliaHideStyle.injectAureliaHideStyleAtBoundary)(this.domBoundary); + }; + + Show.prototype.valueChanged = function valueChanged(newValue) { + if (newValue) { + this.animator.removeClass(this.element, _aureliaHideStyle.aureliaHideClassName); + } else { + this.animator.addClass(this.element, _aureliaHideStyle.aureliaHideClassName); + } + }; + + Show.prototype.bind = function bind(bindingContext) { + this.valueChanged(this.value); + }; + + return Show; + }()) || _class); +}); +define('aurelia-templating-resources/set-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.SetRepeatStrategy = undefined; + + + + var SetRepeatStrategy = exports.SetRepeatStrategy = function () { + function SetRepeatStrategy() { + + } + + SetRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) { + return observerLocator.getSetObserver(items); + }; + + SetRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) { + var _this = this; + + var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); + if (removePromise instanceof Promise) { + removePromise.then(function () { + return _this._standardProcessItems(repeat, items); + }); + return; + } + this._standardProcessItems(repeat, items); + }; + + SetRepeatStrategy.prototype._standardProcessItems = function _standardProcessItems(repeat, items) { + var index = 0; + var overrideContext = void 0; + + items.forEach(function (value) { + overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, value, index, items.size); + repeat.addView(overrideContext.bindingContext, overrideContext); + ++index; + }); + }; + + SetRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, set, records) { + var value = void 0; + var i = void 0; + var ii = void 0; + var overrideContext = void 0; + var removeIndex = void 0; + var record = void 0; + var rmPromises = []; + var viewOrPromise = void 0; + + for (i = 0, ii = records.length; i < ii; ++i) { + record = records[i]; + value = record.value; + switch (record.type) { + case 'add': + var size = Math.max(set.size - 1, 0); + overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, value, size, set.size); + repeat.insertView(size, overrideContext.bindingContext, overrideContext); + break; + case 'delete': + removeIndex = this._getViewIndexByValue(repeat, value); + viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle); + if (viewOrPromise instanceof Promise) { + rmPromises.push(viewOrPromise); + } + break; + case 'clear': + repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); + break; + default: + continue; + } + } + + if (rmPromises.length > 0) { + Promise.all(rmPromises).then(function () { + (0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0); + }); + } else { + (0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0); + } + }; + + SetRepeatStrategy.prototype._getViewIndexByValue = function _getViewIndexByValue(repeat, value) { + var i = void 0; + var ii = void 0; + var child = void 0; + + for (i = 0, ii = repeat.viewCount(); i < ii; ++i) { + child = repeat.view(i); + if (child.bindingContext[repeat.local] === value) { + return i; + } + } + + return undefined; + }; + + return SetRepeatStrategy; + }(); +}); +define('aurelia-templating-resources/self-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.SelfBindingBehavior = undefined; + + + + var _dec, _class; + + function findOriginalEventTarget(event) { + return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target; + } + + function handleSelfEvent(event) { + var target = findOriginalEventTarget(event); + if (this.target !== target) return; + this.selfEventCallSource(event); + } + + var SelfBindingBehavior = exports.SelfBindingBehavior = (_dec = (0, _aureliaBinding.bindingBehavior)('self'), _dec(_class = function () { + function SelfBindingBehavior() { + + } + + SelfBindingBehavior.prototype.bind = function bind(binding, source) { + if (!binding.callSource || !binding.targetEvent) throw new Error('Self binding behavior only supports event.'); + binding.selfEventCallSource = binding.callSource; + binding.callSource = handleSelfEvent; + }; + + SelfBindingBehavior.prototype.unbind = function unbind(binding, source) { + binding.callSource = binding.selfEventCallSource; + binding.selfEventCallSource = null; + }; + + return SelfBindingBehavior; + }()) || _class); +}); +define('aurelia-templating-resources/sanitize-html',['exports', 'aurelia-binding', 'aurelia-dependency-injection', './html-sanitizer'], function (exports, _aureliaBinding, _aureliaDependencyInjection, _htmlSanitizer) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.SanitizeHTMLValueConverter = undefined; + + + + var _dec, _dec2, _class; + + var SanitizeHTMLValueConverter = exports.SanitizeHTMLValueConverter = (_dec = (0, _aureliaBinding.valueConverter)('sanitizeHTML'), _dec2 = (0, _aureliaDependencyInjection.inject)(_htmlSanitizer.HTMLSanitizer), _dec(_class = _dec2(_class = function () { + function SanitizeHTMLValueConverter(sanitizer) { + + + this.sanitizer = sanitizer; + } + + SanitizeHTMLValueConverter.prototype.toView = function toView(untrustedMarkup) { + if (untrustedMarkup === null || untrustedMarkup === undefined) { + return null; + } + + return this.sanitizer.sanitize(untrustedMarkup); + }; + + return SanitizeHTMLValueConverter; + }()) || _class) || _class); +}); +define('aurelia-templating-resources/replaceable',['exports', 'aurelia-dependency-injection', 'aurelia-templating'], function (exports, _aureliaDependencyInjection, _aureliaTemplating) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Replaceable = undefined; + + + + var _dec, _dec2, _class; + + var Replaceable = exports.Replaceable = (_dec = (0, _aureliaTemplating.customAttribute)('replaceable'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = function () { + function Replaceable(viewFactory, viewSlot) { + + + this.viewFactory = viewFactory; + this.viewSlot = viewSlot; + this.view = null; + } + + Replaceable.prototype.bind = function bind(bindingContext, overrideContext) { + if (this.view === null) { + this.view = this.viewFactory.create(); + this.viewSlot.add(this.view); + } + + this.view.bind(bindingContext, overrideContext); + }; + + Replaceable.prototype.unbind = function unbind() { + this.view.unbind(); + }; + + return Replaceable; + }()) || _class) || _class) || _class); +}); +define('aurelia-templating-resources/repeat',['exports', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-templating', './repeat-strategy-locator', './repeat-utilities', './analyze-view-factory', './abstract-repeater'], function (exports, _aureliaDependencyInjection, _aureliaBinding, _aureliaTemplating, _repeatStrategyLocator, _repeatUtilities, _analyzeViewFactory, _abstractRepeater) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Repeat = undefined; + + function _initDefineProp(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); + } + + + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } + + return desc; + } + + function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.'); + } + + var _dec, _dec2, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4; + + var Repeat = exports.Repeat = (_dec = (0, _aureliaTemplating.customAttribute)('repeat'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.TargetInstruction, _aureliaTemplating.ViewSlot, _aureliaTemplating.ViewResources, _aureliaBinding.ObserverLocator, _repeatStrategyLocator.RepeatStrategyLocator), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = (_class2 = function (_AbstractRepeater) { + _inherits(Repeat, _AbstractRepeater); + + function Repeat(viewFactory, instruction, viewSlot, viewResources, observerLocator, strategyLocator) { + + + var _this = _possibleConstructorReturn(this, _AbstractRepeater.call(this, { + local: 'item', + viewsRequireLifecycle: (0, _analyzeViewFactory.viewsRequireLifecycle)(viewFactory) + })); + + _initDefineProp(_this, 'items', _descriptor, _this); + + _initDefineProp(_this, 'local', _descriptor2, _this); + + _initDefineProp(_this, 'key', _descriptor3, _this); + + _initDefineProp(_this, 'value', _descriptor4, _this); + + _this.viewFactory = viewFactory; + _this.instruction = instruction; + _this.viewSlot = viewSlot; + _this.lookupFunctions = viewResources.lookupFunctions; + _this.observerLocator = observerLocator; + _this.key = 'key'; + _this.value = 'value'; + _this.strategyLocator = strategyLocator; + _this.ignoreMutation = false; + _this.sourceExpression = (0, _repeatUtilities.getItemsSourceExpression)(_this.instruction, 'repeat.for'); + _this.isOneTime = (0, _repeatUtilities.isOneTime)(_this.sourceExpression); + _this.viewsRequireLifecycle = (0, _analyzeViewFactory.viewsRequireLifecycle)(viewFactory); + return _this; + } + + Repeat.prototype.call = function call(context, changes) { + this[context](this.items, changes); + }; + + Repeat.prototype.bind = function bind(bindingContext, overrideContext) { + this.scope = { bindingContext: bindingContext, overrideContext: overrideContext }; + this.matcherBinding = this._captureAndRemoveMatcherBinding(); + this.itemsChanged(); + }; + + Repeat.prototype.unbind = function unbind() { + this.scope = null; + this.items = null; + this.matcherBinding = null; + this.viewSlot.removeAll(true, true); + this._unsubscribeCollection(); + }; + + Repeat.prototype._unsubscribeCollection = function _unsubscribeCollection() { + if (this.collectionObserver) { + this.collectionObserver.unsubscribe(this.callContext, this); + this.collectionObserver = null; + this.callContext = null; + } + }; + + Repeat.prototype.itemsChanged = function itemsChanged() { + var _this2 = this; + + this._unsubscribeCollection(); + + if (!this.scope) { + return; + } + + var items = this.items; + this.strategy = this.strategyLocator.getStrategy(items); + if (!this.strategy) { + throw new Error('Value for \'' + this.sourceExpression + '\' is non-repeatable'); + } + + if (!this.isOneTime && !this._observeInnerCollection()) { + this._observeCollection(); + } + this.ignoreMutation = true; + this.strategy.instanceChanged(this, items); + this.observerLocator.taskQueue.queueMicroTask(function () { + _this2.ignoreMutation = false; + }); + }; + + Repeat.prototype._getInnerCollection = function _getInnerCollection() { + var expression = (0, _repeatUtilities.unwrapExpression)(this.sourceExpression); + if (!expression) { + return null; + } + return expression.evaluate(this.scope, null); + }; + + Repeat.prototype.handleCollectionMutated = function handleCollectionMutated(collection, changes) { + if (!this.collectionObserver) { + return; + } + if (this.ignoreMutation) { + return; + } + this.strategy.instanceMutated(this, collection, changes); + }; + + Repeat.prototype.handleInnerCollectionMutated = function handleInnerCollectionMutated(collection, changes) { + var _this3 = this; + + if (!this.collectionObserver) { + return; + } + + if (this.ignoreMutation) { + return; + } + this.ignoreMutation = true; + var newItems = this.sourceExpression.evaluate(this.scope, this.lookupFunctions); + this.observerLocator.taskQueue.queueMicroTask(function () { + return _this3.ignoreMutation = false; + }); + + if (newItems === this.items) { + this.itemsChanged(); + } else { + this.items = newItems; + } + }; + + Repeat.prototype._observeInnerCollection = function _observeInnerCollection() { + var items = this._getInnerCollection(); + var strategy = this.strategyLocator.getStrategy(items); + if (!strategy) { + return false; + } + this.collectionObserver = strategy.getCollectionObserver(this.observerLocator, items); + if (!this.collectionObserver) { + return false; + } + this.callContext = 'handleInnerCollectionMutated'; + this.collectionObserver.subscribe(this.callContext, this); + return true; + }; + + Repeat.prototype._observeCollection = function _observeCollection() { + var items = this.items; + this.collectionObserver = this.strategy.getCollectionObserver(this.observerLocator, items); + if (this.collectionObserver) { + this.callContext = 'handleCollectionMutated'; + this.collectionObserver.subscribe(this.callContext, this); + } + }; + + Repeat.prototype._captureAndRemoveMatcherBinding = function _captureAndRemoveMatcherBinding() { + if (this.viewFactory.viewFactory) { + var instructions = this.viewFactory.viewFactory.instructions; + var instructionIds = Object.keys(instructions); + for (var i = 0; i < instructionIds.length; i++) { + var expressions = instructions[instructionIds[i]].expressions; + if (expressions) { + for (var ii = 0; i < expressions.length; i++) { + if (expressions[ii].targetProperty === 'matcher') { + var matcherBinding = expressions[ii]; + expressions.splice(ii, 1); + return matcherBinding; + } + } + } + } + } + + return undefined; + }; + + Repeat.prototype.viewCount = function viewCount() { + return this.viewSlot.children.length; + }; + + Repeat.prototype.views = function views() { + return this.viewSlot.children; + }; + + Repeat.prototype.view = function view(index) { + return this.viewSlot.children[index]; + }; + + Repeat.prototype.matcher = function matcher() { + return this.matcherBinding ? this.matcherBinding.sourceExpression.evaluate(this.scope, this.matcherBinding.lookupFunctions) : null; + }; + + Repeat.prototype.addView = function addView(bindingContext, overrideContext) { + var view = this.viewFactory.create(); + view.bind(bindingContext, overrideContext); + this.viewSlot.add(view); + }; + + Repeat.prototype.insertView = function insertView(index, bindingContext, overrideContext) { + var view = this.viewFactory.create(); + view.bind(bindingContext, overrideContext); + this.viewSlot.insert(index, view); + }; + + Repeat.prototype.moveView = function moveView(sourceIndex, targetIndex) { + this.viewSlot.move(sourceIndex, targetIndex); + }; + + Repeat.prototype.removeAllViews = function removeAllViews(returnToCache, skipAnimation) { + return this.viewSlot.removeAll(returnToCache, skipAnimation); + }; + + Repeat.prototype.removeViews = function removeViews(viewsToRemove, returnToCache, skipAnimation) { + return this.viewSlot.removeMany(viewsToRemove, returnToCache, skipAnimation); + }; + + Repeat.prototype.removeView = function removeView(index, returnToCache, skipAnimation) { + return this.viewSlot.removeAt(index, returnToCache, skipAnimation); + }; + + Repeat.prototype.updateBindings = function updateBindings(view) { + var j = view.bindings.length; + while (j--) { + (0, _repeatUtilities.updateOneTimeBinding)(view.bindings[j]); + } + j = view.controllers.length; + while (j--) { + var k = view.controllers[j].boundProperties.length; + while (k--) { + var binding = view.controllers[j].boundProperties[k].binding; + (0, _repeatUtilities.updateOneTimeBinding)(binding); + } + } + }; + + return Repeat; + }(_abstractRepeater.AbstractRepeater), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'items', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'local', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'key', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'value', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + })), _class2)) || _class) || _class) || _class); +}); +define('aurelia-templating-resources/repeat-utilities',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.updateOverrideContexts = updateOverrideContexts; + exports.createFullOverrideContext = createFullOverrideContext; + exports.updateOverrideContext = updateOverrideContext; + exports.getItemsSourceExpression = getItemsSourceExpression; + exports.unwrapExpression = unwrapExpression; + exports.isOneTime = isOneTime; + exports.updateOneTimeBinding = updateOneTimeBinding; + exports.indexOf = indexOf; + + + var oneTime = _aureliaBinding.bindingMode.oneTime; + + function updateOverrideContexts(views, startIndex) { + var length = views.length; + + if (startIndex > 0) { + startIndex = startIndex - 1; + } + + for (; startIndex < length; ++startIndex) { + updateOverrideContext(views[startIndex].overrideContext, startIndex, length); + } + } + + function createFullOverrideContext(repeat, data, index, length, key) { + var bindingContext = {}; + var overrideContext = (0, _aureliaBinding.createOverrideContext)(bindingContext, repeat.scope.overrideContext); + + if (typeof key !== 'undefined') { + bindingContext[repeat.key] = key; + bindingContext[repeat.value] = data; + } else { + bindingContext[repeat.local] = data; + } + updateOverrideContext(overrideContext, index, length); + return overrideContext; + } + + function updateOverrideContext(overrideContext, index, length) { + var first = index === 0; + var last = index === length - 1; + var even = index % 2 === 0; + + overrideContext.$index = index; + overrideContext.$first = first; + overrideContext.$last = last; + overrideContext.$middle = !(first || last); + overrideContext.$odd = !even; + overrideContext.$even = even; + } + + function getItemsSourceExpression(instruction, attrName) { + return instruction.behaviorInstructions.filter(function (bi) { + return bi.originalAttrName === attrName; + })[0].attributes.items.sourceExpression; + } + + function unwrapExpression(expression) { + var unwrapped = false; + while (expression instanceof _aureliaBinding.BindingBehavior) { + expression = expression.expression; + } + while (expression instanceof _aureliaBinding.ValueConverter) { + expression = expression.expression; + unwrapped = true; + } + return unwrapped ? expression : null; + } + + function isOneTime(expression) { + while (expression instanceof _aureliaBinding.BindingBehavior) { + if (expression.name === 'oneTime') { + return true; + } + expression = expression.expression; + } + return false; + } + + function updateOneTimeBinding(binding) { + if (binding.call && binding.mode === oneTime) { + binding.call(_aureliaBinding.sourceContext); + } else if (binding.updateOneTimeBindings) { + binding.updateOneTimeBindings(); + } + } + + function indexOf(array, item, matcher, startIndex) { + if (!matcher) { + return array.indexOf(item); + } + var length = array.length; + for (var index = startIndex || 0; index < length; index++) { + if (matcher(array[index], item)) { + return index; + } + } + return -1; + } +}); +define('aurelia-templating-resources/repeat-strategy-locator',['exports', './null-repeat-strategy', './array-repeat-strategy', './map-repeat-strategy', './set-repeat-strategy', './number-repeat-strategy'], function (exports, _nullRepeatStrategy, _arrayRepeatStrategy, _mapRepeatStrategy, _setRepeatStrategy, _numberRepeatStrategy) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.RepeatStrategyLocator = undefined; + + + + var RepeatStrategyLocator = exports.RepeatStrategyLocator = function () { + function RepeatStrategyLocator() { + + + this.matchers = []; + this.strategies = []; + + this.addStrategy(function (items) { + return items === null || items === undefined; + }, new _nullRepeatStrategy.NullRepeatStrategy()); + this.addStrategy(function (items) { + return items instanceof Array; + }, new _arrayRepeatStrategy.ArrayRepeatStrategy()); + this.addStrategy(function (items) { + return items instanceof Map; + }, new _mapRepeatStrategy.MapRepeatStrategy()); + this.addStrategy(function (items) { + return items instanceof Set; + }, new _setRepeatStrategy.SetRepeatStrategy()); + this.addStrategy(function (items) { + return typeof items === 'number'; + }, new _numberRepeatStrategy.NumberRepeatStrategy()); + } + + RepeatStrategyLocator.prototype.addStrategy = function addStrategy(matcher, strategy) { + this.matchers.push(matcher); + this.strategies.push(strategy); + }; + + RepeatStrategyLocator.prototype.getStrategy = function getStrategy(items) { + var matchers = this.matchers; + + for (var i = 0, ii = matchers.length; i < ii; ++i) { + if (matchers[i](items)) { + return this.strategies[i]; + } + } + + return null; + }; + + return RepeatStrategyLocator; + }(); +}); +define('aurelia-templating-resources/number-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.NumberRepeatStrategy = undefined; + + + + var NumberRepeatStrategy = exports.NumberRepeatStrategy = function () { + function NumberRepeatStrategy() { + + } + + NumberRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver() { + return null; + }; + + NumberRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, value) { + var _this = this; + + var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); + if (removePromise instanceof Promise) { + removePromise.then(function () { + return _this._standardProcessItems(repeat, value); + }); + return; + } + this._standardProcessItems(repeat, value); + }; + + NumberRepeatStrategy.prototype._standardProcessItems = function _standardProcessItems(repeat, value) { + var childrenLength = repeat.viewCount(); + var i = void 0; + var ii = void 0; + var overrideContext = void 0; + var viewsToRemove = void 0; + + value = Math.floor(value); + viewsToRemove = childrenLength - value; + + if (viewsToRemove > 0) { + if (viewsToRemove > childrenLength) { + viewsToRemove = childrenLength; + } + + for (i = 0, ii = viewsToRemove; i < ii; ++i) { + repeat.removeView(childrenLength - (i + 1), true, !repeat.viewsRequireLifecycle); + } + + return; + } + + for (i = childrenLength, ii = value; i < ii; ++i) { + overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, i, i, ii); + repeat.addView(overrideContext.bindingContext, overrideContext); + } + + (0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0); + }; + + return NumberRepeatStrategy; + }(); +}); +define('aurelia-templating-resources/null-repeat-strategy',["exports"], function (exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + + + var NullRepeatStrategy = exports.NullRepeatStrategy = function () { + function NullRepeatStrategy() { + + } + + NullRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) { + repeat.removeAllViews(true); + }; + + NullRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) {}; + + return NullRepeatStrategy; + }(); +}); +define('aurelia-templating-resources/map-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.MapRepeatStrategy = undefined; + + + + var MapRepeatStrategy = exports.MapRepeatStrategy = function () { + function MapRepeatStrategy() { + + } + + MapRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) { + return observerLocator.getMapObserver(items); + }; + + MapRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) { + var _this = this; + + var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); + if (removePromise instanceof Promise) { + removePromise.then(function () { + return _this._standardProcessItems(repeat, items); + }); + return; + } + this._standardProcessItems(repeat, items); + }; + + MapRepeatStrategy.prototype._standardProcessItems = function _standardProcessItems(repeat, items) { + var index = 0; + var overrideContext = void 0; + + items.forEach(function (value, key) { + overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, value, index, items.size, key); + repeat.addView(overrideContext.bindingContext, overrideContext); + ++index; + }); + }; + + MapRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, map, records) { + var key = void 0; + var i = void 0; + var ii = void 0; + var overrideContext = void 0; + var removeIndex = void 0; + var addIndex = void 0; + var record = void 0; + var rmPromises = []; + var viewOrPromise = void 0; + + for (i = 0, ii = records.length; i < ii; ++i) { + record = records[i]; + key = record.key; + switch (record.type) { + case 'update': + removeIndex = this._getViewIndexByKey(repeat, key); + viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle); + if (viewOrPromise instanceof Promise) { + rmPromises.push(viewOrPromise); + } + overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, map.get(key), removeIndex, map.size, key); + repeat.insertView(removeIndex, overrideContext.bindingContext, overrideContext); + break; + case 'add': + addIndex = repeat.viewCount() <= map.size - 1 ? repeat.viewCount() : map.size - 1; + overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, map.get(key), addIndex, map.size, key); + repeat.insertView(map.size - 1, overrideContext.bindingContext, overrideContext); + break; + case 'delete': + if (record.oldValue === undefined) { + return; + } + removeIndex = this._getViewIndexByKey(repeat, key); + viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle); + if (viewOrPromise instanceof Promise) { + rmPromises.push(viewOrPromise); + } + break; + case 'clear': + repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); + break; + default: + continue; + } + } + + if (rmPromises.length > 0) { + Promise.all(rmPromises).then(function () { + (0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0); + }); + } else { + (0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0); + } + }; + + MapRepeatStrategy.prototype._getViewIndexByKey = function _getViewIndexByKey(repeat, key) { + var i = void 0; + var ii = void 0; + var child = void 0; + + for (i = 0, ii = repeat.viewCount(); i < ii; ++i) { + child = repeat.view(i); + if (child.bindingContext[repeat.key] === key) { + return i; + } + } + + return undefined; + }; + + return MapRepeatStrategy; + }(); +}); +define('aurelia-templating-resources/if',['exports', 'aurelia-templating', 'aurelia-dependency-injection', './if-core'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _ifCore) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.If = undefined; + + function _initDefineProp(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); + } + + + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } + + return desc; + } + + function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.'); + } + + var _dec, _dec2, _dec3, _class, _desc, _value, _class2, _descriptor, _descriptor2; + + var If = exports.If = (_dec = (0, _aureliaTemplating.customAttribute)('if'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot), _dec3 = (0, _aureliaTemplating.bindable)({ primaryProperty: true }), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = (_class2 = function (_IfCore) { + _inherits(If, _IfCore); + + function If() { + var _temp, _this, _ret; + + + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return _ret = (_temp = (_this = _possibleConstructorReturn(this, _IfCore.call.apply(_IfCore, [this].concat(args))), _this), _initDefineProp(_this, 'condition', _descriptor, _this), _initDefineProp(_this, 'swapOrder', _descriptor2, _this), _temp), _possibleConstructorReturn(_this, _ret); + } + + If.prototype.bind = function bind(bindingContext, overrideContext) { + _IfCore.prototype.bind.call(this, bindingContext, overrideContext); + if (this.condition) { + this._show(); + } else { + this._hide(); + } + }; + + If.prototype.conditionChanged = function conditionChanged(newValue) { + this._update(newValue); + }; + + If.prototype._update = function _update(show) { + var _this2 = this; + + if (this.animating) { + return; + } + + var promise = void 0; + if (this.elseVm) { + promise = show ? this._swap(this.elseVm, this) : this._swap(this, this.elseVm); + } else { + promise = show ? this._show() : this._hide(); + } + + if (promise) { + this.animating = true; + promise.then(function () { + _this2.animating = false; + if (_this2.condition !== _this2.showing) { + _this2._update(_this2.condition); + } + }); + } + }; + + If.prototype._swap = function _swap(remove, add) { + switch (this.swapOrder) { + case 'before': + return Promise.resolve(add._show()).then(function () { + return remove._hide(); + }); + case 'with': + return Promise.all([remove._hide(), add._show()]); + default: + var promise = remove._hide(); + return promise ? promise.then(function () { + return add._show(); + }) : add._show(); + } + }; + + return If; + }(_ifCore.IfCore), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'condition', [_dec3], { + enumerable: true, + initializer: null + }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'swapOrder', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + })), _class2)) || _class) || _class) || _class); +}); +define('aurelia-templating-resources/if-core',["exports"], function (exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + + + var IfCore = exports.IfCore = function () { + function IfCore(viewFactory, viewSlot) { + + + this.viewFactory = viewFactory; + this.viewSlot = viewSlot; + this.view = null; + this.bindingContext = null; + this.overrideContext = null; + + this.showing = false; + } + + IfCore.prototype.bind = function bind(bindingContext, overrideContext) { + this.bindingContext = bindingContext; + this.overrideContext = overrideContext; + }; + + IfCore.prototype.unbind = function unbind() { + if (this.view === null) { + return; + } + + this.view.unbind(); + + if (!this.viewFactory.isCaching) { + return; + } + + if (this.showing) { + this.showing = false; + this.viewSlot.remove(this.view, true, true); + } else { + this.view.returnToCache(); + } + + this.view = null; + }; + + IfCore.prototype._show = function _show() { + if (this.showing) { + if (!this.view.isBound) { + this.view.bind(this.bindingContext, this.overrideContext); + } + return; + } + + if (this.view === null) { + this.view = this.viewFactory.create(); + } + + if (!this.view.isBound) { + this.view.bind(this.bindingContext, this.overrideContext); + } + + this.showing = true; + return this.viewSlot.add(this.view); + }; + + IfCore.prototype._hide = function _hide() { + var _this = this; + + if (!this.showing) { + return; + } + + this.showing = false; + var removed = this.viewSlot.remove(this.view); + + if (removed instanceof Promise) { + return removed.then(function () { + return _this.view.unbind(); + }); + } + + this.view.unbind(); + }; + + return IfCore; + }(); +}); +define('aurelia-templating-resources/html-sanitizer',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + + + var SCRIPT_REGEX = /)<[^<]*)*<\/script>/gi; + + var HTMLSanitizer = exports.HTMLSanitizer = function () { + function HTMLSanitizer() { + + } + + HTMLSanitizer.prototype.sanitize = function sanitize(input) { + return input.replace(SCRIPT_REGEX, ''); + }; + + return HTMLSanitizer; + }(); +}); +define('aurelia-templating-resources/html-resource-plugin',['exports', 'aurelia-templating', './dynamic-element'], function (exports, _aureliaTemplating, _dynamicElement) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.getElementName = getElementName; + exports.configure = configure; + function getElementName(address) { + return (/([^\/^\?]+)\.html/i.exec(address)[1].toLowerCase() + ); + } + + function configure(config) { + var viewEngine = config.container.get(_aureliaTemplating.ViewEngine); + var loader = config.aurelia.loader; + + viewEngine.addResourcePlugin('.html', { + 'fetch': function fetch(address) { + return loader.loadTemplate(address).then(function (registryEntry) { + var _ref; + + var bindable = registryEntry.template.getAttribute('bindable'); + var elementName = getElementName(address); + + if (bindable) { + bindable = bindable.split(',').map(function (x) { + return x.trim(); + }); + registryEntry.template.removeAttribute('bindable'); + } else { + bindable = []; + } + + return _ref = {}, _ref[elementName] = (0, _dynamicElement._createDynamicElement)(elementName, address, bindable), _ref; + }); + } + }); + } +}); +define('aurelia-templating-resources/hide',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-pal', './aurelia-hide-style'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaPal, _aureliaHideStyle) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Hide = undefined; + + + + var _dec, _class; + + var Hide = exports.Hide = (_dec = (0, _aureliaTemplating.customAttribute)('hide'), _dec(_class = function () { + Hide.inject = function inject() { + return [_aureliaPal.DOM.Element, _aureliaTemplating.Animator, _aureliaDependencyInjection.Optional.of(_aureliaPal.DOM.boundary, true)]; + }; + + function Hide(element, animator, domBoundary) { + + + this.element = element; + this.animator = animator; + this.domBoundary = domBoundary; + } + + Hide.prototype.created = function created() { + (0, _aureliaHideStyle.injectAureliaHideStyleAtBoundary)(this.domBoundary); + }; + + Hide.prototype.valueChanged = function valueChanged(newValue) { + if (newValue) { + this.animator.addClass(this.element, _aureliaHideStyle.aureliaHideClassName); + } else { + this.animator.removeClass(this.element, _aureliaHideStyle.aureliaHideClassName); + } + }; + + Hide.prototype.bind = function bind(bindingContext) { + this.valueChanged(this.value); + }; + + return Hide; + }()) || _class); +}); +define('aurelia-templating-resources/focus',['exports', 'aurelia-templating', 'aurelia-binding', 'aurelia-task-queue', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaBinding, _aureliaTaskQueue, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Focus = undefined; + + + + var _dec, _class; + + var Focus = exports.Focus = (_dec = (0, _aureliaTemplating.customAttribute)('focus', _aureliaBinding.bindingMode.twoWay), _dec(_class = function () { + Focus.inject = function inject() { + return [_aureliaPal.DOM.Element, _aureliaTaskQueue.TaskQueue]; + }; + + function Focus(element, taskQueue) { + + + this.element = element; + this.taskQueue = taskQueue; + this.isAttached = false; + this.needsApply = false; + } + + Focus.prototype.valueChanged = function valueChanged(newValue) { + if (this.isAttached) { + this._apply(); + } else { + this.needsApply = true; + } + }; + + Focus.prototype._apply = function _apply() { + var _this = this; + + if (this.value) { + this.taskQueue.queueMicroTask(function () { + if (_this.value) { + _this.element.focus(); + } + }); + } else { + this.element.blur(); + } + }; + + Focus.prototype.attached = function attached() { + this.isAttached = true; + if (this.needsApply) { + this.needsApply = false; + this._apply(); + } + this.element.addEventListener('focus', this); + this.element.addEventListener('blur', this); + }; + + Focus.prototype.detached = function detached() { + this.isAttached = false; + this.element.removeEventListener('focus', this); + this.element.removeEventListener('blur', this); + }; + + Focus.prototype.handleEvent = function handleEvent(e) { + if (e.type === 'focus') { + this.value = true; + } else if (_aureliaPal.DOM.activeElement !== this.element) { + this.value = false; + } + }; + + return Focus; + }()) || _class); +}); +define('aurelia-templating-resources/else',['exports', 'aurelia-templating', 'aurelia-dependency-injection', './if-core'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _ifCore) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Else = undefined; + + + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + var _dec, _dec2, _class; + + var Else = exports.Else = (_dec = (0, _aureliaTemplating.customAttribute)('else'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = function (_IfCore) { + _inherits(Else, _IfCore); + + function Else(viewFactory, viewSlot) { + + + var _this = _possibleConstructorReturn(this, _IfCore.call(this, viewFactory, viewSlot)); + + _this._registerInIf(); + return _this; + } + + Else.prototype.bind = function bind(bindingContext, overrideContext) { + _IfCore.prototype.bind.call(this, bindingContext, overrideContext); + + if (this.ifVm.condition) { + this._hide(); + } else { + this._show(); + } + }; + + Else.prototype._registerInIf = function _registerInIf() { + var previous = this.viewSlot.anchor.previousSibling; + while (previous && !previous.au) { + previous = previous.previousSibling; + } + if (!previous || !previous.au.if) { + throw new Error("Can't find matching If for Else custom attribute."); + } + this.ifVm = previous.au.if.viewModel; + this.ifVm.elseVm = this; + }; + + return Else; + }(_ifCore.IfCore)) || _class) || _class) || _class); +}); +define('aurelia-templating-resources/dynamic-element',['exports', 'aurelia-templating'], function (exports, _aureliaTemplating) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports._createDynamicElement = _createDynamicElement; + + + + function _createDynamicElement(name, viewUrl, bindableNames) { + var _dec, _dec2, _class; + + var DynamicElement = (_dec = (0, _aureliaTemplating.customElement)(name), _dec2 = (0, _aureliaTemplating.useView)(viewUrl), _dec(_class = _dec2(_class = function () { + function DynamicElement() { + + } + + DynamicElement.prototype.bind = function bind(bindingContext) { + this.$parent = bindingContext; + }; + + return DynamicElement; + }()) || _class) || _class); + + for (var i = 0, ii = bindableNames.length; i < ii; ++i) { + (0, _aureliaTemplating.bindable)(bindableNames[i])(DynamicElement); + } + return DynamicElement; + } +}); +define('aurelia-templating-resources/debounce-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.DebounceBindingBehavior = undefined; + + + + var _dec, _class; + + var unset = {}; + + function debounceCallSource(event) { + var _this = this; + + var state = this.debounceState; + clearTimeout(state.timeoutId); + state.timeoutId = setTimeout(function () { + return _this.debouncedMethod(event); + }, state.delay); + } + + function debounceCall(context, newValue, oldValue) { + var _this2 = this; + + var state = this.debounceState; + clearTimeout(state.timeoutId); + if (context !== state.callContextToDebounce) { + state.oldValue = unset; + this.debouncedMethod(context, newValue, oldValue); + return; + } + if (state.oldValue === unset) { + state.oldValue = oldValue; + } + state.timeoutId = setTimeout(function () { + var _oldValue = state.oldValue; + state.oldValue = unset; + _this2.debouncedMethod(context, newValue, _oldValue); + }, state.delay); + } + + var DebounceBindingBehavior = exports.DebounceBindingBehavior = (_dec = (0, _aureliaBinding.bindingBehavior)('debounce'), _dec(_class = function () { + function DebounceBindingBehavior() { + + } + + DebounceBindingBehavior.prototype.bind = function bind(binding, source) { + var delay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 200; + + var isCallSource = binding.callSource !== undefined; + var methodToDebounce = isCallSource ? 'callSource' : 'call'; + var debouncer = isCallSource ? debounceCallSource : debounceCall; + var mode = binding.mode; + var callContextToDebounce = mode === _aureliaBinding.bindingMode.twoWay || mode === _aureliaBinding.bindingMode.fromView ? _aureliaBinding.targetContext : _aureliaBinding.sourceContext; + + binding.debouncedMethod = binding[methodToDebounce]; + binding.debouncedMethod.originalName = methodToDebounce; + + binding[methodToDebounce] = debouncer; + + binding.debounceState = { + callContextToDebounce: callContextToDebounce, + delay: delay, + timeoutId: 0, + oldValue: unset + }; + }; + + DebounceBindingBehavior.prototype.unbind = function unbind(binding, source) { + var methodToRestore = binding.debouncedMethod.originalName; + binding[methodToRestore] = binding.debouncedMethod; + binding.debouncedMethod = null; + clearTimeout(binding.debounceState.timeoutId); + binding.debounceState = null; + }; + + return DebounceBindingBehavior; + }()) || _class); +}); +define('aurelia-templating-resources/css-resource',['exports', 'aurelia-templating', 'aurelia-loader', 'aurelia-dependency-injection', 'aurelia-path', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaLoader, _aureliaDependencyInjection, _aureliaPath, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports._createCSSResource = _createCSSResource; + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + + + var cssUrlMatcher = /url\((?!['"]data)([^)]+)\)/gi; + + function fixupCSSUrls(address, css) { + if (typeof css !== 'string') { + throw new Error('Failed loading required CSS file: ' + address); + } + return css.replace(cssUrlMatcher, function (match, p1) { + var quote = p1.charAt(0); + if (quote === '\'' || quote === '"') { + p1 = p1.substr(1, p1.length - 2); + } + return 'url(\'' + (0, _aureliaPath.relativeToFile)(p1, address) + '\')'; + }); + } + + var CSSResource = function () { + function CSSResource(address) { + + + this.address = address; + this._scoped = null; + this._global = false; + this._alreadyGloballyInjected = false; + } + + CSSResource.prototype.initialize = function initialize(container, target) { + this._scoped = new target(this); + }; + + CSSResource.prototype.register = function register(registry, name) { + if (name === 'scoped') { + registry.registerViewEngineHooks(this._scoped); + } else { + this._global = true; + } + }; + + CSSResource.prototype.load = function load(container) { + var _this = this; + + return container.get(_aureliaLoader.Loader).loadText(this.address).catch(function (err) { + return null; + }).then(function (text) { + text = fixupCSSUrls(_this.address, text); + _this._scoped.css = text; + if (_this._global) { + _this._alreadyGloballyInjected = true; + _aureliaPal.DOM.injectStyles(text); + } + }); + }; + + return CSSResource; + }(); + + var CSSViewEngineHooks = function () { + function CSSViewEngineHooks(owner) { + + + this.owner = owner; + this.css = null; + } + + CSSViewEngineHooks.prototype.beforeCompile = function beforeCompile(content, resources, instruction) { + if (instruction.targetShadowDOM) { + _aureliaPal.DOM.injectStyles(this.css, content, true); + } else if (_aureliaPal.FEATURE.scopedCSS) { + var styleNode = _aureliaPal.DOM.injectStyles(this.css, content, true); + styleNode.setAttribute('scoped', 'scoped'); + } else if (this._global && !this.owner._alreadyGloballyInjected) { + _aureliaPal.DOM.injectStyles(this.css); + this.owner._alreadyGloballyInjected = true; + } + }; + + return CSSViewEngineHooks; + }(); + + function _createCSSResource(address) { + var _dec, _class; + + var ViewCSS = (_dec = (0, _aureliaTemplating.resource)(new CSSResource(address)), _dec(_class = function (_CSSViewEngineHooks) { + _inherits(ViewCSS, _CSSViewEngineHooks); + + function ViewCSS() { + + + return _possibleConstructorReturn(this, _CSSViewEngineHooks.apply(this, arguments)); + } + + return ViewCSS; + }(CSSViewEngineHooks)) || _class); + + return ViewCSS; + } +}); +define('aurelia-templating-resources/compose',['exports', 'aurelia-dependency-injection', 'aurelia-task-queue', 'aurelia-templating', 'aurelia-pal'], function (exports, _aureliaDependencyInjection, _aureliaTaskQueue, _aureliaTemplating, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Compose = undefined; + + function _initDefineProp(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); + } + + + + function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object['ke' + 'ys'](descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object['define' + 'Property'](target, property, desc); + desc = null; + } + + return desc; + } + + function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.'); + } + + var _dec, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4; + + var Compose = exports.Compose = (_dec = (0, _aureliaTemplating.customElement)('compose'), _dec(_class = (0, _aureliaTemplating.noView)(_class = (_class2 = function () { + Compose.inject = function inject() { + return [_aureliaPal.DOM.Element, _aureliaDependencyInjection.Container, _aureliaTemplating.CompositionEngine, _aureliaTemplating.ViewSlot, _aureliaTemplating.ViewResources, _aureliaTaskQueue.TaskQueue]; + }; + + function Compose(element, container, compositionEngine, viewSlot, viewResources, taskQueue) { + + + _initDefineProp(this, 'model', _descriptor, this); + + _initDefineProp(this, 'view', _descriptor2, this); + + _initDefineProp(this, 'viewModel', _descriptor3, this); + + _initDefineProp(this, 'swapOrder', _descriptor4, this); + + this.element = element; + this.container = container; + this.compositionEngine = compositionEngine; + this.viewSlot = viewSlot; + this.viewResources = viewResources; + this.taskQueue = taskQueue; + this.currentController = null; + this.currentViewModel = null; + this.changes = Object.create(null); + } + + Compose.prototype.created = function created(owningView) { + this.owningView = owningView; + }; + + Compose.prototype.bind = function bind(bindingContext, overrideContext) { + this.bindingContext = bindingContext; + this.overrideContext = overrideContext; + this.changes.view = this.view; + this.changes.viewModel = this.viewModel; + this.changes.model = this.model; + if (!this.pendingTask) { + processChanges(this); + } + }; + + Compose.prototype.unbind = function unbind() { + this.changes = Object.create(null); + this.bindingContext = null; + this.overrideContext = null; + var returnToCache = true; + var skipAnimation = true; + this.viewSlot.removeAll(returnToCache, skipAnimation); + }; + + Compose.prototype.modelChanged = function modelChanged(newValue, oldValue) { + this.changes.model = newValue; + requestUpdate(this); + }; + + Compose.prototype.viewChanged = function viewChanged(newValue, oldValue) { + this.changes.view = newValue; + requestUpdate(this); + }; + + Compose.prototype.viewModelChanged = function viewModelChanged(newValue, oldValue) { + this.changes.viewModel = newValue; + requestUpdate(this); + }; + + return Compose; + }(), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'model', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'view', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'viewModel', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + }), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'swapOrder', [_aureliaTemplating.bindable], { + enumerable: true, + initializer: null + })), _class2)) || _class) || _class); + + + function isEmpty(obj) { + for (var key in obj) { + return false; + } + return true; + } + + function tryActivateViewModel(vm, model) { + if (vm && typeof vm.activate === 'function') { + return Promise.resolve(vm.activate(model)); + } + } + + function createInstruction(composer, instruction) { + return Object.assign(instruction, { + bindingContext: composer.bindingContext, + overrideContext: composer.overrideContext, + owningView: composer.owningView, + container: composer.container, + viewSlot: composer.viewSlot, + viewResources: composer.viewResources, + currentController: composer.currentController, + host: composer.element, + swapOrder: composer.swapOrder + }); + } + + function processChanges(composer) { + var changes = composer.changes; + composer.changes = Object.create(null); + + if (!('view' in changes) && !('viewModel' in changes) && 'model' in changes) { + composer.pendingTask = tryActivateViewModel(composer.currentViewModel, changes.model); + if (!composer.pendingTask) { + return; + } + } else { + var instruction = { + view: composer.view, + viewModel: composer.currentViewModel || composer.viewModel, + model: composer.model + }; + + instruction = Object.assign(instruction, changes); + + instruction = createInstruction(composer, instruction); + composer.pendingTask = composer.compositionEngine.compose(instruction).then(function (controller) { + composer.currentController = controller; + composer.currentViewModel = controller ? controller.viewModel : null; + }); + } + + composer.pendingTask = composer.pendingTask.then(function () { + completeCompositionTask(composer); + }, function (reason) { + completeCompositionTask(composer); + throw reason; + }); + } + + function completeCompositionTask(composer) { + composer.pendingTask = null; + if (!isEmpty(composer.changes)) { + processChanges(composer); + } + } + + function requestUpdate(composer) { + if (composer.pendingTask || composer.updateRequested) { + return; + } + composer.updateRequested = true; + composer.taskQueue.queueMicroTask(function () { + composer.updateRequested = false; + processChanges(composer); + }); + } +}); +define('aurelia-templating-resources/binding-signaler',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.BindingSignaler = undefined; + + + + var BindingSignaler = exports.BindingSignaler = function () { + function BindingSignaler() { + + + this.signals = {}; + } + + BindingSignaler.prototype.signal = function signal(name) { + var bindings = this.signals[name]; + if (!bindings) { + return; + } + var i = bindings.length; + while (i--) { + bindings[i].call(_aureliaBinding.sourceContext); + } + }; + + return BindingSignaler; + }(); +}); +define('aurelia-templating-resources/binding-mode-behaviors',['exports', 'aurelia-binding', 'aurelia-metadata'], function (exports, _aureliaBinding, _aureliaMetadata) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TwoWayBindingBehavior = exports.FromViewBindingBehavior = exports.ToViewBindingBehavior = exports.OneWayBindingBehavior = exports.OneTimeBindingBehavior = undefined; + + + + var _dec, _dec2, _class, _dec3, _dec4, _class2, _dec5, _dec6, _class3, _dec7, _dec8, _class4, _dec9, _dec10, _class5; + + var modeBindingBehavior = { + bind: function bind(binding, source, lookupFunctions) { + binding.originalMode = binding.mode; + binding.mode = this.mode; + }, + unbind: function unbind(binding, source) { + binding.mode = binding.originalMode; + binding.originalMode = null; + } + }; + + var OneTimeBindingBehavior = exports.OneTimeBindingBehavior = (_dec = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec2 = (0, _aureliaBinding.bindingBehavior)('oneTime'), _dec(_class = _dec2(_class = function OneTimeBindingBehavior() { + + + this.mode = _aureliaBinding.bindingMode.oneTime; + }) || _class) || _class); + var OneWayBindingBehavior = exports.OneWayBindingBehavior = (_dec3 = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec4 = (0, _aureliaBinding.bindingBehavior)('oneWay'), _dec3(_class2 = _dec4(_class2 = function OneWayBindingBehavior() { + + + this.mode = _aureliaBinding.bindingMode.toView; + }) || _class2) || _class2); + var ToViewBindingBehavior = exports.ToViewBindingBehavior = (_dec5 = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec6 = (0, _aureliaBinding.bindingBehavior)('toView'), _dec5(_class3 = _dec6(_class3 = function ToViewBindingBehavior() { + + + this.mode = _aureliaBinding.bindingMode.toView; + }) || _class3) || _class3); + var FromViewBindingBehavior = exports.FromViewBindingBehavior = (_dec7 = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec8 = (0, _aureliaBinding.bindingBehavior)('fromView'), _dec7(_class4 = _dec8(_class4 = function FromViewBindingBehavior() { + + + this.mode = _aureliaBinding.bindingMode.fromView; + }) || _class4) || _class4); + var TwoWayBindingBehavior = exports.TwoWayBindingBehavior = (_dec9 = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec10 = (0, _aureliaBinding.bindingBehavior)('twoWay'), _dec9(_class5 = _dec10(_class5 = function TwoWayBindingBehavior() { + + + this.mode = _aureliaBinding.bindingMode.twoWay; + }) || _class5) || _class5); +}); +define('aurelia-templating-resources/aurelia-templating-resources',['exports', './compose', './if', './else', './with', './repeat', './show', './hide', './sanitize-html', './replaceable', './focus', 'aurelia-templating', './css-resource', './html-sanitizer', './attr-binding-behavior', './binding-mode-behaviors', './throttle-binding-behavior', './debounce-binding-behavior', './self-binding-behavior', './signal-binding-behavior', './binding-signaler', './update-trigger-binding-behavior', './abstract-repeater', './repeat-strategy-locator', './html-resource-plugin', './null-repeat-strategy', './array-repeat-strategy', './map-repeat-strategy', './set-repeat-strategy', './number-repeat-strategy', './repeat-utilities', './analyze-view-factory', './aurelia-hide-style'], function (exports, _compose, _if, _else, _with, _repeat, _show, _hide, _sanitizeHtml, _replaceable, _focus, _aureliaTemplating, _cssResource, _htmlSanitizer, _attrBindingBehavior, _bindingModeBehaviors, _throttleBindingBehavior, _debounceBindingBehavior, _selfBindingBehavior, _signalBindingBehavior, _bindingSignaler, _updateTriggerBindingBehavior, _abstractRepeater, _repeatStrategyLocator, _htmlResourcePlugin, _nullRepeatStrategy, _arrayRepeatStrategy, _mapRepeatStrategy, _setRepeatStrategy, _numberRepeatStrategy, _repeatUtilities, _analyzeViewFactory, _aureliaHideStyle) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.viewsRequireLifecycle = exports.unwrapExpression = exports.updateOneTimeBinding = exports.isOneTime = exports.getItemsSourceExpression = exports.updateOverrideContext = exports.createFullOverrideContext = exports.NumberRepeatStrategy = exports.SetRepeatStrategy = exports.MapRepeatStrategy = exports.ArrayRepeatStrategy = exports.NullRepeatStrategy = exports.RepeatStrategyLocator = exports.AbstractRepeater = exports.UpdateTriggerBindingBehavior = exports.BindingSignaler = exports.SignalBindingBehavior = exports.SelfBindingBehavior = exports.DebounceBindingBehavior = exports.ThrottleBindingBehavior = exports.TwoWayBindingBehavior = exports.FromViewBindingBehavior = exports.ToViewBindingBehavior = exports.OneWayBindingBehavior = exports.OneTimeBindingBehavior = exports.AttrBindingBehavior = exports.configure = exports.Focus = exports.Replaceable = exports.SanitizeHTMLValueConverter = exports.HTMLSanitizer = exports.Hide = exports.Show = exports.Repeat = exports.With = exports.Else = exports.If = exports.Compose = undefined; + + + function configure(config) { + (0, _aureliaHideStyle.injectAureliaHideStyleAtHead)(); + + config.globalResources(_compose.Compose, _if.If, _else.Else, _with.With, _repeat.Repeat, _show.Show, _hide.Hide, _replaceable.Replaceable, _focus.Focus, _sanitizeHtml.SanitizeHTMLValueConverter, _bindingModeBehaviors.OneTimeBindingBehavior, _bindingModeBehaviors.OneWayBindingBehavior, _bindingModeBehaviors.ToViewBindingBehavior, _bindingModeBehaviors.FromViewBindingBehavior, _bindingModeBehaviors.TwoWayBindingBehavior, _throttleBindingBehavior.ThrottleBindingBehavior, _debounceBindingBehavior.DebounceBindingBehavior, _selfBindingBehavior.SelfBindingBehavior, _signalBindingBehavior.SignalBindingBehavior, _updateTriggerBindingBehavior.UpdateTriggerBindingBehavior, _attrBindingBehavior.AttrBindingBehavior); + + (0, _htmlResourcePlugin.configure)(config); + + var viewEngine = config.container.get(_aureliaTemplating.ViewEngine); + var styleResourcePlugin = { + fetch: function fetch(address) { + var _ref; + + return _ref = {}, _ref[address] = (0, _cssResource._createCSSResource)(address), _ref; + } + }; + ['.css', '.less', '.sass', '.scss', '.styl'].forEach(function (ext) { + return viewEngine.addResourcePlugin(ext, styleResourcePlugin); + }); + } + + exports.Compose = _compose.Compose; + exports.If = _if.If; + exports.Else = _else.Else; + exports.With = _with.With; + exports.Repeat = _repeat.Repeat; + exports.Show = _show.Show; + exports.Hide = _hide.Hide; + exports.HTMLSanitizer = _htmlSanitizer.HTMLSanitizer; + exports.SanitizeHTMLValueConverter = _sanitizeHtml.SanitizeHTMLValueConverter; + exports.Replaceable = _replaceable.Replaceable; + exports.Focus = _focus.Focus; + exports.configure = configure; + exports.AttrBindingBehavior = _attrBindingBehavior.AttrBindingBehavior; + exports.OneTimeBindingBehavior = _bindingModeBehaviors.OneTimeBindingBehavior; + exports.OneWayBindingBehavior = _bindingModeBehaviors.OneWayBindingBehavior; + exports.ToViewBindingBehavior = _bindingModeBehaviors.ToViewBindingBehavior; + exports.FromViewBindingBehavior = _bindingModeBehaviors.FromViewBindingBehavior; + exports.TwoWayBindingBehavior = _bindingModeBehaviors.TwoWayBindingBehavior; + exports.ThrottleBindingBehavior = _throttleBindingBehavior.ThrottleBindingBehavior; + exports.DebounceBindingBehavior = _debounceBindingBehavior.DebounceBindingBehavior; + exports.SelfBindingBehavior = _selfBindingBehavior.SelfBindingBehavior; + exports.SignalBindingBehavior = _signalBindingBehavior.SignalBindingBehavior; + exports.BindingSignaler = _bindingSignaler.BindingSignaler; + exports.UpdateTriggerBindingBehavior = _updateTriggerBindingBehavior.UpdateTriggerBindingBehavior; + exports.AbstractRepeater = _abstractRepeater.AbstractRepeater; + exports.RepeatStrategyLocator = _repeatStrategyLocator.RepeatStrategyLocator; + exports.NullRepeatStrategy = _nullRepeatStrategy.NullRepeatStrategy; + exports.ArrayRepeatStrategy = _arrayRepeatStrategy.ArrayRepeatStrategy; + exports.MapRepeatStrategy = _mapRepeatStrategy.MapRepeatStrategy; + exports.SetRepeatStrategy = _setRepeatStrategy.SetRepeatStrategy; + exports.NumberRepeatStrategy = _numberRepeatStrategy.NumberRepeatStrategy; + exports.createFullOverrideContext = _repeatUtilities.createFullOverrideContext; + exports.updateOverrideContext = _repeatUtilities.updateOverrideContext; + exports.getItemsSourceExpression = _repeatUtilities.getItemsSourceExpression; + exports.isOneTime = _repeatUtilities.isOneTime; + exports.updateOneTimeBinding = _repeatUtilities.updateOneTimeBinding; + exports.unwrapExpression = _repeatUtilities.unwrapExpression; + exports.viewsRequireLifecycle = _analyzeViewFactory.viewsRequireLifecycle; +}); +;define('aurelia-templating-resources', ['aurelia-templating-resources/aurelia-templating-resources'], function (main) { return main; }); + +define('aurelia-templating-resources/aurelia-hide-style',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.aureliaHideClassName = undefined; + exports.injectAureliaHideStyleAtHead = injectAureliaHideStyleAtHead; + exports.injectAureliaHideStyleAtBoundary = injectAureliaHideStyleAtBoundary; + var aureliaHideClassName = exports.aureliaHideClassName = 'aurelia-hide'; + + var aureliaHideClass = '.' + aureliaHideClassName + ' { display:none !important; }'; + + function injectAureliaHideStyleAtHead() { + _aureliaPal.DOM.injectStyles(aureliaHideClass); + } + + function injectAureliaHideStyleAtBoundary(domBoundary) { + if (_aureliaPal.FEATURE.shadowDOM && domBoundary && !domBoundary.hasAureliaHideStyle) { + domBoundary.hasAureliaHideStyle = true; + _aureliaPal.DOM.injectStyles(aureliaHideClass, domBoundary); + } + } +}); +define('aurelia-templating-resources/attr-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.AttrBindingBehavior = undefined; + + + + var _dec, _class; + + var AttrBindingBehavior = exports.AttrBindingBehavior = (_dec = (0, _aureliaBinding.bindingBehavior)('attr'), _dec(_class = function () { + function AttrBindingBehavior() { + + } + + AttrBindingBehavior.prototype.bind = function bind(binding, source) { + binding.targetObserver = new _aureliaBinding.DataAttributeObserver(binding.target, binding.targetProperty); + }; + + AttrBindingBehavior.prototype.unbind = function unbind(binding, source) {}; + + return AttrBindingBehavior; + }()) || _class); +}); +define('aurelia-templating-resources/array-repeat-strategy',['exports', './repeat-utilities', 'aurelia-binding'], function (exports, _repeatUtilities, _aureliaBinding) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ArrayRepeatStrategy = undefined; + + + + var ArrayRepeatStrategy = exports.ArrayRepeatStrategy = function () { + function ArrayRepeatStrategy() { + + } + + ArrayRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) { + return observerLocator.getArrayObserver(items); + }; + + ArrayRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) { + var _this = this; + + var itemsLength = items.length; + + if (!items || itemsLength === 0) { + repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); + return; + } + + var children = repeat.views(); + var viewsLength = children.length; + + if (viewsLength === 0) { + this._standardProcessInstanceChanged(repeat, items); + return; + } + + if (repeat.viewsRequireLifecycle) { + var childrenSnapshot = children.slice(0); + var itemNameInBindingContext = repeat.local; + var matcher = repeat.matcher(); + + var itemsPreviouslyInViews = []; + var viewsToRemove = []; + + for (var index = 0; index < viewsLength; index++) { + var view = childrenSnapshot[index]; + var oldItem = view.bindingContext[itemNameInBindingContext]; + + if ((0, _repeatUtilities.indexOf)(items, oldItem, matcher) === -1) { + viewsToRemove.push(view); + } else { + itemsPreviouslyInViews.push(oldItem); + } + } + + var updateViews = void 0; + var removePromise = void 0; + + if (itemsPreviouslyInViews.length > 0) { + removePromise = repeat.removeViews(viewsToRemove, true, !repeat.viewsRequireLifecycle); + updateViews = function updateViews() { + for (var _index = 0; _index < itemsLength; _index++) { + var item = items[_index]; + var indexOfView = (0, _repeatUtilities.indexOf)(itemsPreviouslyInViews, item, matcher, _index); + var _view = void 0; + + if (indexOfView === -1) { + var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, items[_index], _index, itemsLength); + repeat.insertView(_index, overrideContext.bindingContext, overrideContext); + + itemsPreviouslyInViews.splice(_index, 0, undefined); + } else if (indexOfView === _index) { + _view = children[indexOfView]; + itemsPreviouslyInViews[indexOfView] = undefined; + } else { + _view = children[indexOfView]; + repeat.moveView(indexOfView, _index); + itemsPreviouslyInViews.splice(indexOfView, 1); + itemsPreviouslyInViews.splice(_index, 0, undefined); + } + + if (_view) { + (0, _repeatUtilities.updateOverrideContext)(_view.overrideContext, _index, itemsLength); + } + } + + _this._inPlaceProcessItems(repeat, items); + }; + } else { + removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); + updateViews = function updateViews() { + return _this._standardProcessInstanceChanged(repeat, items); + }; + } + + if (removePromise instanceof Promise) { + removePromise.then(updateViews); + } else { + updateViews(); + } + } else { + this._inPlaceProcessItems(repeat, items); + } + }; + + ArrayRepeatStrategy.prototype._standardProcessInstanceChanged = function _standardProcessInstanceChanged(repeat, items) { + for (var i = 0, ii = items.length; i < ii; i++) { + var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, items[i], i, ii); + repeat.addView(overrideContext.bindingContext, overrideContext); + } + }; + + ArrayRepeatStrategy.prototype._inPlaceProcessItems = function _inPlaceProcessItems(repeat, items) { + var itemsLength = items.length; + var viewsLength = repeat.viewCount(); + + while (viewsLength > itemsLength) { + viewsLength--; + repeat.removeView(viewsLength, true, !repeat.viewsRequireLifecycle); + } + + var local = repeat.local; + + for (var i = 0; i < viewsLength; i++) { + var view = repeat.view(i); + var last = i === itemsLength - 1; + var middle = i !== 0 && !last; + + if (view.bindingContext[local] === items[i] && view.overrideContext.$middle === middle && view.overrideContext.$last === last) { + continue; + } + + view.bindingContext[local] = items[i]; + view.overrideContext.$middle = middle; + view.overrideContext.$last = last; + repeat.updateBindings(view); + } + + for (var _i = viewsLength; _i < itemsLength; _i++) { + var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, items[_i], _i, itemsLength); + repeat.addView(overrideContext.bindingContext, overrideContext); + } + }; + + ArrayRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, array, splices) { + var _this2 = this; + + if (repeat.__queuedSplices) { + for (var i = 0, ii = splices.length; i < ii; ++i) { + var _splices$i = splices[i], + index = _splices$i.index, + removed = _splices$i.removed, + addedCount = _splices$i.addedCount; + + (0, _aureliaBinding.mergeSplice)(repeat.__queuedSplices, index, removed, addedCount); + } + + repeat.__array = array.slice(0); + return; + } + + var maybePromise = this._runSplices(repeat, array.slice(0), splices); + if (maybePromise instanceof Promise) { + var queuedSplices = repeat.__queuedSplices = []; + + var runQueuedSplices = function runQueuedSplices() { + if (!queuedSplices.length) { + repeat.__queuedSplices = undefined; + repeat.__array = undefined; + return; + } + + var nextPromise = _this2._runSplices(repeat, repeat.__array, queuedSplices) || Promise.resolve(); + queuedSplices = repeat.__queuedSplices = []; + nextPromise.then(runQueuedSplices); + }; + + maybePromise.then(runQueuedSplices); + } + }; + + ArrayRepeatStrategy.prototype._runSplices = function _runSplices(repeat, array, splices) { + var _this3 = this; + + var removeDelta = 0; + var rmPromises = []; + + for (var i = 0, ii = splices.length; i < ii; ++i) { + var splice = splices[i]; + var removed = splice.removed; + + for (var j = 0, jj = removed.length; j < jj; ++j) { + var viewOrPromise = repeat.removeView(splice.index + removeDelta + rmPromises.length, true); + if (viewOrPromise instanceof Promise) { + rmPromises.push(viewOrPromise); + } + } + removeDelta -= splice.addedCount; + } + + if (rmPromises.length > 0) { + return Promise.all(rmPromises).then(function () { + var spliceIndexLow = _this3._handleAddedSplices(repeat, array, splices); + (0, _repeatUtilities.updateOverrideContexts)(repeat.views(), spliceIndexLow); + }); + } + + var spliceIndexLow = this._handleAddedSplices(repeat, array, splices); + (0, _repeatUtilities.updateOverrideContexts)(repeat.views(), spliceIndexLow); + + return undefined; + }; + + ArrayRepeatStrategy.prototype._handleAddedSplices = function _handleAddedSplices(repeat, array, splices) { + var spliceIndex = void 0; + var spliceIndexLow = void 0; + var arrayLength = array.length; + for (var i = 0, ii = splices.length; i < ii; ++i) { + var splice = splices[i]; + var addIndex = spliceIndex = splice.index; + var end = splice.index + splice.addedCount; + + if (typeof spliceIndexLow === 'undefined' || spliceIndexLow === null || spliceIndexLow > splice.index) { + spliceIndexLow = spliceIndex; + } + + for (; addIndex < end; ++addIndex) { + var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, array[addIndex], addIndex, arrayLength); + repeat.insertView(addIndex, overrideContext.bindingContext, overrideContext); + } + } + + return spliceIndexLow; + }; + + return ArrayRepeatStrategy; + }(); +}); +define('aurelia-templating-resources/analyze-view-factory',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.viewsRequireLifecycle = viewsRequireLifecycle; + var lifecycleOptionalBehaviors = exports.lifecycleOptionalBehaviors = ['focus', 'if', 'else', 'repeat', 'show', 'hide', 'with']; + + function behaviorRequiresLifecycle(instruction) { + var t = instruction.type; + var name = t.elementName !== null ? t.elementName : t.attributeName; + return lifecycleOptionalBehaviors.indexOf(name) === -1 && (t.handlesAttached || t.handlesBind || t.handlesCreated || t.handlesDetached || t.handlesUnbind) || t.viewFactory && viewsRequireLifecycle(t.viewFactory) || instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory); + } + + function targetRequiresLifecycle(instruction) { + var behaviors = instruction.behaviorInstructions; + if (behaviors) { + var i = behaviors.length; + while (i--) { + if (behaviorRequiresLifecycle(behaviors[i])) { + return true; + } + } + } + + return instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory); + } + + function viewsRequireLifecycle(viewFactory) { + if ('_viewsRequireLifecycle' in viewFactory) { + return viewFactory._viewsRequireLifecycle; + } + + viewFactory._viewsRequireLifecycle = false; + + if (viewFactory.viewFactory) { + viewFactory._viewsRequireLifecycle = viewsRequireLifecycle(viewFactory.viewFactory); + return viewFactory._viewsRequireLifecycle; + } + + if (viewFactory.template.querySelector('.au-animate')) { + viewFactory._viewsRequireLifecycle = true; + return true; + } + + for (var id in viewFactory.instructions) { + if (targetRequiresLifecycle(viewFactory.instructions[id])) { + viewFactory._viewsRequireLifecycle = true; + return true; + } + } + + viewFactory._viewsRequireLifecycle = false; + return false; + } +}); +define('aurelia-templating-resources/abstract-repeater',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + + + var AbstractRepeater = exports.AbstractRepeater = function () { + function AbstractRepeater(options) { + + + Object.assign(this, { + local: 'items', + viewsRequireLifecycle: true + }, options); + } + + AbstractRepeater.prototype.viewCount = function viewCount() { + throw new Error('subclass must implement `viewCount`'); + }; + + AbstractRepeater.prototype.views = function views() { + throw new Error('subclass must implement `views`'); + }; + + AbstractRepeater.prototype.view = function view(index) { + throw new Error('subclass must implement `view`'); + }; + + AbstractRepeater.prototype.matcher = function matcher() { + throw new Error('subclass must implement `matcher`'); + }; + + AbstractRepeater.prototype.addView = function addView(bindingContext, overrideContext) { + throw new Error('subclass must implement `addView`'); + }; + + AbstractRepeater.prototype.insertView = function insertView(index, bindingContext, overrideContext) { + throw new Error('subclass must implement `insertView`'); + }; + + AbstractRepeater.prototype.moveView = function moveView(sourceIndex, targetIndex) { + throw new Error('subclass must implement `moveView`'); + }; + + AbstractRepeater.prototype.removeAllViews = function removeAllViews(returnToCache, skipAnimation) { + throw new Error('subclass must implement `removeAllViews`'); + }; + + AbstractRepeater.prototype.removeViews = function removeViews(viewsToRemove, returnToCache, skipAnimation) { + throw new Error('subclass must implement `removeView`'); + }; + + AbstractRepeater.prototype.removeView = function removeView(index, returnToCache, skipAnimation) { + throw new Error('subclass must implement `removeView`'); + }; + + AbstractRepeater.prototype.updateBindings = function updateBindings(view) { + throw new Error('subclass must implement `updateBindings`'); + }; + + return AbstractRepeater; + }(); +}); +define('aurelia-templating-binding',['exports', 'aurelia-logging', 'aurelia-binding', 'aurelia-templating'], function (exports, _aureliaLogging, _aureliaBinding, _aureliaTemplating) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TemplatingBindingLanguage = exports.SyntaxInterpreter = exports.ChildInterpolationBinding = exports.InterpolationBinding = exports.InterpolationBindingExpression = exports.AttributeMap = undefined; + exports.configure = configure; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + + + var _class, _temp, _dec, _class2, _class3, _temp2, _class4, _temp3; + + var AttributeMap = exports.AttributeMap = (_temp = _class = function () { + function AttributeMap(svg) { + + + this.elements = Object.create(null); + this.allElements = Object.create(null); + + this.svg = svg; + + this.registerUniversal('accesskey', 'accessKey'); + this.registerUniversal('contenteditable', 'contentEditable'); + this.registerUniversal('tabindex', 'tabIndex'); + this.registerUniversal('textcontent', 'textContent'); + this.registerUniversal('innerhtml', 'innerHTML'); + this.registerUniversal('scrolltop', 'scrollTop'); + this.registerUniversal('scrollleft', 'scrollLeft'); + this.registerUniversal('readonly', 'readOnly'); + + this.register('label', 'for', 'htmlFor'); + + this.register('img', 'usemap', 'useMap'); + + this.register('input', 'maxlength', 'maxLength'); + this.register('input', 'minlength', 'minLength'); + this.register('input', 'formaction', 'formAction'); + this.register('input', 'formenctype', 'formEncType'); + this.register('input', 'formmethod', 'formMethod'); + this.register('input', 'formnovalidate', 'formNoValidate'); + this.register('input', 'formtarget', 'formTarget'); + + this.register('textarea', 'maxlength', 'maxLength'); + + this.register('td', 'rowspan', 'rowSpan'); + this.register('td', 'colspan', 'colSpan'); + this.register('th', 'rowspan', 'rowSpan'); + this.register('th', 'colspan', 'colSpan'); + } + + AttributeMap.prototype.register = function register(elementName, attributeName, propertyName) { + elementName = elementName.toLowerCase(); + attributeName = attributeName.toLowerCase(); + var element = this.elements[elementName] = this.elements[elementName] || Object.create(null); + element[attributeName] = propertyName; + }; + + AttributeMap.prototype.registerUniversal = function registerUniversal(attributeName, propertyName) { + attributeName = attributeName.toLowerCase(); + this.allElements[attributeName] = propertyName; + }; + + AttributeMap.prototype.map = function map(elementName, attributeName) { + if (this.svg.isStandardSvgAttribute(elementName, attributeName)) { + return attributeName; + } + elementName = elementName.toLowerCase(); + attributeName = attributeName.toLowerCase(); + var element = this.elements[elementName]; + if (element !== undefined && attributeName in element) { + return element[attributeName]; + } + if (attributeName in this.allElements) { + return this.allElements[attributeName]; + } + + if (/(?:^data-)|(?:^aria-)|:/.test(attributeName)) { + return attributeName; + } + return (0, _aureliaBinding.camelCase)(attributeName); + }; + + return AttributeMap; + }(), _class.inject = [_aureliaBinding.SVGAnalyzer], _temp); + + var InterpolationBindingExpression = exports.InterpolationBindingExpression = function () { + function InterpolationBindingExpression(observerLocator, targetProperty, parts, mode, lookupFunctions, attribute) { + + + this.observerLocator = observerLocator; + this.targetProperty = targetProperty; + this.parts = parts; + this.mode = mode; + this.lookupFunctions = lookupFunctions; + this.attribute = this.attrToRemove = attribute; + this.discrete = false; + } + + InterpolationBindingExpression.prototype.createBinding = function createBinding(target) { + if (this.parts.length === 3) { + return new ChildInterpolationBinding(target, this.observerLocator, this.parts[1], this.mode, this.lookupFunctions, this.targetProperty, this.parts[0], this.parts[2]); + } + return new InterpolationBinding(this.observerLocator, this.parts, target, this.targetProperty, this.mode, this.lookupFunctions); + }; + + return InterpolationBindingExpression; + }(); + + function validateTarget(target, propertyName) { + if (propertyName === 'style') { + LogManager.getLogger('templating-binding').info('Internet Explorer does not support interpolation in "style" attributes. Use the style attribute\'s alias, "css" instead.'); + } else if (target.parentElement && target.parentElement.nodeName === 'TEXTAREA' && propertyName === 'textContent') { + throw new Error('Interpolation binding cannot be used in the content of a textarea element. Use instead.'); + } + } + + var InterpolationBinding = exports.InterpolationBinding = function () { + function InterpolationBinding(observerLocator, parts, target, targetProperty, mode, lookupFunctions) { + + + validateTarget(target, targetProperty); + this.observerLocator = observerLocator; + this.parts = parts; + this.target = target; + this.targetProperty = targetProperty; + this.targetAccessor = observerLocator.getAccessor(target, targetProperty); + this.mode = mode; + this.lookupFunctions = lookupFunctions; + } + + InterpolationBinding.prototype.interpolate = function interpolate() { + if (this.isBound) { + var value = ''; + var parts = this.parts; + for (var i = 0, ii = parts.length; i < ii; i++) { + value += i % 2 === 0 ? parts[i] : this['childBinding' + i].value; + } + this.targetAccessor.setValue(value, this.target, this.targetProperty); + } + }; + + InterpolationBinding.prototype.updateOneTimeBindings = function updateOneTimeBindings() { + for (var i = 1, ii = this.parts.length; i < ii; i += 2) { + var child = this['childBinding' + i]; + if (child.mode === _aureliaBinding.bindingMode.oneTime) { + child.call(); + } + } + }; + + InterpolationBinding.prototype.bind = function bind(source) { + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.source = source; + + var parts = this.parts; + for (var i = 1, ii = parts.length; i < ii; i += 2) { + var binding = new ChildInterpolationBinding(this, this.observerLocator, parts[i], this.mode, this.lookupFunctions); + binding.bind(source); + this['childBinding' + i] = binding; + } + + this.isBound = true; + this.interpolate(); + }; + + InterpolationBinding.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + this.source = null; + var parts = this.parts; + for (var i = 1, ii = parts.length; i < ii; i += 2) { + var name = 'childBinding' + i; + this[name].unbind(); + } + }; + + return InterpolationBinding; + }(); + + var ChildInterpolationBinding = exports.ChildInterpolationBinding = (_dec = (0, _aureliaBinding.connectable)(), _dec(_class2 = function () { + function ChildInterpolationBinding(target, observerLocator, sourceExpression, mode, lookupFunctions, targetProperty, left, right) { + + + if (target instanceof InterpolationBinding) { + this.parent = target; + } else { + validateTarget(target, targetProperty); + this.target = target; + this.targetProperty = targetProperty; + this.targetAccessor = observerLocator.getAccessor(target, targetProperty); + } + this.observerLocator = observerLocator; + this.sourceExpression = sourceExpression; + this.mode = mode; + this.lookupFunctions = lookupFunctions; + this.left = left; + this.right = right; + } + + ChildInterpolationBinding.prototype.updateTarget = function updateTarget(value) { + value = value === null || value === undefined ? '' : value.toString(); + if (value !== this.value) { + this.value = value; + if (this.parent) { + this.parent.interpolate(); + } else { + this.targetAccessor.setValue(this.left + value + this.right, this.target, this.targetProperty); + } + } + }; + + ChildInterpolationBinding.prototype.call = function call() { + if (!this.isBound) { + return; + } + + this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); + this.updateTarget(this.rawValue); + + if (this.mode !== _aureliaBinding.bindingMode.oneTime) { + this._version++; + this.sourceExpression.connect(this, this.source); + if (this.rawValue instanceof Array) { + this.observeArray(this.rawValue); + } + this.unobserve(false); + } + }; + + ChildInterpolationBinding.prototype.bind = function bind(source) { + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.isBound = true; + this.source = source; + + var sourceExpression = this.sourceExpression; + if (sourceExpression.bind) { + sourceExpression.bind(this, source, this.lookupFunctions); + } + + this.rawValue = sourceExpression.evaluate(source, this.lookupFunctions); + this.updateTarget(this.rawValue); + + if (this.mode === _aureliaBinding.bindingMode.oneWay) { + (0, _aureliaBinding.enqueueBindingConnect)(this); + } + }; + + ChildInterpolationBinding.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + var sourceExpression = this.sourceExpression; + if (sourceExpression.unbind) { + sourceExpression.unbind(this, this.source); + } + this.source = null; + this.value = null; + this.rawValue = null; + this.unobserve(true); + }; + + ChildInterpolationBinding.prototype.connect = function connect(evaluate) { + if (!this.isBound) { + return; + } + if (evaluate) { + this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); + this.updateTarget(this.rawValue); + } + this.sourceExpression.connect(this, this.source); + if (this.rawValue instanceof Array) { + this.observeArray(this.rawValue); + } + }; + + return ChildInterpolationBinding; + }()) || _class2); + var SyntaxInterpreter = exports.SyntaxInterpreter = (_temp2 = _class3 = function () { + function SyntaxInterpreter(parser, observerLocator, eventManager, attributeMap) { + + + this.parser = parser; + this.observerLocator = observerLocator; + this.eventManager = eventManager; + this.attributeMap = attributeMap; + } + + SyntaxInterpreter.prototype.interpret = function interpret(resources, element, info, existingInstruction, context) { + if (info.command in this) { + return this[info.command](resources, element, info, existingInstruction, context); + } + + return this.handleUnknownCommand(resources, element, info, existingInstruction, context); + }; + + SyntaxInterpreter.prototype.handleUnknownCommand = function handleUnknownCommand(resources, element, info, existingInstruction, context) { + LogManager.getLogger('templating-binding').warn('Unknown binding command.', info); + return existingInstruction; + }; + + SyntaxInterpreter.prototype.determineDefaultBindingMode = function determineDefaultBindingMode(element, attrName, context) { + var tagName = element.tagName.toLowerCase(); + + if (tagName === 'input' && (attrName === 'value' || attrName === 'files') && element.type !== 'checkbox' && element.type !== 'radio' || tagName === 'input' && attrName === 'checked' && (element.type === 'checkbox' || element.type === 'radio') || (tagName === 'textarea' || tagName === 'select') && attrName === 'value' || (attrName === 'textcontent' || attrName === 'innerhtml') && element.contentEditable === 'true' || attrName === 'scrolltop' || attrName === 'scrollleft') { + return _aureliaBinding.bindingMode.twoWay; + } + + if (context && attrName in context.attributes && context.attributes[attrName] && context.attributes[attrName].defaultBindingMode >= _aureliaBinding.bindingMode.oneTime) { + return context.attributes[attrName].defaultBindingMode; + } + + return _aureliaBinding.bindingMode.oneWay; + }; + + SyntaxInterpreter.prototype.bind = function bind(resources, element, info, existingInstruction, context) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), info.defaultBindingMode === undefined || info.defaultBindingMode === null ? this.determineDefaultBindingMode(element, info.attrName, context) : info.defaultBindingMode, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype.trigger = function trigger(resources, element, info) { + return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.delegationStrategy.none, true, resources.lookupFunctions); + }; + + SyntaxInterpreter.prototype.capture = function capture(resources, element, info) { + return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.delegationStrategy.capturing, true, resources.lookupFunctions); + }; + + SyntaxInterpreter.prototype.delegate = function delegate(resources, element, info) { + return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.delegationStrategy.bubbling, true, resources.lookupFunctions); + }; + + SyntaxInterpreter.prototype.call = function call(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.CallExpression(this.observerLocator, info.attrName, this.parser.parse(info.attrValue), resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype.options = function options(resources, element, info, existingInstruction, context) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + var attrValue = info.attrValue; + var language = this.language; + var name = null; + var target = ''; + var current = void 0; + var i = void 0; + var ii = void 0; + var inString = false; + var inEscape = false; + var foundName = false; + + for (i = 0, ii = attrValue.length; i < ii; ++i) { + current = attrValue[i]; + + if (current === ';' && !inString) { + if (!foundName) { + name = this._getPrimaryPropertyName(resources, context); + } + info = language.inspectAttribute(resources, '?', name, target.trim()); + language.createAttributeInstruction(resources, element, info, instruction, context); + + if (!instruction.attributes[info.attrName]) { + instruction.attributes[info.attrName] = info.attrValue; + } + + target = ''; + name = null; + } else if (current === ':' && name === null) { + foundName = true; + name = target.trim(); + target = ''; + } else if (current === '\\') { + target += current; + inEscape = true; + continue; + } else { + target += current; + + if (name !== null && inEscape === false && current === '\'') { + inString = !inString; + } + } + + inEscape = false; + } + + if (!foundName) { + name = this._getPrimaryPropertyName(resources, context); + } + + if (name !== null) { + info = language.inspectAttribute(resources, '?', name, target.trim()); + language.createAttributeInstruction(resources, element, info, instruction, context); + + if (!instruction.attributes[info.attrName]) { + instruction.attributes[info.attrName] = info.attrValue; + } + } + + return instruction; + }; + + SyntaxInterpreter.prototype._getPrimaryPropertyName = function _getPrimaryPropertyName(resources, context) { + var type = resources.getAttribute(context.attributeName); + if (type && type.primaryProperty) { + return type.primaryProperty.attribute; + } + return null; + }; + + SyntaxInterpreter.prototype['for'] = function _for(resources, element, info, existingInstruction) { + var parts = void 0; + var keyValue = void 0; + var instruction = void 0; + var attrValue = void 0; + var isDestructuring = void 0; + + attrValue = info.attrValue; + isDestructuring = attrValue.match(/^ *[[].+[\]]/); + parts = isDestructuring ? attrValue.split('of ') : attrValue.split(' of '); + + if (parts.length !== 2) { + throw new Error('Incorrect syntax for "for". The form is: "$local of $items" or "[$key, $value] of $items".'); + } + + instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + if (isDestructuring) { + keyValue = parts[0].replace(/[[\]]/g, '').replace(/,/g, ' ').replace(/\s+/g, ' ').trim().split(' '); + instruction.attributes.key = keyValue[0]; + instruction.attributes.value = keyValue[1]; + } else { + instruction.attributes.local = parts[0]; + } + + instruction.attributes.items = new _aureliaBinding.BindingExpression(this.observerLocator, 'items', this.parser.parse(parts[1]), _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype['two-way'] = function twoWay(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.twoWay, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype['to-view'] = function toView(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.toView, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype['from-view'] = function fromView(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.fromView, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype['one-time'] = function oneTime(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.oneTime, resources.lookupFunctions); + + return instruction; + }; + + return SyntaxInterpreter; + }(), _class3.inject = [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, _aureliaBinding.EventManager, AttributeMap], _temp2); + + + SyntaxInterpreter.prototype['one-way'] = SyntaxInterpreter.prototype['to-view']; + + var info = {}; + + var TemplatingBindingLanguage = exports.TemplatingBindingLanguage = (_temp3 = _class4 = function (_BindingLanguage) { + _inherits(TemplatingBindingLanguage, _BindingLanguage); + + function TemplatingBindingLanguage(parser, observerLocator, syntaxInterpreter, attributeMap) { + + + var _this = _possibleConstructorReturn(this, _BindingLanguage.call(this)); + + _this.parser = parser; + _this.observerLocator = observerLocator; + _this.syntaxInterpreter = syntaxInterpreter; + _this.emptyStringExpression = _this.parser.parse('\'\''); + syntaxInterpreter.language = _this; + _this.attributeMap = attributeMap; + return _this; + } + + TemplatingBindingLanguage.prototype.inspectAttribute = function inspectAttribute(resources, elementName, attrName, attrValue) { + var parts = attrName.split('.'); + + info.defaultBindingMode = null; + + if (parts.length === 2) { + info.attrName = parts[0].trim(); + info.attrValue = attrValue; + info.command = parts[1].trim(); + + if (info.command === 'ref') { + info.expression = new _aureliaBinding.NameExpression(this.parser.parse(attrValue), info.attrName, resources.lookupFunctions); + info.command = null; + info.attrName = 'ref'; + } else { + info.expression = null; + } + } else if (attrName === 'ref') { + info.attrName = attrName; + info.attrValue = attrValue; + info.command = null; + info.expression = new _aureliaBinding.NameExpression(this.parser.parse(attrValue), 'element', resources.lookupFunctions); + } else { + info.attrName = attrName; + info.attrValue = attrValue; + info.command = null; + var interpolationParts = this.parseInterpolation(resources, attrValue); + if (interpolationParts === null) { + info.expression = null; + } else { + info.expression = new InterpolationBindingExpression(this.observerLocator, this.attributeMap.map(elementName, attrName), interpolationParts, _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions, attrName); + } + } + + return info; + }; + + TemplatingBindingLanguage.prototype.createAttributeInstruction = function createAttributeInstruction(resources, element, theInfo, existingInstruction, context) { + var instruction = void 0; + + if (theInfo.expression) { + if (theInfo.attrName === 'ref') { + return theInfo.expression; + } + + instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(theInfo.attrName); + instruction.attributes[theInfo.attrName] = theInfo.expression; + } else if (theInfo.command) { + instruction = this.syntaxInterpreter.interpret(resources, element, theInfo, existingInstruction, context); + } + + return instruction; + }; + + TemplatingBindingLanguage.prototype.inspectTextContent = function inspectTextContent(resources, value) { + var parts = this.parseInterpolation(resources, value); + if (parts === null) { + return null; + } + return new InterpolationBindingExpression(this.observerLocator, 'textContent', parts, _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions, 'textContent'); + }; + + TemplatingBindingLanguage.prototype.parseInterpolation = function parseInterpolation(resources, value) { + var i = value.indexOf('${', 0); + var ii = value.length; + var char = void 0; + var pos = 0; + var open = 0; + var quote = null; + var interpolationStart = void 0; + var parts = void 0; + var partIndex = 0; + + while (i >= 0 && i < ii - 2) { + open = 1; + interpolationStart = i; + i += 2; + + do { + char = value[i]; + i++; + + if (char === "'" || char === '"') { + if (quote === null) { + quote = char; + } else if (quote === char) { + quote = null; + } + continue; + } + + if (char === '\\') { + i++; + continue; + } + + if (quote !== null) { + continue; + } + + if (char === '{') { + open++; + } else if (char === '}') { + open--; + } + } while (open > 0 && i < ii); + + if (open === 0) { + parts = parts || []; + if (value[interpolationStart - 1] === '\\' && value[interpolationStart - 2] !== '\\') { + parts[partIndex] = value.substring(pos, interpolationStart - 1) + value.substring(interpolationStart, i); + partIndex++; + parts[partIndex] = this.emptyStringExpression; + partIndex++; + } else { + parts[partIndex] = value.substring(pos, interpolationStart); + partIndex++; + parts[partIndex] = this.parser.parse(value.substring(interpolationStart + 2, i - 1)); + partIndex++; + } + pos = i; + i = value.indexOf('${', i); + } else { + break; + } + } + + if (partIndex === 0) { + return null; + } + + parts[partIndex] = value.substr(pos); + return parts; + }; + + return TemplatingBindingLanguage; + }(_aureliaTemplating.BindingLanguage), _class4.inject = [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, SyntaxInterpreter, AttributeMap], _temp3); + function configure(config) { + config.container.registerSingleton(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage); + config.container.registerAlias(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage); + } +}); +define('aurelia-task-queue',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TaskQueue = undefined; + + + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + var stackSeparator = '\nEnqueued in TaskQueue by:\n'; + var microStackSeparator = '\nEnqueued in MicroTaskQueue by:\n'; + + function makeRequestFlushFromMutationObserver(flush) { + var observer = _aureliaPal.DOM.createMutationObserver(flush); + var val = 'a'; + var node = _aureliaPal.DOM.createTextNode('a'); + var values = Object.create(null); + values.a = 'b'; + values.b = 'a'; + observer.observe(node, { characterData: true }); + return function requestFlush() { + node.data = val = values[val]; + }; + } + + function makeRequestFlushFromTimer(flush) { + return function requestFlush() { + var timeoutHandle = setTimeout(handleFlushTimer, 0); + + var intervalHandle = setInterval(handleFlushTimer, 50); + function handleFlushTimer() { + clearTimeout(timeoutHandle); + clearInterval(intervalHandle); + flush(); + } + }; + } + + function onError(error, task, longStacks) { + if (longStacks && task.stack && (typeof error === 'undefined' ? 'undefined' : _typeof(error)) === 'object' && error !== null) { + error.stack = filterFlushStack(error.stack) + task.stack; + } + + if ('onError' in task) { + task.onError(error); + } else { + setTimeout(function () { + throw error; + }, 0); + } + } + + var TaskQueue = exports.TaskQueue = function () { + function TaskQueue() { + var _this = this; + + + + this.flushing = false; + this.longStacks = false; + + this.microTaskQueue = []; + this.microTaskQueueCapacity = 1024; + this.taskQueue = []; + + if (_aureliaPal.FEATURE.mutationObserver) { + this.requestFlushMicroTaskQueue = makeRequestFlushFromMutationObserver(function () { + return _this.flushMicroTaskQueue(); + }); + } else { + this.requestFlushMicroTaskQueue = makeRequestFlushFromTimer(function () { + return _this.flushMicroTaskQueue(); + }); + } + + this.requestFlushTaskQueue = makeRequestFlushFromTimer(function () { + return _this.flushTaskQueue(); + }); + } + + TaskQueue.prototype._flushQueue = function _flushQueue(queue, capacity) { + var index = 0; + var task = void 0; + + try { + this.flushing = true; + while (index < queue.length) { + task = queue[index]; + if (this.longStacks) { + this.stack = typeof task.stack === 'string' ? task.stack : undefined; + } + task.call(); + index++; + + if (index > capacity) { + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + + queue.length -= index; + index = 0; + } + } + } catch (error) { + onError(error, task, this.longStacks); + } finally { + this.flushing = false; + } + }; + + TaskQueue.prototype.queueMicroTask = function queueMicroTask(task) { + if (this.microTaskQueue.length < 1) { + this.requestFlushMicroTaskQueue(); + } + + if (this.longStacks) { + task.stack = this.prepareQueueStack(microStackSeparator); + } + + this.microTaskQueue.push(task); + }; + + TaskQueue.prototype.queueTask = function queueTask(task) { + if (this.taskQueue.length < 1) { + this.requestFlushTaskQueue(); + } + + if (this.longStacks) { + task.stack = this.prepareQueueStack(stackSeparator); + } + + this.taskQueue.push(task); + }; + + TaskQueue.prototype.flushTaskQueue = function flushTaskQueue() { + var queue = this.taskQueue; + this.taskQueue = []; + this._flushQueue(queue, Number.MAX_VALUE); + }; + + TaskQueue.prototype.flushMicroTaskQueue = function flushMicroTaskQueue() { + var queue = this.microTaskQueue; + this._flushQueue(queue, this.microTaskQueueCapacity); + queue.length = 0; + }; + + TaskQueue.prototype.prepareQueueStack = function prepareQueueStack(separator) { + var stack = separator + filterQueueStack(captureStack()); + + if (typeof this.stack === 'string') { + stack = filterFlushStack(stack) + this.stack; + } + + return stack; + }; + + return TaskQueue; + }(); + + function captureStack() { + var error = new Error(); + + if (error.stack) { + return error.stack; + } + + try { + throw error; + } catch (e) { + return e.stack; + } + } + + function filterQueueStack(stack) { + return stack.replace(/^[\s\S]*?\bqueue(Micro)?Task\b[^\n]*\n/, ''); + } + + function filterFlushStack(stack) { + var index = stack.lastIndexOf('flushMicroTaskQueue'); + + if (index < 0) { + index = stack.lastIndexOf('flushTaskQueue'); + if (index < 0) { + return stack; + } + } + + index = stack.lastIndexOf('\n', index); + + return index < 0 ? stack : stack.substr(0, index); + } +}); +define('aurelia-router',['exports', 'aurelia-logging', 'aurelia-route-recognizer', 'aurelia-dependency-injection', 'aurelia-history', 'aurelia-event-aggregator'], function (exports, _aureliaLogging, _aureliaRouteRecognizer, _aureliaDependencyInjection, _aureliaHistory, _aureliaEventAggregator) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.AppRouter = exports.PipelineProvider = exports.LoadRouteStep = exports.RouteLoader = exports.ActivateNextStep = exports.DeactivatePreviousStep = exports.CanActivateNextStep = exports.CanDeactivatePreviousStep = exports.Router = exports.BuildNavigationPlanStep = exports.activationStrategy = exports.RouterConfiguration = exports.Pipeline = exports.pipelineStatus = exports.RedirectToRoute = exports.Redirect = exports.NavModel = exports.NavigationInstruction = exports.CommitChangesStep = undefined; + exports._normalizeAbsolutePath = _normalizeAbsolutePath; + exports._createRootedPath = _createRootedPath; + exports._resolveUrl = _resolveUrl; + exports._ensureArrayWithSingleRoutePerConfig = _ensureArrayWithSingleRoutePerConfig; + exports.isNavigationCommand = isNavigationCommand; + exports._buildNavigationPlan = _buildNavigationPlan; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + + + function _normalizeAbsolutePath(path, hasPushState) { + var absolute = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!hasPushState && path[0] !== '#') { + path = '#' + path; + } + + if (hasPushState && absolute) { + path = path.substring(1, path.length); + } + + return path; + } + + function _createRootedPath(fragment, baseUrl, hasPushState, absolute) { + if (isAbsoluteUrl.test(fragment)) { + return fragment; + } + + var path = ''; + + if (baseUrl.length && baseUrl[0] !== '/') { + path += '/'; + } + + path += baseUrl; + + if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') { + path += '/'; + } + + if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') { + path = path.substring(0, path.length - 1); + } + + return _normalizeAbsolutePath(path + fragment, hasPushState, absolute); + } + + function _resolveUrl(fragment, baseUrl, hasPushState) { + if (isRootedPath.test(fragment)) { + return _normalizeAbsolutePath(fragment, hasPushState); + } + + return _createRootedPath(fragment, baseUrl, hasPushState); + } + + function _ensureArrayWithSingleRoutePerConfig(config) { + var routeConfigs = []; + + if (Array.isArray(config.route)) { + for (var i = 0, ii = config.route.length; i < ii; ++i) { + var current = Object.assign({}, config); + current.route = config.route[i]; + routeConfigs.push(current); + } + } else { + routeConfigs.push(Object.assign({}, config)); + } + + return routeConfigs; + } + + var isRootedPath = /^#?\//; + var isAbsoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; + + var CommitChangesStep = exports.CommitChangesStep = function () { + function CommitChangesStep() { + + } + + CommitChangesStep.prototype.run = function run(navigationInstruction, next) { + return navigationInstruction._commitChanges(true).then(function () { + navigationInstruction._updateTitle(); + return next(); + }); + }; + + return CommitChangesStep; + }(); + + var NavigationInstruction = exports.NavigationInstruction = function () { + function NavigationInstruction(init) { + + + this.plan = null; + this.options = {}; + + Object.assign(this, init); + + this.params = this.params || {}; + this.viewPortInstructions = {}; + + var ancestorParams = []; + var current = this; + do { + var currentParams = Object.assign({}, current.params); + if (current.config && current.config.hasChildRouter) { + delete currentParams[current.getWildCardName()]; + } + + ancestorParams.unshift(currentParams); + current = current.parentInstruction; + } while (current); + + var allParams = Object.assign.apply(Object, [{}, this.queryParams].concat(ancestorParams)); + this.lifecycleArgs = [allParams, this.config, this]; + } + + NavigationInstruction.prototype.getAllInstructions = function getAllInstructions() { + var instructions = [this]; + for (var _key in this.viewPortInstructions) { + var childInstruction = this.viewPortInstructions[_key].childNavigationInstruction; + if (childInstruction) { + instructions.push.apply(instructions, childInstruction.getAllInstructions()); + } + } + + return instructions; + }; + + NavigationInstruction.prototype.getAllPreviousInstructions = function getAllPreviousInstructions() { + return this.getAllInstructions().map(function (c) { + return c.previousInstruction; + }).filter(function (c) { + return c; + }); + }; + + NavigationInstruction.prototype.addViewPortInstruction = function addViewPortInstruction(viewPortName, strategy, moduleId, component) { + var config = Object.assign({}, this.lifecycleArgs[1], { currentViewPort: viewPortName }); + var viewportInstruction = this.viewPortInstructions[viewPortName] = { + name: viewPortName, + strategy: strategy, + moduleId: moduleId, + component: component, + childRouter: component.childRouter, + lifecycleArgs: [].concat(this.lifecycleArgs[0], config, this.lifecycleArgs[2]) + }; + + return viewportInstruction; + }; + + NavigationInstruction.prototype.getWildCardName = function getWildCardName() { + var wildcardIndex = this.config.route.lastIndexOf('*'); + return this.config.route.substr(wildcardIndex + 1); + }; + + NavigationInstruction.prototype.getWildcardPath = function getWildcardPath() { + var wildcardName = this.getWildCardName(); + var path = this.params[wildcardName] || ''; + + if (this.queryString) { + path += '?' + this.queryString; + } + + return path; + }; + + NavigationInstruction.prototype.getBaseUrl = function getBaseUrl() { + var _this = this; + + var fragment = decodeURI(this.fragment); + + if (fragment === '') { + var nonEmptyRoute = this.router.routes.find(function (route) { + return route.name === _this.config.name && route.route !== ''; + }); + if (nonEmptyRoute) { + fragment = nonEmptyRoute.route; + } + } + + if (!this.params) { + return encodeURI(fragment); + } + + var wildcardName = this.getWildCardName(); + var path = this.params[wildcardName] || ''; + + if (!path) { + return encodeURI(fragment); + } + + return encodeURI(fragment.substr(0, fragment.lastIndexOf(path))); + }; + + NavigationInstruction.prototype._commitChanges = function _commitChanges(waitToSwap) { + var _this2 = this; + + var router = this.router; + router.currentInstruction = this; + + if (this.previousInstruction) { + this.previousInstruction.config.navModel.isActive = false; + } + + this.config.navModel.isActive = true; + + router.refreshNavigation(); + + var loads = []; + var delaySwaps = []; + + var _loop = function _loop(viewPortName) { + var viewPortInstruction = _this2.viewPortInstructions[viewPortName]; + var viewPort = router.viewPorts[viewPortName]; + + if (!viewPort) { + throw new Error('There was no router-view found in the view for ' + viewPortInstruction.moduleId + '.'); + } + + if (viewPortInstruction.strategy === activationStrategy.replace) { + if (viewPortInstruction.childNavigationInstruction && viewPortInstruction.childNavigationInstruction.parentCatchHandler) { + loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap)); + } else { + if (waitToSwap) { + delaySwaps.push({ viewPort: viewPort, viewPortInstruction: viewPortInstruction }); + } + loads.push(viewPort.process(viewPortInstruction, waitToSwap).then(function (x) { + if (viewPortInstruction.childNavigationInstruction) { + return viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap); + } + })); + } + } else { + if (viewPortInstruction.childNavigationInstruction) { + loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap)); + } + } + }; + + for (var viewPortName in this.viewPortInstructions) { + _loop(viewPortName); + } + + return Promise.all(loads).then(function () { + delaySwaps.forEach(function (x) { + return x.viewPort.swap(x.viewPortInstruction); + }); + return null; + }).then(function () { + return prune(_this2); + }); + }; + + NavigationInstruction.prototype._updateTitle = function _updateTitle() { + var title = this._buildTitle(this.router.titleSeparator); + if (title) { + this.router.history.setTitle(title); + } + }; + + NavigationInstruction.prototype._buildTitle = function _buildTitle() { + var separator = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ' | '; + + var title = ''; + var childTitles = []; + + if (this.config.navModel.title) { + title = this.router.transformTitle(this.config.navModel.title); + } + + for (var viewPortName in this.viewPortInstructions) { + var _viewPortInstruction = this.viewPortInstructions[viewPortName]; + + if (_viewPortInstruction.childNavigationInstruction) { + var childTitle = _viewPortInstruction.childNavigationInstruction._buildTitle(separator); + if (childTitle) { + childTitles.push(childTitle); + } + } + } + + if (childTitles.length) { + title = childTitles.join(separator) + (title ? separator : '') + title; + } + + if (this.router.title) { + title += (title ? separator : '') + this.router.transformTitle(this.router.title); + } + + return title; + }; + + return NavigationInstruction; + }(); + + function prune(instruction) { + instruction.previousInstruction = null; + instruction.plan = null; + } + + var NavModel = exports.NavModel = function () { + function NavModel(router, relativeHref) { + + + this.isActive = false; + this.title = null; + this.href = null; + this.relativeHref = null; + this.settings = {}; + this.config = null; + + this.router = router; + this.relativeHref = relativeHref; + } + + NavModel.prototype.setTitle = function setTitle(title) { + this.title = title; + + if (this.isActive) { + this.router.updateTitle(); + } + }; + + return NavModel; + }(); + + function isNavigationCommand(obj) { + return obj && typeof obj.navigate === 'function'; + } + + var Redirect = exports.Redirect = function () { + function Redirect(url) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + + + this.url = url; + this.options = Object.assign({ trigger: true, replace: true }, options); + this.shouldContinueProcessing = false; + } + + Redirect.prototype.setRouter = function setRouter(router) { + this.router = router; + }; + + Redirect.prototype.navigate = function navigate(appRouter) { + var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter; + navigatingRouter.navigate(this.url, this.options); + }; + + return Redirect; + }(); + + var RedirectToRoute = exports.RedirectToRoute = function () { + function RedirectToRoute(route) { + var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + + + this.route = route; + this.params = params; + this.options = Object.assign({ trigger: true, replace: true }, options); + this.shouldContinueProcessing = false; + } + + RedirectToRoute.prototype.setRouter = function setRouter(router) { + this.router = router; + }; + + RedirectToRoute.prototype.navigate = function navigate(appRouter) { + var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter; + navigatingRouter.navigateToRoute(this.route, this.params, this.options); + }; + + return RedirectToRoute; + }(); + + var pipelineStatus = exports.pipelineStatus = { + completed: 'completed', + canceled: 'canceled', + rejected: 'rejected', + running: 'running' + }; + + var Pipeline = exports.Pipeline = function () { + function Pipeline() { + + + this.steps = []; + } + + Pipeline.prototype.addStep = function addStep(step) { + var run = void 0; + + if (typeof step === 'function') { + run = step; + } else if (typeof step.getSteps === 'function') { + var steps = step.getSteps(); + for (var i = 0, l = steps.length; i < l; i++) { + this.addStep(steps[i]); + } + + return this; + } else { + run = step.run.bind(step); + } + + this.steps.push(run); + + return this; + }; + + Pipeline.prototype.run = function run(instruction) { + var index = -1; + var steps = this.steps; + + function next() { + index++; + + if (index < steps.length) { + var currentStep = steps[index]; + + try { + return currentStep(instruction, next); + } catch (e) { + return next.reject(e); + } + } else { + return next.complete(); + } + } + + next.complete = createCompletionHandler(next, pipelineStatus.completed); + next.cancel = createCompletionHandler(next, pipelineStatus.canceled); + next.reject = createCompletionHandler(next, pipelineStatus.rejected); + + return next(); + }; + + return Pipeline; + }(); + + function createCompletionHandler(next, status) { + return function (output) { + return Promise.resolve({ status: status, output: output, completed: status === pipelineStatus.completed }); + }; + } + + var RouterConfiguration = exports.RouterConfiguration = function () { + function RouterConfiguration() { + + + this.instructions = []; + this.options = {}; + this.pipelineSteps = []; + } + + RouterConfiguration.prototype.addPipelineStep = function addPipelineStep(name, step) { + if (step === null || step === undefined) { + throw new Error('Pipeline step cannot be null or undefined.'); + } + this.pipelineSteps.push({ name: name, step: step }); + return this; + }; + + RouterConfiguration.prototype.addAuthorizeStep = function addAuthorizeStep(step) { + return this.addPipelineStep('authorize', step); + }; + + RouterConfiguration.prototype.addPreActivateStep = function addPreActivateStep(step) { + return this.addPipelineStep('preActivate', step); + }; + + RouterConfiguration.prototype.addPreRenderStep = function addPreRenderStep(step) { + return this.addPipelineStep('preRender', step); + }; + + RouterConfiguration.prototype.addPostRenderStep = function addPostRenderStep(step) { + return this.addPipelineStep('postRender', step); + }; + + RouterConfiguration.prototype.fallbackRoute = function fallbackRoute(fragment) { + this._fallbackRoute = fragment; + return this; + }; + + RouterConfiguration.prototype.map = function map(route) { + if (Array.isArray(route)) { + route.forEach(this.map.bind(this)); + return this; + } + + return this.mapRoute(route); + }; + + RouterConfiguration.prototype.useViewPortDefaults = function useViewPortDefaults(viewPortConfig) { + this.viewPortDefaults = viewPortConfig; + return this; + }; + + RouterConfiguration.prototype.mapRoute = function mapRoute(config) { + this.instructions.push(function (router) { + var routeConfigs = _ensureArrayWithSingleRoutePerConfig(config); + + var navModel = void 0; + for (var i = 0, ii = routeConfigs.length; i < ii; ++i) { + var _routeConfig = routeConfigs[i]; + _routeConfig.settings = _routeConfig.settings || {}; + if (!navModel) { + navModel = router.createNavModel(_routeConfig); + } + + router.addRoute(_routeConfig, navModel); + } + }); + + return this; + }; + + RouterConfiguration.prototype.mapUnknownRoutes = function mapUnknownRoutes(config) { + this.unknownRouteConfig = config; + return this; + }; + + RouterConfiguration.prototype.exportToRouter = function exportToRouter(router) { + var instructions = this.instructions; + for (var i = 0, ii = instructions.length; i < ii; ++i) { + instructions[i](router); + } + + if (this.title) { + router.title = this.title; + } + + if (this.titleSeparator) { + router.titleSeparator = this.titleSeparator; + } + + if (this.unknownRouteConfig) { + router.handleUnknownRoutes(this.unknownRouteConfig); + } + + if (this._fallbackRoute) { + router.fallbackRoute = this._fallbackRoute; + } + + if (this.viewPortDefaults) { + router.useViewPortDefaults(this.viewPortDefaults); + } + + Object.assign(router.options, this.options); + + var pipelineSteps = this.pipelineSteps; + if (pipelineSteps.length) { + if (!router.isRoot) { + throw new Error('Pipeline steps can only be added to the root router'); + } + + var pipelineProvider = router.pipelineProvider; + for (var _i = 0, _ii = pipelineSteps.length; _i < _ii; ++_i) { + var _pipelineSteps$_i = pipelineSteps[_i], + _name = _pipelineSteps$_i.name, + _step = _pipelineSteps$_i.step; + + pipelineProvider.addStep(_name, _step); + } + } + }; + + return RouterConfiguration; + }(); + + var activationStrategy = exports.activationStrategy = { + noChange: 'no-change', + invokeLifecycle: 'invoke-lifecycle', + replace: 'replace' + }; + + var BuildNavigationPlanStep = exports.BuildNavigationPlanStep = function () { + function BuildNavigationPlanStep() { + + } + + BuildNavigationPlanStep.prototype.run = function run(navigationInstruction, next) { + return _buildNavigationPlan(navigationInstruction).then(function (plan) { + if (plan instanceof Redirect) { + return next.cancel(plan); + } + navigationInstruction.plan = plan; + return next(); + }).catch(next.cancel); + }; + + return BuildNavigationPlanStep; + }(); + + function _buildNavigationPlan(instruction, forceLifecycleMinimum) { + var config = instruction.config; + + if ('redirect' in config) { + var _router = instruction.router; + return _router._createNavigationInstruction(config.redirect).then(function (newInstruction) { + var params = {}; + for (var _key2 in newInstruction.params) { + var val = newInstruction.params[_key2]; + if (typeof val === 'string' && val[0] === ':') { + val = val.slice(1); + + if (val in instruction.params) { + params[_key2] = instruction.params[val]; + } + } else { + params[_key2] = newInstruction.params[_key2]; + } + } + var redirectLocation = _router.generate(newInstruction.config.name, params, instruction.options); + + if (instruction.queryString) { + redirectLocation += '?' + instruction.queryString; + } + + return Promise.resolve(new Redirect(redirectLocation)); + }); + } + + var prev = instruction.previousInstruction; + var plan = {}; + var defaults = instruction.router.viewPortDefaults; + + if (prev) { + var newParams = hasDifferentParameterValues(prev, instruction); + var pending = []; + + var _loop2 = function _loop2(viewPortName) { + var prevViewPortInstruction = prev.viewPortInstructions[viewPortName]; + var nextViewPortConfig = viewPortName in config.viewPorts ? config.viewPorts[viewPortName] : prevViewPortInstruction; + if (nextViewPortConfig.moduleId === null && viewPortName in instruction.router.viewPortDefaults) { + nextViewPortConfig = defaults[viewPortName]; + } + + var viewPortPlan = plan[viewPortName] = { + name: viewPortName, + config: nextViewPortConfig, + prevComponent: prevViewPortInstruction.component, + prevModuleId: prevViewPortInstruction.moduleId + }; + + if (prevViewPortInstruction.moduleId !== nextViewPortConfig.moduleId) { + viewPortPlan.strategy = activationStrategy.replace; + } else if ('determineActivationStrategy' in prevViewPortInstruction.component.viewModel) { + var _prevViewPortInstruct; + + viewPortPlan.strategy = (_prevViewPortInstruct = prevViewPortInstruction.component.viewModel).determineActivationStrategy.apply(_prevViewPortInstruct, instruction.lifecycleArgs); + } else if (config.activationStrategy) { + viewPortPlan.strategy = config.activationStrategy; + } else if (newParams || forceLifecycleMinimum) { + viewPortPlan.strategy = activationStrategy.invokeLifecycle; + } else { + viewPortPlan.strategy = activationStrategy.noChange; + } + + if (viewPortPlan.strategy !== activationStrategy.replace && prevViewPortInstruction.childRouter) { + var path = instruction.getWildcardPath(); + var task = prevViewPortInstruction.childRouter._createNavigationInstruction(path, instruction).then(function (childInstruction) { + viewPortPlan.childNavigationInstruction = childInstruction; + + return _buildNavigationPlan(childInstruction, viewPortPlan.strategy === activationStrategy.invokeLifecycle).then(function (childPlan) { + if (childPlan instanceof Redirect) { + return Promise.reject(childPlan); + } + childInstruction.plan = childPlan; + }); + }); + + pending.push(task); + } + }; + + for (var viewPortName in prev.viewPortInstructions) { + _loop2(viewPortName); + } + + return Promise.all(pending).then(function () { + return plan; + }); + } + + for (var viewPortName in config.viewPorts) { + var viewPortConfig = config.viewPorts[viewPortName]; + if (viewPortConfig.moduleId === null && viewPortName in instruction.router.viewPortDefaults) { + viewPortConfig = defaults[viewPortName]; + } + plan[viewPortName] = { + name: viewPortName, + strategy: activationStrategy.replace, + config: viewPortConfig + }; + } + + return Promise.resolve(plan); + } + + function hasDifferentParameterValues(prev, next) { + var prevParams = prev.params; + var nextParams = next.params; + var nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null; + + for (var _key3 in nextParams) { + if (_key3 === nextWildCardName) { + continue; + } + + if (prevParams[_key3] !== nextParams[_key3]) { + return true; + } + } + + for (var _key4 in prevParams) { + if (_key4 === nextWildCardName) { + continue; + } + + if (prevParams[_key4] !== nextParams[_key4]) { + return true; + } + } + + if (!next.options.compareQueryParams) { + return false; + } + + var prevQueryParams = prev.queryParams; + var nextQueryParams = next.queryParams; + for (var _key5 in nextQueryParams) { + if (prevQueryParams[_key5] !== nextQueryParams[_key5]) { + return true; + } + } + + for (var _key6 in prevQueryParams) { + if (prevQueryParams[_key6] !== nextQueryParams[_key6]) { + return true; + } + } + + return false; + } + + var Router = exports.Router = function () { + function Router(container, history) { + var _this3 = this; + + + + this.parent = null; + this.options = {}; + this.viewPortDefaults = {}; + + this.transformTitle = function (title) { + if (_this3.parent) { + return _this3.parent.transformTitle(title); + } + return title; + }; + + this.container = container; + this.history = history; + this.reset(); + } + + Router.prototype.reset = function reset() { + var _this4 = this; + + this.viewPorts = {}; + this.routes = []; + this.baseUrl = ''; + this.isConfigured = false; + this.isNavigating = false; + this.isExplicitNavigation = false; + this.isExplicitNavigationBack = false; + this.isNavigatingFirst = false; + this.isNavigatingNew = false; + this.isNavigatingRefresh = false; + this.isNavigatingForward = false; + this.isNavigatingBack = false; + this.navigation = []; + this.currentInstruction = null; + this.viewPortDefaults = {}; + this._fallbackOrder = 100; + this._recognizer = new _aureliaRouteRecognizer.RouteRecognizer(); + this._childRecognizer = new _aureliaRouteRecognizer.RouteRecognizer(); + this._configuredPromise = new Promise(function (resolve) { + _this4._resolveConfiguredPromise = resolve; + }); + }; + + Router.prototype.registerViewPort = function registerViewPort(viewPort, name) { + name = name || 'default'; + this.viewPorts[name] = viewPort; + }; + + Router.prototype.ensureConfigured = function ensureConfigured() { + return this._configuredPromise; + }; + + Router.prototype.configure = function configure(callbackOrConfig) { + var _this5 = this; + + this.isConfigured = true; + + var result = callbackOrConfig; + var config = void 0; + if (typeof callbackOrConfig === 'function') { + config = new RouterConfiguration(); + result = callbackOrConfig(config); + } + + return Promise.resolve(result).then(function (c) { + if (c && c.exportToRouter) { + config = c; + } + + config.exportToRouter(_this5); + _this5.isConfigured = true; + _this5._resolveConfiguredPromise(); + }); + }; + + Router.prototype.navigate = function navigate(fragment, options) { + if (!this.isConfigured && this.parent) { + return this.parent.navigate(fragment, options); + } + + this.isExplicitNavigation = true; + return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options); + }; + + Router.prototype.navigateToRoute = function navigateToRoute(route, params, options) { + var path = this.generate(route, params); + return this.navigate(path, options); + }; + + Router.prototype.navigateBack = function navigateBack() { + this.isExplicitNavigationBack = true; + this.history.navigateBack(); + }; + + Router.prototype.createChild = function createChild(container) { + var childRouter = new Router(container || this.container.createChild(), this.history); + childRouter.parent = this; + return childRouter; + }; + + Router.prototype.generate = function generate(name, params) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + var hasRoute = this._recognizer.hasRoute(name); + if ((!this.isConfigured || !hasRoute) && this.parent) { + return this.parent.generate(name, params, options); + } + + if (!hasRoute) { + throw new Error('A route with name \'' + name + '\' could not be found. Check that `name: \'' + name + '\'` was specified in the route\'s config.'); + } + + var path = this._recognizer.generate(name, params); + var rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute); + return options.absolute ? '' + this.history.getAbsoluteRoot() + rootedPath : rootedPath; + }; + + Router.prototype.createNavModel = function createNavModel(config) { + var navModel = new NavModel(this, 'href' in config ? config.href : config.route); + navModel.title = config.title; + navModel.order = config.nav; + navModel.href = config.href; + navModel.settings = config.settings; + navModel.config = config; + + return navModel; + }; + + Router.prototype.addRoute = function addRoute(config, navModel) { + if (Array.isArray(config.route)) { + var routeConfigs = _ensureArrayWithSingleRoutePerConfig(config); + routeConfigs.forEach(this.addRoute.bind(this)); + return; + } + + validateRouteConfig(config, this.routes); + + if (!('viewPorts' in config) && !config.navigationStrategy) { + config.viewPorts = { + 'default': { + moduleId: config.moduleId, + view: config.view + } + }; + } + + if (!navModel) { + navModel = this.createNavModel(config); + } + + this.routes.push(config); + + var path = config.route; + if (path.charAt(0) === '/') { + path = path.substr(1); + } + var caseSensitive = config.caseSensitive === true; + var state = this._recognizer.add({ path: path, handler: config, caseSensitive: caseSensitive }); + + if (path) { + var _settings = config.settings; + delete config.settings; + var withChild = JSON.parse(JSON.stringify(config)); + config.settings = _settings; + withChild.route = path + '/*childRoute'; + withChild.hasChildRouter = true; + this._childRecognizer.add({ + path: withChild.route, + handler: withChild, + caseSensitive: caseSensitive + }); + + withChild.navModel = navModel; + withChild.settings = config.settings; + withChild.navigationStrategy = config.navigationStrategy; + } + + config.navModel = navModel; + + if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) { + if (!navModel.href && navModel.href !== '' && (state.types.dynamics || state.types.stars)) { + throw new Error('Invalid route config for "' + config.route + '" : dynamic routes must specify an "href:" to be included in the navigation model.'); + } + + if (typeof navModel.order !== 'number') { + navModel.order = ++this._fallbackOrder; + } + + this.navigation.push(navModel); + this.navigation = this.navigation.sort(function (a, b) { + return a.order - b.order; + }); + } + }; + + Router.prototype.hasRoute = function hasRoute(name) { + return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name)); + }; + + Router.prototype.hasOwnRoute = function hasOwnRoute(name) { + return this._recognizer.hasRoute(name); + }; + + Router.prototype.handleUnknownRoutes = function handleUnknownRoutes(config) { + var _this6 = this; + + if (!config) { + throw new Error('Invalid unknown route handler'); + } + + this.catchAllHandler = function (instruction) { + return _this6._createRouteConfig(config, instruction).then(function (c) { + instruction.config = c; + return instruction; + }); + }; + }; + + Router.prototype.updateTitle = function updateTitle() { + if (this.parent) { + return this.parent.updateTitle(); + } + + if (this.currentInstruction) { + this.currentInstruction._updateTitle(); + } + return undefined; + }; + + Router.prototype.refreshNavigation = function refreshNavigation() { + var nav = this.navigation; + + for (var i = 0, length = nav.length; i < length; i++) { + var _current = nav[i]; + if (!_current.config.href) { + _current.href = _createRootedPath(_current.relativeHref, this.baseUrl, this.history._hasPushState); + } else { + _current.href = _normalizeAbsolutePath(_current.config.href, this.history._hasPushState); + } + } + }; + + Router.prototype.useViewPortDefaults = function useViewPortDefaults(viewPortDefaults) { + for (var viewPortName in viewPortDefaults) { + var viewPortConfig = viewPortDefaults[viewPortName]; + this.viewPortDefaults[viewPortName] = { + moduleId: viewPortConfig.moduleId + }; + } + }; + + Router.prototype._refreshBaseUrl = function _refreshBaseUrl() { + if (this.parent) { + this.baseUrl = generateBaseUrl(this.parent, this.parent.currentInstruction); + } + }; + + Router.prototype._createNavigationInstruction = function _createNavigationInstruction() { + var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var parentInstruction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + + var fragment = url; + var queryString = ''; + + var queryIndex = url.indexOf('?'); + if (queryIndex !== -1) { + fragment = url.substr(0, queryIndex); + queryString = url.substr(queryIndex + 1); + } + + var results = this._recognizer.recognize(url); + if (!results || !results.length) { + results = this._childRecognizer.recognize(url); + } + + var instructionInit = { + fragment: fragment, + queryString: queryString, + config: null, + parentInstruction: parentInstruction, + previousInstruction: this.currentInstruction, + router: this, + options: { + compareQueryParams: this.options.compareQueryParams + } + }; + + var result = void 0; + + if (results && results.length) { + var first = results[0]; + var _instruction = new NavigationInstruction(Object.assign({}, instructionInit, { + params: first.params, + queryParams: first.queryParams || results.queryParams, + config: first.config || first.handler + })); + + if (typeof first.handler === 'function') { + result = evaluateNavigationStrategy(_instruction, first.handler, first); + } else if (first.handler && typeof first.handler.navigationStrategy === 'function') { + result = evaluateNavigationStrategy(_instruction, first.handler.navigationStrategy, first.handler); + } else { + result = Promise.resolve(_instruction); + } + } else if (this.catchAllHandler) { + var _instruction2 = new NavigationInstruction(Object.assign({}, instructionInit, { + params: { path: fragment }, + queryParams: results ? results.queryParams : {}, + config: null })); + + result = evaluateNavigationStrategy(_instruction2, this.catchAllHandler); + } else if (this.parent) { + var _router2 = this._parentCatchAllHandler(this.parent); + + if (_router2) { + var newParentInstruction = this._findParentInstructionFromRouter(_router2, parentInstruction); + + var _instruction3 = new NavigationInstruction(Object.assign({}, instructionInit, { + params: { path: fragment }, + queryParams: results ? results.queryParams : {}, + router: _router2, + parentInstruction: newParentInstruction, + parentCatchHandler: true, + config: null })); + + result = evaluateNavigationStrategy(_instruction3, _router2.catchAllHandler); + } + } + + if (result && parentInstruction) { + this.baseUrl = generateBaseUrl(this.parent, parentInstruction); + } + + return result || Promise.reject(new Error('Route not found: ' + url)); + }; + + Router.prototype._findParentInstructionFromRouter = function _findParentInstructionFromRouter(router, instruction) { + if (instruction.router === router) { + instruction.fragment = router.baseUrl; + return instruction; + } else if (instruction.parentInstruction) { + return this._findParentInstructionFromRouter(router, instruction.parentInstruction); + } + return undefined; + }; + + Router.prototype._parentCatchAllHandler = function _parentCatchAllHandler(router) { + if (router.catchAllHandler) { + return router; + } else if (router.parent) { + return this._parentCatchAllHandler(router.parent); + } + return false; + }; + + Router.prototype._createRouteConfig = function _createRouteConfig(config, instruction) { + var _this7 = this; + + return Promise.resolve(config).then(function (c) { + if (typeof c === 'string') { + return { moduleId: c }; + } else if (typeof c === 'function') { + return c(instruction); + } + + return c; + }).then(function (c) { + return typeof c === 'string' ? { moduleId: c } : c; + }).then(function (c) { + c.route = instruction.params.path; + validateRouteConfig(c, _this7.routes); + + if (!c.navModel) { + c.navModel = _this7.createNavModel(c); + } + + return c; + }); + }; + + _createClass(Router, [{ + key: 'isRoot', + get: function get() { + return !this.parent; + } + }]); + + return Router; + }(); + + function generateBaseUrl(router, instruction) { + return '' + (router.baseUrl || '') + (instruction.getBaseUrl() || ''); + } + + function validateRouteConfig(config, routes) { + if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) !== 'object') { + throw new Error('Invalid Route Config'); + } + + if (typeof config.route !== 'string') { + var _name2 = config.name || '(no name)'; + throw new Error('Invalid Route Config for "' + _name2 + '": You must specify a "route:" pattern.'); + } + + if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) { + throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".'); + } + } + + function evaluateNavigationStrategy(instruction, evaluator, context) { + return Promise.resolve(evaluator.call(context, instruction)).then(function () { + if (!('viewPorts' in instruction.config)) { + instruction.config.viewPorts = { + 'default': { + moduleId: instruction.config.moduleId + } + }; + } + + return instruction; + }); + } + + var CanDeactivatePreviousStep = exports.CanDeactivatePreviousStep = function () { + function CanDeactivatePreviousStep() { + + } + + CanDeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { + return processDeactivatable(navigationInstruction, 'canDeactivate', next); + }; + + return CanDeactivatePreviousStep; + }(); + + var CanActivateNextStep = exports.CanActivateNextStep = function () { + function CanActivateNextStep() { + + } + + CanActivateNextStep.prototype.run = function run(navigationInstruction, next) { + return processActivatable(navigationInstruction, 'canActivate', next); + }; + + return CanActivateNextStep; + }(); + + var DeactivatePreviousStep = exports.DeactivatePreviousStep = function () { + function DeactivatePreviousStep() { + + } + + DeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { + return processDeactivatable(navigationInstruction, 'deactivate', next, true); + }; + + return DeactivatePreviousStep; + }(); + + var ActivateNextStep = exports.ActivateNextStep = function () { + function ActivateNextStep() { + + } + + ActivateNextStep.prototype.run = function run(navigationInstruction, next) { + return processActivatable(navigationInstruction, 'activate', next, true); + }; + + return ActivateNextStep; + }(); + + function processDeactivatable(navigationInstruction, callbackName, next, ignoreResult) { + var plan = navigationInstruction.plan; + var infos = findDeactivatable(plan, callbackName); + var i = infos.length; + + function inspect(val) { + if (ignoreResult || shouldContinue(val)) { + return iterate(); + } + + return next.cancel(val); + } + + function iterate() { + if (i--) { + try { + var viewModel = infos[i]; + var _result = viewModel[callbackName](navigationInstruction); + return processPotential(_result, inspect, next.cancel); + } catch (error) { + return next.cancel(error); + } + } + + return next(); + } + + return iterate(); + } + + function findDeactivatable(plan, callbackName) { + var list = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + + for (var viewPortName in plan) { + var _viewPortPlan = plan[viewPortName]; + var prevComponent = _viewPortPlan.prevComponent; + + if ((_viewPortPlan.strategy === activationStrategy.invokeLifecycle || _viewPortPlan.strategy === activationStrategy.replace) && prevComponent) { + var viewModel = prevComponent.viewModel; + + if (callbackName in viewModel) { + list.push(viewModel); + } + } + + if (_viewPortPlan.strategy === activationStrategy.replace && prevComponent) { + addPreviousDeactivatable(prevComponent, callbackName, list); + } else if (_viewPortPlan.childNavigationInstruction) { + findDeactivatable(_viewPortPlan.childNavigationInstruction.plan, callbackName, list); + } + } + + return list; + } + + function addPreviousDeactivatable(component, callbackName, list) { + var childRouter = component.childRouter; + + if (childRouter && childRouter.currentInstruction) { + var viewPortInstructions = childRouter.currentInstruction.viewPortInstructions; + + for (var viewPortName in viewPortInstructions) { + var _viewPortInstruction2 = viewPortInstructions[viewPortName]; + var prevComponent = _viewPortInstruction2.component; + var prevViewModel = prevComponent.viewModel; + + if (callbackName in prevViewModel) { + list.push(prevViewModel); + } + + addPreviousDeactivatable(prevComponent, callbackName, list); + } + } + } + + function processActivatable(navigationInstruction, callbackName, next, ignoreResult) { + var infos = findActivatable(navigationInstruction, callbackName); + var length = infos.length; + var i = -1; + + function inspect(val, router) { + if (ignoreResult || shouldContinue(val, router)) { + return iterate(); + } + + return next.cancel(val); + } + + function iterate() { + i++; + + if (i < length) { + try { + var _current2$viewModel; + + var _current2 = infos[i]; + var _result2 = (_current2$viewModel = _current2.viewModel)[callbackName].apply(_current2$viewModel, _current2.lifecycleArgs); + return processPotential(_result2, function (val) { + return inspect(val, _current2.router); + }, next.cancel); + } catch (error) { + return next.cancel(error); + } + } + + return next(); + } + + return iterate(); + } + + function findActivatable(navigationInstruction, callbackName) { + var list = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var router = arguments[3]; + + var plan = navigationInstruction.plan; + + Object.keys(plan).filter(function (viewPortName) { + var viewPortPlan = plan[viewPortName]; + var viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName]; + var viewModel = viewPortInstruction.component.viewModel; + + if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && callbackName in viewModel) { + list.push({ + viewModel: viewModel, + lifecycleArgs: viewPortInstruction.lifecycleArgs, + router: router + }); + } + + if (viewPortPlan.childNavigationInstruction) { + findActivatable(viewPortPlan.childNavigationInstruction, callbackName, list, viewPortInstruction.component.childRouter || router); + } + }); + + return list; + } + + function shouldContinue(output, router) { + if (output instanceof Error) { + return false; + } + + if (isNavigationCommand(output)) { + if (typeof output.setRouter === 'function') { + output.setRouter(router); + } + + return !!output.shouldContinueProcessing; + } + + if (output === undefined) { + return true; + } + + return output; + } + + var SafeSubscription = function () { + function SafeSubscription(subscriptionFunc) { + + + this._subscribed = true; + this._subscription = subscriptionFunc(this); + + if (!this._subscribed) this.unsubscribe(); + } + + SafeSubscription.prototype.unsubscribe = function unsubscribe() { + if (this._subscribed && this._subscription) this._subscription.unsubscribe(); + + this._subscribed = false; + }; + + _createClass(SafeSubscription, [{ + key: 'subscribed', + get: function get() { + return this._subscribed; + } + }]); + + return SafeSubscription; + }(); + + function processPotential(obj, resolve, reject) { + if (obj && typeof obj.then === 'function') { + return Promise.resolve(obj).then(resolve).catch(reject); + } + + if (obj && typeof obj.subscribe === 'function') { + var obs = obj; + return new SafeSubscription(function (sub) { + return obs.subscribe({ + next: function next() { + if (sub.subscribed) { + sub.unsubscribe(); + resolve(obj); + } + }, + error: function error(_error) { + if (sub.subscribed) { + sub.unsubscribe(); + reject(_error); + } + }, + complete: function complete() { + if (sub.subscribed) { + sub.unsubscribe(); + resolve(obj); + } + } + }); + }); + } + + try { + return resolve(obj); + } catch (error) { + return reject(error); + } + } + + var RouteLoader = exports.RouteLoader = function () { + function RouteLoader() { + + } + + RouteLoader.prototype.loadRoute = function loadRoute(router, config, navigationInstruction) { + throw Error('Route loaders must implement "loadRoute(router, config, navigationInstruction)".'); + }; + + return RouteLoader; + }(); + + var LoadRouteStep = exports.LoadRouteStep = function () { + LoadRouteStep.inject = function inject() { + return [RouteLoader]; + }; + + function LoadRouteStep(routeLoader) { + + + this.routeLoader = routeLoader; + } + + LoadRouteStep.prototype.run = function run(navigationInstruction, next) { + return loadNewRoute(this.routeLoader, navigationInstruction).then(next).catch(next.cancel); + }; + + return LoadRouteStep; + }(); + + function loadNewRoute(routeLoader, navigationInstruction) { + var toLoad = determineWhatToLoad(navigationInstruction); + var loadPromises = toLoad.map(function (current) { + return loadRoute(routeLoader, current.navigationInstruction, current.viewPortPlan); + }); + + return Promise.all(loadPromises); + } + + function determineWhatToLoad(navigationInstruction) { + var toLoad = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + var plan = navigationInstruction.plan; + + for (var viewPortName in plan) { + var _viewPortPlan2 = plan[viewPortName]; + + if (_viewPortPlan2.strategy === activationStrategy.replace) { + toLoad.push({ viewPortPlan: _viewPortPlan2, navigationInstruction: navigationInstruction }); + + if (_viewPortPlan2.childNavigationInstruction) { + determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad); + } + } else { + var _viewPortInstruction3 = navigationInstruction.addViewPortInstruction(viewPortName, _viewPortPlan2.strategy, _viewPortPlan2.prevModuleId, _viewPortPlan2.prevComponent); + + if (_viewPortPlan2.childNavigationInstruction) { + _viewPortInstruction3.childNavigationInstruction = _viewPortPlan2.childNavigationInstruction; + determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad); + } + } + } + + return toLoad; + } + + function loadRoute(routeLoader, navigationInstruction, viewPortPlan) { + var moduleId = viewPortPlan.config ? viewPortPlan.config.moduleId : null; + + return loadComponent(routeLoader, navigationInstruction, viewPortPlan.config).then(function (component) { + var viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortPlan.name, viewPortPlan.strategy, moduleId, component); + + var childRouter = component.childRouter; + if (childRouter) { + var path = navigationInstruction.getWildcardPath(); + + return childRouter._createNavigationInstruction(path, navigationInstruction).then(function (childInstruction) { + viewPortPlan.childNavigationInstruction = childInstruction; + + return _buildNavigationPlan(childInstruction).then(function (childPlan) { + if (childPlan instanceof Redirect) { + return Promise.reject(childPlan); + } + childInstruction.plan = childPlan; + viewPortInstruction.childNavigationInstruction = childInstruction; + + return loadNewRoute(routeLoader, childInstruction); + }); + }); + } + + return undefined; + }); + } + + function loadComponent(routeLoader, navigationInstruction, config) { + var router = navigationInstruction.router; + var lifecycleArgs = navigationInstruction.lifecycleArgs; + + return routeLoader.loadRoute(router, config, navigationInstruction).then(function (component) { + var viewModel = component.viewModel, + childContainer = component.childContainer; + + component.router = router; + component.config = config; + + if ('configureRouter' in viewModel) { + var childRouter = childContainer.getChildRouter(); + component.childRouter = childRouter; + + return childRouter.configure(function (c) { + return viewModel.configureRouter.apply(viewModel, [c, childRouter].concat(lifecycleArgs)); + }).then(function () { + return component; + }); + } + + return component; + }); + } + + var PipelineSlot = function () { + function PipelineSlot(container, name, alias) { + + + this.steps = []; + + this.container = container; + this.slotName = name; + this.slotAlias = alias; + } + + PipelineSlot.prototype.getSteps = function getSteps() { + var _this8 = this; + + return this.steps.map(function (x) { + return _this8.container.get(x); + }); + }; + + return PipelineSlot; + }(); + + var PipelineProvider = exports.PipelineProvider = function () { + PipelineProvider.inject = function inject() { + return [_aureliaDependencyInjection.Container]; + }; + + function PipelineProvider(container) { + + + this.container = container; + this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, this._createPipelineSlot('authorize'), CanActivateNextStep, this._createPipelineSlot('preActivate', 'modelbind'), DeactivatePreviousStep, ActivateNextStep, this._createPipelineSlot('preRender', 'precommit'), CommitChangesStep, this._createPipelineSlot('postRender', 'postcomplete')]; + } + + PipelineProvider.prototype.createPipeline = function createPipeline() { + var _this9 = this; + + var pipeline = new Pipeline(); + this.steps.forEach(function (step) { + return pipeline.addStep(_this9.container.get(step)); + }); + return pipeline; + }; + + PipelineProvider.prototype._findStep = function _findStep(name) { + return this.steps.find(function (x) { + return x.slotName === name || x.slotAlias === name; + }); + }; + + PipelineProvider.prototype.addStep = function addStep(name, step) { + var found = this._findStep(name); + if (found) { + if (!found.steps.includes(step)) { + found.steps.push(step); + } + } else { + throw new Error('Invalid pipeline slot name: ' + name + '.'); + } + }; + + PipelineProvider.prototype.removeStep = function removeStep(name, step) { + var slot = this._findStep(name); + if (slot) { + slot.steps.splice(slot.steps.indexOf(step), 1); + } + }; + + PipelineProvider.prototype._clearSteps = function _clearSteps() { + var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + + var slot = this._findStep(name); + if (slot) { + slot.steps = []; + } + }; + + PipelineProvider.prototype.reset = function reset() { + this._clearSteps('authorize'); + this._clearSteps('preActivate'); + this._clearSteps('preRender'); + this._clearSteps('postRender'); + }; + + PipelineProvider.prototype._createPipelineSlot = function _createPipelineSlot(name, alias) { + return new PipelineSlot(this.container, name, alias); + }; + + return PipelineProvider; + }(); + + var logger = LogManager.getLogger('app-router'); + + var AppRouter = exports.AppRouter = function (_Router) { + _inherits(AppRouter, _Router); + + AppRouter.inject = function inject() { + return [_aureliaDependencyInjection.Container, _aureliaHistory.History, PipelineProvider, _aureliaEventAggregator.EventAggregator]; + }; + + function AppRouter(container, history, pipelineProvider, events) { + + + var _this10 = _possibleConstructorReturn(this, _Router.call(this, container, history)); + + _this10.pipelineProvider = pipelineProvider; + _this10.events = events; + return _this10; + } + + AppRouter.prototype.reset = function reset() { + _Router.prototype.reset.call(this); + this.maxInstructionCount = 10; + if (!this._queue) { + this._queue = []; + } else { + this._queue.length = 0; + } + }; + + AppRouter.prototype.loadUrl = function loadUrl(url) { + var _this11 = this; + + return this._createNavigationInstruction(url).then(function (instruction) { + return _this11._queueInstruction(instruction); + }).catch(function (error) { + logger.error(error); + restorePreviousLocation(_this11); + }); + }; + + AppRouter.prototype.registerViewPort = function registerViewPort(viewPort, name) { + var _this12 = this; + + _Router.prototype.registerViewPort.call(this, viewPort, name); + + if (!this.isActive) { + var viewModel = this._findViewModel(viewPort); + if ('configureRouter' in viewModel) { + if (!this.isConfigured) { + var resolveConfiguredPromise = this._resolveConfiguredPromise; + this._resolveConfiguredPromise = function () {}; + return this.configure(function (config) { + return viewModel.configureRouter(config, _this12); + }).then(function () { + _this12.activate(); + resolveConfiguredPromise(); + }); + } + } else { + this.activate(); + } + } else { + this._dequeueInstruction(); + } + + return Promise.resolve(); + }; + + AppRouter.prototype.activate = function activate(options) { + if (this.isActive) { + return; + } + + this.isActive = true; + this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options); + this.history.activate(this.options); + this._dequeueInstruction(); + }; + + AppRouter.prototype.deactivate = function deactivate() { + this.isActive = false; + this.history.deactivate(); + }; + + AppRouter.prototype._queueInstruction = function _queueInstruction(instruction) { + var _this13 = this; + + return new Promise(function (resolve) { + instruction.resolve = resolve; + _this13._queue.unshift(instruction); + _this13._dequeueInstruction(); + }); + }; + + AppRouter.prototype._dequeueInstruction = function _dequeueInstruction() { + var _this14 = this; + + var instructionCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + + return Promise.resolve().then(function () { + if (_this14.isNavigating && !instructionCount) { + return undefined; + } + + var instruction = _this14._queue.shift(); + _this14._queue.length = 0; + + if (!instruction) { + return undefined; + } + + _this14.isNavigating = true; + + var navtracker = _this14.history.getState('NavigationTracker'); + if (!navtracker && !_this14.currentNavigationTracker) { + _this14.isNavigatingFirst = true; + _this14.isNavigatingNew = true; + } else if (!navtracker) { + _this14.isNavigatingNew = true; + } else if (!_this14.currentNavigationTracker) { + _this14.isNavigatingRefresh = true; + } else if (_this14.currentNavigationTracker < navtracker) { + _this14.isNavigatingForward = true; + } else if (_this14.currentNavigationTracker > navtracker) { + _this14.isNavigatingBack = true; + }if (!navtracker) { + navtracker = Date.now(); + _this14.history.setState('NavigationTracker', navtracker); + } + _this14.currentNavigationTracker = navtracker; + + instruction.previousInstruction = _this14.currentInstruction; + + if (!instructionCount) { + _this14.events.publish('router:navigation:processing', { instruction: instruction }); + } else if (instructionCount === _this14.maxInstructionCount - 1) { + logger.error(instructionCount + 1 + ' navigation instructions have been attempted without success. Restoring last known good location.'); + restorePreviousLocation(_this14); + return _this14._dequeueInstruction(instructionCount + 1); + } else if (instructionCount > _this14.maxInstructionCount) { + throw new Error('Maximum navigation attempts exceeded. Giving up.'); + } + + var pipeline = _this14.pipelineProvider.createPipeline(); + + return pipeline.run(instruction).then(function (result) { + return processResult(instruction, result, instructionCount, _this14); + }).catch(function (error) { + return { output: error instanceof Error ? error : new Error(error) }; + }).then(function (result) { + return resolveInstruction(instruction, result, !!instructionCount, _this14); + }); + }); + }; + + AppRouter.prototype._findViewModel = function _findViewModel(viewPort) { + if (this.container.viewModel) { + return this.container.viewModel; + } + + if (viewPort.container) { + var container = viewPort.container; + + while (container) { + if (container.viewModel) { + this.container.viewModel = container.viewModel; + return container.viewModel; + } + + container = container.parent; + } + } + + return undefined; + }; + + return AppRouter; + }(Router); + + function processResult(instruction, result, instructionCount, router) { + if (!(result && 'completed' in result && 'output' in result)) { + result = result || {}; + result.output = new Error('Expected router pipeline to return a navigation result, but got [' + JSON.stringify(result) + '] instead.'); + } + + var finalResult = null; + var navigationCommandResult = null; + if (isNavigationCommand(result.output)) { + navigationCommandResult = result.output.navigate(router); + } else { + finalResult = result; + + if (!result.completed) { + if (result.output instanceof Error) { + logger.error(result.output); + } + + restorePreviousLocation(router); + } + } + + return Promise.resolve(navigationCommandResult).then(function (_) { + return router._dequeueInstruction(instructionCount + 1); + }).then(function (innerResult) { + return finalResult || innerResult || result; + }); + } + + function resolveInstruction(instruction, result, isInnerInstruction, router) { + instruction.resolve(result); + + var eventArgs = { instruction: instruction, result: result }; + if (!isInnerInstruction) { + router.isNavigating = false; + router.isExplicitNavigation = false; + router.isExplicitNavigationBack = false; + router.isNavigatingFirst = false; + router.isNavigatingNew = false; + router.isNavigatingRefresh = false; + router.isNavigatingForward = false; + router.isNavigatingBack = false; + + var eventName = void 0; + + if (result.output instanceof Error) { + eventName = 'error'; + } else if (!result.completed) { + eventName = 'canceled'; + } else { + var _queryString = instruction.queryString ? '?' + instruction.queryString : ''; + router.history.previousLocation = instruction.fragment + _queryString; + eventName = 'success'; + } + + router.events.publish('router:navigation:' + eventName, eventArgs); + router.events.publish('router:navigation:complete', eventArgs); + } else { + router.events.publish('router:navigation:child:complete', eventArgs); + } + + return result; + } + + function restorePreviousLocation(router) { + var previousLocation = router.history.previousLocation; + if (previousLocation) { + router.navigate(router.history.previousLocation, { trigger: false, replace: true }); + } else if (router.fallbackRoute) { + router.navigate(router.fallbackRoute, { trigger: true, replace: true }); + } else { + logger.error('Router navigation failed, and no previous location or fallbackRoute could be restored.'); + } + } +}); +define('aurelia-route-recognizer',['exports', 'aurelia-path'], function (exports, _aureliaPath) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.RouteRecognizer = exports.EpsilonSegment = exports.StarSegment = exports.DynamicSegment = exports.StaticSegment = exports.State = undefined; + + + + var State = exports.State = function () { + function State(charSpec) { + + + this.charSpec = charSpec; + this.nextStates = []; + } + + State.prototype.get = function get(charSpec) { + for (var _iterator = this.nextStates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var child = _ref; + + var isEqual = child.charSpec.validChars === charSpec.validChars && child.charSpec.invalidChars === charSpec.invalidChars; + + if (isEqual) { + return child; + } + } + + return undefined; + }; + + State.prototype.put = function put(charSpec) { + var state = this.get(charSpec); + + if (state) { + return state; + } + + state = new State(charSpec); + + this.nextStates.push(state); + + if (charSpec.repeat) { + state.nextStates.push(state); + } + + return state; + }; + + State.prototype.match = function match(ch) { + var nextStates = this.nextStates; + var results = []; + + for (var i = 0, l = nextStates.length; i < l; i++) { + var child = nextStates[i]; + var charSpec = child.charSpec; + + if (charSpec.validChars !== undefined) { + if (charSpec.validChars.indexOf(ch) !== -1) { + results.push(child); + } + } else if (charSpec.invalidChars !== undefined) { + if (charSpec.invalidChars.indexOf(ch) === -1) { + results.push(child); + } + } + } + + return results; + }; + + return State; + }(); + + var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; + + var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); + + var StaticSegment = exports.StaticSegment = function () { + function StaticSegment(string, caseSensitive) { + + + this.string = string; + this.caseSensitive = caseSensitive; + } + + StaticSegment.prototype.eachChar = function eachChar(callback) { + var s = this.string; + for (var i = 0, ii = s.length; i < ii; ++i) { + var ch = s[i]; + callback({ validChars: this.caseSensitive ? ch : ch.toUpperCase() + ch.toLowerCase() }); + } + }; + + StaticSegment.prototype.regex = function regex() { + return this.string.replace(escapeRegex, '\\$1'); + }; + + StaticSegment.prototype.generate = function generate() { + return this.string; + }; + + return StaticSegment; + }(); + + var DynamicSegment = exports.DynamicSegment = function () { + function DynamicSegment(name, optional) { + + + this.name = name; + this.optional = optional; + } + + DynamicSegment.prototype.eachChar = function eachChar(callback) { + callback({ invalidChars: '/', repeat: true }); + }; + + DynamicSegment.prototype.regex = function regex() { + return '([^/]+)'; + }; + + DynamicSegment.prototype.generate = function generate(params, consumed) { + consumed[this.name] = true; + return params[this.name]; + }; + + return DynamicSegment; + }(); + + var StarSegment = exports.StarSegment = function () { + function StarSegment(name) { + + + this.name = name; + } + + StarSegment.prototype.eachChar = function eachChar(callback) { + callback({ invalidChars: '', repeat: true }); + }; + + StarSegment.prototype.regex = function regex() { + return '(.+)'; + }; + + StarSegment.prototype.generate = function generate(params, consumed) { + consumed[this.name] = true; + return params[this.name]; + }; + + return StarSegment; + }(); + + var EpsilonSegment = exports.EpsilonSegment = function () { + function EpsilonSegment() { + + } + + EpsilonSegment.prototype.eachChar = function eachChar() {}; + + EpsilonSegment.prototype.regex = function regex() { + return ''; + }; + + EpsilonSegment.prototype.generate = function generate() { + return ''; + }; + + return EpsilonSegment; + }(); + + var RouteRecognizer = exports.RouteRecognizer = function () { + function RouteRecognizer() { + + + this.rootState = new State(); + this.names = {}; + } + + RouteRecognizer.prototype.add = function add(route) { + var _this = this; + + if (Array.isArray(route)) { + route.forEach(function (r) { + return _this.add(r); + }); + return undefined; + } + + var currentState = this.rootState; + var skippableStates = []; + var regex = '^'; + var types = { statics: 0, dynamics: 0, stars: 0 }; + var names = []; + var routeName = route.handler.name; + var isEmpty = true; + var segments = parse(route.path, names, types, route.caseSensitive); + + for (var i = 0, ii = segments.length; i < ii; i++) { + var segment = segments[i]; + if (segment instanceof EpsilonSegment) { + continue; + } + + var _addSegment = addSegment(currentState, segment), + firstState = _addSegment[0], + nextState = _addSegment[1]; + + for (var j = 0, jj = skippableStates.length; j < jj; j++) { + skippableStates[j].nextStates.push(firstState); + } + + if (segment.optional) { + skippableStates.push(nextState); + regex += '(?:/' + segment.regex() + ')?'; + } else { + currentState = nextState; + regex += '/' + segment.regex(); + skippableStates.length = 0; + isEmpty = false; + } + } + + if (isEmpty) { + currentState = currentState.put({ validChars: '/' }); + regex += '/?'; + } + + var handlers = [{ handler: route.handler, names: names }]; + + if (routeName) { + var routeNames = Array.isArray(routeName) ? routeName : [routeName]; + for (var _i2 = 0; _i2 < routeNames.length; _i2++) { + this.names[routeNames[_i2]] = { + segments: segments, + handlers: handlers + }; + } + } + + for (var _i3 = 0; _i3 < skippableStates.length; _i3++) { + var state = skippableStates[_i3]; + state.handlers = handlers; + state.regex = new RegExp(regex + '$', route.caseSensitive ? '' : 'i'); + state.types = types; + } + + currentState.handlers = handlers; + currentState.regex = new RegExp(regex + '$', route.caseSensitive ? '' : 'i'); + currentState.types = types; + + return currentState; + }; + + RouteRecognizer.prototype.handlersFor = function handlersFor(name) { + var route = this.names[name]; + if (!route) { + throw new Error('There is no route named ' + name); + } + + return [].concat(route.handlers); + }; + + RouteRecognizer.prototype.hasRoute = function hasRoute(name) { + return !!this.names[name]; + }; + + RouteRecognizer.prototype.generate = function generate(name, params) { + var route = this.names[name]; + if (!route) { + throw new Error('There is no route named ' + name); + } + + var handler = route.handlers[0].handler; + if (handler.generationUsesHref) { + return handler.href; + } + + var routeParams = Object.assign({}, params); + var segments = route.segments; + var consumed = {}; + var output = ''; + + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + + if (segment instanceof EpsilonSegment) { + continue; + } + + var segmentValue = segment.generate(routeParams, consumed); + if (segmentValue === null || segmentValue === undefined) { + if (!segment.optional) { + throw new Error('A value is required for route parameter \'' + segment.name + '\' in route \'' + name + '\'.'); + } + } else { + output += '/'; + output += segmentValue; + } + } + + if (output.charAt(0) !== '/') { + output = '/' + output; + } + + for (var param in consumed) { + delete routeParams[param]; + } + + var queryString = (0, _aureliaPath.buildQueryString)(routeParams); + output += queryString ? '?' + queryString : ''; + + return output; + }; + + RouteRecognizer.prototype.recognize = function recognize(path) { + var states = [this.rootState]; + var queryParams = {}; + var isSlashDropped = false; + var normalizedPath = path; + + var queryStart = normalizedPath.indexOf('?'); + if (queryStart !== -1) { + var queryString = normalizedPath.substr(queryStart + 1, normalizedPath.length); + normalizedPath = normalizedPath.substr(0, queryStart); + queryParams = (0, _aureliaPath.parseQueryString)(queryString); + } + + normalizedPath = decodeURI(normalizedPath); + + if (normalizedPath.charAt(0) !== '/') { + normalizedPath = '/' + normalizedPath; + } + + var pathLen = normalizedPath.length; + if (pathLen > 1 && normalizedPath.charAt(pathLen - 1) === '/') { + normalizedPath = normalizedPath.substr(0, pathLen - 1); + isSlashDropped = true; + } + + for (var i = 0, l = normalizedPath.length; i < l; i++) { + states = recognizeChar(states, normalizedPath.charAt(i)); + if (!states.length) { + break; + } + } + + var solutions = []; + for (var _i4 = 0, _l = states.length; _i4 < _l; _i4++) { + if (states[_i4].handlers) { + solutions.push(states[_i4]); + } + } + + states = sortSolutions(solutions); + + var state = solutions[0]; + if (state && state.handlers) { + if (isSlashDropped && state.regex.source.slice(-5) === '(.+)$') { + normalizedPath = normalizedPath + '/'; + } + + return findHandler(state, normalizedPath, queryParams); + } + }; + + return RouteRecognizer; + }(); + + var RecognizeResults = function RecognizeResults(queryParams) { + + + this.splice = Array.prototype.splice; + this.slice = Array.prototype.slice; + this.push = Array.prototype.push; + this.length = 0; + this.queryParams = queryParams || {}; + }; + + function parse(route, names, types, caseSensitive) { + var normalizedRoute = route; + if (route.charAt(0) === '/') { + normalizedRoute = route.substr(1); + } + + var results = []; + + var splitRoute = normalizedRoute.split('/'); + for (var i = 0, ii = splitRoute.length; i < ii; ++i) { + var segment = splitRoute[i]; + + var match = segment.match(/^:([^?]+)(\?)?$/); + if (match) { + var _match = match, + _name = _match[1], + optional = _match[2]; + + if (_name.indexOf('=') !== -1) { + throw new Error('Parameter ' + _name + ' in route ' + route + ' has a default value, which is not supported.'); + } + results.push(new DynamicSegment(_name, !!optional)); + names.push(_name); + types.dynamics++; + continue; + } + + match = segment.match(/^\*(.+)$/); + if (match) { + results.push(new StarSegment(match[1])); + names.push(match[1]); + types.stars++; + } else if (segment === '') { + results.push(new EpsilonSegment()); + } else { + results.push(new StaticSegment(segment, caseSensitive)); + types.statics++; + } + } + + return results; + } + + function sortSolutions(states) { + return states.sort(function (a, b) { + if (a.types.stars !== b.types.stars) { + return a.types.stars - b.types.stars; + } + + if (a.types.stars) { + if (a.types.statics !== b.types.statics) { + return b.types.statics - a.types.statics; + } + if (a.types.dynamics !== b.types.dynamics) { + return b.types.dynamics - a.types.dynamics; + } + } + + if (a.types.dynamics !== b.types.dynamics) { + return a.types.dynamics - b.types.dynamics; + } + + if (a.types.statics !== b.types.statics) { + return b.types.statics - a.types.statics; + } + + return 0; + }); + } + + function recognizeChar(states, ch) { + var nextStates = []; + + for (var i = 0, l = states.length; i < l; i++) { + var state = states[i]; + nextStates.push.apply(nextStates, state.match(ch)); + } + + return nextStates; + } + + function findHandler(state, path, queryParams) { + var handlers = state.handlers; + var regex = state.regex; + var captures = path.match(regex); + var currentCapture = 1; + var result = new RecognizeResults(queryParams); + + for (var i = 0, l = handlers.length; i < l; i++) { + var _handler = handlers[i]; + var _names = _handler.names; + var _params = {}; + + for (var j = 0, m = _names.length; j < m; j++) { + _params[_names[j]] = captures[currentCapture++]; + } + + result.push({ handler: _handler.handler, params: _params, isDynamic: !!_names.length }); + } + + return result; + } + + function addSegment(currentState, segment) { + var firstState = currentState.put({ validChars: '/' }); + var nextState = firstState; + segment.eachChar(function (ch) { + nextState = nextState.put(ch); + }); + + return [firstState, nextState]; + } +}); +define('aurelia-polyfills',['aurelia-pal'], function (_aureliaPal) { + 'use strict'; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + if (typeof FEATURE_NO_ES2015 === 'undefined') { + + (function (Object, GOPS) { + 'use strict'; + + if (GOPS in Object) return; + + var setDescriptor, + G = _aureliaPal.PLATFORM.global, + id = 0, + random = '' + Math.random(), + prefix = '__\x01symbol:', + prefixLength = prefix.length, + internalSymbol = '__\x01symbol@@' + random, + DP = 'defineProperty', + DPies = 'defineProperties', + GOPN = 'getOwnPropertyNames', + GOPD = 'getOwnPropertyDescriptor', + PIE = 'propertyIsEnumerable', + gOPN = Object[GOPN], + gOPD = Object[GOPD], + create = Object.create, + keys = Object.keys, + defineProperty = Object[DP], + $defineProperties = Object[DPies], + descriptor = gOPD(Object, GOPN), + ObjectProto = Object.prototype, + hOP = ObjectProto.hasOwnProperty, + pIE = ObjectProto[PIE], + toString = ObjectProto.toString, + indexOf = Array.prototype.indexOf || function (v) { + for (var i = this.length; i-- && this[i] !== v;) {} + return i; + }, + addInternalIfNeeded = function addInternalIfNeeded(o, uid, enumerable) { + if (!hOP.call(o, internalSymbol)) { + defineProperty(o, internalSymbol, { + enumerable: false, + configurable: false, + writable: false, + value: {} + }); + } + o[internalSymbol]['@@' + uid] = enumerable; + }, + createWithSymbols = function createWithSymbols(proto, descriptors) { + var self = create(proto); + if (descriptors !== null && (typeof descriptors === 'undefined' ? 'undefined' : _typeof(descriptors)) === 'object') { + gOPN(descriptors).forEach(function (key) { + if (propertyIsEnumerable.call(descriptors, key)) { + $defineProperty(self, key, descriptors[key]); + } + }); + } + return self; + }, + copyAsNonEnumerable = function copyAsNonEnumerable(descriptor) { + var newDescriptor = create(descriptor); + newDescriptor.enumerable = false; + return newDescriptor; + }, + get = function get() {}, + onlyNonSymbols = function onlyNonSymbols(name) { + return name != internalSymbol && !hOP.call(source, name); + }, + onlySymbols = function onlySymbols(name) { + return name != internalSymbol && hOP.call(source, name); + }, + propertyIsEnumerable = function propertyIsEnumerable(key) { + var uid = '' + key; + return onlySymbols(uid) ? hOP.call(this, uid) && this[internalSymbol] && this[internalSymbol]['@@' + uid] : pIE.call(this, key); + }, + setAndGetSymbol = function setAndGetSymbol(uid) { + var descriptor = { + enumerable: false, + configurable: true, + get: get, + set: function set(value) { + setDescriptor(this, uid, { + enumerable: false, + configurable: true, + writable: true, + value: value + }); + addInternalIfNeeded(this, uid, true); + } + }; + defineProperty(ObjectProto, uid, descriptor); + return source[uid] = defineProperty(Object(uid), 'constructor', sourceConstructor); + }, + _Symbol = function _Symbol2(description) { + if (this && this !== G) { + throw new TypeError('Symbol is not a constructor'); + } + return setAndGetSymbol(prefix.concat(description || '', random, ++id)); + }, + source = create(null), + sourceConstructor = { value: _Symbol }, + sourceMap = function sourceMap(uid) { + return source[uid]; + }, + $defineProperty = function defineProp(o, key, descriptor) { + var uid = '' + key; + if (onlySymbols(uid)) { + setDescriptor(o, uid, descriptor.enumerable ? copyAsNonEnumerable(descriptor) : descriptor); + addInternalIfNeeded(o, uid, !!descriptor.enumerable); + } else { + defineProperty(o, key, descriptor); + } + return o; + }, + $getOwnPropertySymbols = function getOwnPropertySymbols(o) { + var cof = toString.call(o); + o = cof === '[object String]' ? o.split('') : Object(o); + return gOPN(o).filter(onlySymbols).map(sourceMap); + }; + + descriptor.value = $defineProperty; + defineProperty(Object, DP, descriptor); + + descriptor.value = $getOwnPropertySymbols; + defineProperty(Object, GOPS, descriptor); + + var cachedWindowNames = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' ? Object.getOwnPropertyNames(window) : []; + var originalObjectGetOwnPropertyNames = Object.getOwnPropertyNames; + descriptor.value = function getOwnPropertyNames(o) { + if (toString.call(o) === '[object Window]') { + try { + return originalObjectGetOwnPropertyNames(o); + } catch (e) { + return [].concat([], cachedWindowNames); + } + } + return gOPN(o).filter(onlyNonSymbols); + }; + defineProperty(Object, GOPN, descriptor); + + descriptor.value = function defineProperties(o, descriptors) { + var symbols = $getOwnPropertySymbols(descriptors); + if (symbols.length) { + keys(descriptors).concat(symbols).forEach(function (uid) { + if (propertyIsEnumerable.call(descriptors, uid)) { + $defineProperty(o, uid, descriptors[uid]); + } + }); + } else { + $defineProperties(o, descriptors); + } + return o; + }; + defineProperty(Object, DPies, descriptor); + + descriptor.value = propertyIsEnumerable; + defineProperty(ObjectProto, PIE, descriptor); + + descriptor.value = _Symbol; + defineProperty(G, 'Symbol', descriptor); + + descriptor.value = function (key) { + var uid = prefix.concat(prefix, key, random); + return uid in ObjectProto ? source[uid] : setAndGetSymbol(uid); + }; + defineProperty(_Symbol, 'for', descriptor); + + descriptor.value = function (symbol) { + return hOP.call(source, symbol) ? symbol.slice(prefixLength * 2, -random.length) : void 0; + }; + defineProperty(_Symbol, 'keyFor', descriptor); + + descriptor.value = function getOwnPropertyDescriptor(o, key) { + var descriptor = gOPD(o, key); + if (descriptor && onlySymbols(key)) { + descriptor.enumerable = propertyIsEnumerable.call(o, key); + } + return descriptor; + }; + defineProperty(Object, GOPD, descriptor); + + descriptor.value = function (proto, descriptors) { + return arguments.length === 1 ? create(proto) : createWithSymbols(proto, descriptors); + }; + defineProperty(Object, 'create', descriptor); + + descriptor.value = function () { + var str = toString.call(this); + return str === '[object String]' && onlySymbols(this) ? '[object Symbol]' : str; + }; + defineProperty(ObjectProto, 'toString', descriptor); + + try { + setDescriptor = create(defineProperty({}, prefix, { + get: function get() { + return defineProperty(this, prefix, { value: false })[prefix]; + } + }))[prefix] || defineProperty; + } catch (o_O) { + setDescriptor = function setDescriptor(o, key, descriptor) { + var protoDescriptor = gOPD(ObjectProto, key); + delete ObjectProto[key]; + defineProperty(o, key, descriptor); + defineProperty(ObjectProto, key, protoDescriptor); + }; + } + })(Object, 'getOwnPropertySymbols'); + + (function (O, S) { + var dP = O.defineProperty, + ObjectProto = O.prototype, + toString = ObjectProto.toString, + toStringTag = 'toStringTag', + descriptor; + ['iterator', 'match', 'replace', 'search', 'split', 'hasInstance', 'isConcatSpreadable', 'unscopables', 'species', 'toPrimitive', toStringTag].forEach(function (name) { + if (!(name in Symbol)) { + dP(Symbol, name, { value: Symbol(name) }); + switch (name) { + case toStringTag: + descriptor = O.getOwnPropertyDescriptor(ObjectProto, 'toString'); + descriptor.value = function () { + var str = toString.call(this), + tst = typeof this === 'undefined' || this === null ? undefined : this[Symbol.toStringTag]; + return typeof tst === 'undefined' ? str : '[object ' + tst + ']'; + }; + dP(ObjectProto, 'toString', descriptor); + break; + } + } + }); + })(Object, Symbol); + + (function (Si, AP, SP) { + + function returnThis() { + return this; + } + + if (!AP[Si]) AP[Si] = function () { + var i = 0, + self = this, + iterator = { + next: function next() { + var done = self.length <= i; + return done ? { done: done } : { done: done, value: self[i++] }; + } + }; + iterator[Si] = returnThis; + return iterator; + }; + + if (!SP[Si]) SP[Si] = function () { + var fromCodePoint = String.fromCodePoint, + self = this, + i = 0, + length = self.length, + iterator = { + next: function next() { + var done = length <= i, + c = done ? '' : fromCodePoint(self.codePointAt(i)); + i += c.length; + return done ? { done: done } : { done: done, value: c }; + } + }; + iterator[Si] = returnThis; + return iterator; + }; + })(Symbol.iterator, Array.prototype, String.prototype); + } + + if (typeof FEATURE_NO_ES2015 === 'undefined') { + + Number.isNaN = Number.isNaN || function (value) { + return value !== value; + }; + + Number.isFinite = Number.isFinite || function (value) { + return typeof value === "number" && isFinite(value); + }; + } + + if (!String.prototype.endsWith || function () { + try { + return !"ab".endsWith("a", 1); + } catch (e) { + return true; + } + }()) { + String.prototype.endsWith = function (searchString, position) { + var subjectString = this.toString(); + if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { + position = subjectString.length; + } + position -= searchString.length; + var lastIndex = subjectString.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; + } + + if (!String.prototype.startsWith || function () { + try { + return !"ab".startsWith("b", 1); + } catch (e) { + return true; + } + }()) { + String.prototype.startsWith = function (searchString, position) { + position = position || 0; + return this.substr(position, searchString.length) === searchString; + }; + } + + if (typeof FEATURE_NO_ES2015 === 'undefined') { + + if (!Array.from) { + Array.from = function () { + var toInteger = function toInteger(it) { + return isNaN(it = +it) ? 0 : (it > 0 ? Math.floor : Math.ceil)(it); + }; + var toLength = function toLength(it) { + return it > 0 ? Math.min(toInteger(it), 0x1fffffffffffff) : 0; + }; + var iterCall = function iterCall(iter, fn, val, index) { + try { + return fn(val, index); + } catch (E) { + if (typeof iter.return == 'function') iter.return(); + throw E; + } + }; + + return function from(arrayLike) { + var O = Object(arrayLike), + C = typeof this == 'function' ? this : Array, + aLen = arguments.length, + mapfn = aLen > 1 ? arguments[1] : undefined, + mapping = mapfn !== undefined, + index = 0, + iterFn = O[Symbol.iterator], + length, + result, + step, + iterator; + if (mapping) mapfn = mapfn.bind(aLen > 2 ? arguments[2] : undefined); + if (iterFn != undefined && !Array.isArray(arrayLike)) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + result[index] = mapping ? iterCall(iterator, mapfn, step.value, index) : step.value; + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + result[index] = mapping ? mapfn(O[index], index) : O[index]; + } + } + result.length = index; + return result; + }; + }(); + } + + if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + configurable: true, + writable: true, + enumerable: false, + value: function value(predicate) { + if (this === null) { + throw new TypeError('Array.prototype.find called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return value; + } + } + return undefined; + } + }); + } + + if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + configurable: true, + writable: true, + enumerable: false, + value: function value(predicate) { + if (this === null) { + throw new TypeError('Array.prototype.findIndex called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return i; + } + } + return -1; + } + }); + } + } + + if (typeof FEATURE_NO_ES2016 === 'undefined' && !Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { + configurable: true, + writable: true, + enumerable: false, + value: function value(searchElement) { + var O = Object(this); + var len = parseInt(O.length) || 0; + if (len === 0) { + return false; + } + var n = parseInt(arguments[1]) || 0; + var k; + if (n >= 0) { + k = n; + } else { + k = len + n; + if (k < 0) { + k = 0; + } + } + var currentElement; + while (k < len) { + currentElement = O[k]; + if (searchElement === currentElement || searchElement !== searchElement && currentElement !== currentElement) { + return true; + } + k++; + } + return false; + } + }); + } + + if (typeof FEATURE_NO_ES2015 === 'undefined') { + + (function () { + var needsFix = false; + + try { + var s = Object.keys('a'); + needsFix = s.length !== 1 || s[0] !== '0'; + } catch (e) { + needsFix = true; + } + + if (needsFix) { + Object.keys = function () { + var hasOwnProperty = Object.prototype.hasOwnProperty, + hasDontEnumBug = !{ toString: null }.propertyIsEnumerable('toString'), + dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], + dontEnumsLength = dontEnums.length; + + return function (obj) { + if (obj === undefined || obj === null) { + throw TypeError('Cannot convert undefined or null to object'); + } + + obj = Object(obj); + + var result = [], + prop, + i; + + for (prop in obj) { + if (hasOwnProperty.call(obj, prop)) { + result.push(prop); + } + } + + if (hasDontEnumBug) { + for (i = 0; i < dontEnumsLength; i++) { + if (hasOwnProperty.call(obj, dontEnums[i])) { + result.push(dontEnums[i]); + } + } + } + + return result; + }; + }(); + } + })(); + + (function (O) { + if ('assign' in O) { + return; + } + + O.defineProperty(O, 'assign', { + configurable: true, + writable: true, + value: function () { + var gOPS = O.getOwnPropertySymbols, + pIE = O.propertyIsEnumerable, + filterOS = gOPS ? function (self) { + return gOPS(self).filter(pIE, self); + } : function () { + return Array.prototype; + }; + + return function assign(where) { + if (gOPS && !(where instanceof O)) { + console.warn('problematic Symbols', where); + } + + function set(keyOrSymbol) { + where[keyOrSymbol] = arg[keyOrSymbol]; + } + + for (var i = 1, ii = arguments.length; i < ii; ++i) { + var arg = arguments[i]; + + if (arg === null || arg === undefined) { + continue; + } + + O.keys(arg).concat(filterOS(arg)).forEach(set); + } + + return where; + }; + }() + }); + })(Object); + + if (!Object.is) { + Object.is = function (x, y) { + if (x === y) { + return x !== 0 || 1 / x === 1 / y; + } else { + return x !== x && y !== y; + } + }; + } + } + + if (typeof FEATURE_NO_ES2015 === 'undefined') { + + (function (global) { + var i; + + var defineProperty = Object.defineProperty, + is = function is(a, b) { + return a === b || a !== a && b !== b; + }; + + if (typeof WeakMap == 'undefined') { + global.WeakMap = createCollection({ + 'delete': sharedDelete, + + clear: sharedClear, + + get: sharedGet, + + has: mapHas, + + set: sharedSet + }, true); + } + + if (typeof Map == 'undefined' || typeof new Map().values !== 'function' || !new Map().values().next) { + var _createCollection; + + global.Map = createCollection((_createCollection = { + 'delete': sharedDelete, + + has: mapHas, + + get: sharedGet, + + set: sharedSet, + + keys: sharedKeys, + + values: sharedValues, + + entries: mapEntries, + + forEach: sharedForEach, + + clear: sharedClear + }, _createCollection[Symbol.iterator] = mapEntries, _createCollection)); + } + + if (typeof Set == 'undefined' || typeof new Set().values !== 'function' || !new Set().values().next) { + var _createCollection2; + + global.Set = createCollection((_createCollection2 = { + has: setHas, + + add: sharedAdd, + + 'delete': sharedDelete, + + clear: sharedClear, + + keys: sharedValues, + values: sharedValues, + + entries: setEntries, + + forEach: sharedForEach + }, _createCollection2[Symbol.iterator] = sharedValues, _createCollection2)); + } + + if (typeof WeakSet == 'undefined') { + global.WeakSet = createCollection({ + 'delete': sharedDelete, + + add: sharedAdd, + + clear: sharedClear, + + has: setHas + }, true); + } + + function createCollection(proto, objectOnly) { + function Collection(a) { + if (!this || this.constructor !== Collection) return new Collection(a); + this._keys = []; + this._values = []; + this._itp = []; + this.objectOnly = objectOnly; + + if (a) init.call(this, a); + } + + if (!objectOnly) { + defineProperty(proto, 'size', { + get: sharedSize + }); + } + + proto.constructor = Collection; + Collection.prototype = proto; + + return Collection; + } + + function init(a) { + var i; + + if (this.add) a.forEach(this.add, this);else a.forEach(function (a) { + this.set(a[0], a[1]); + }, this); + } + + function sharedDelete(key) { + if (this.has(key)) { + this._keys.splice(i, 1); + this._values.splice(i, 1); + + this._itp.forEach(function (p) { + if (i < p[0]) p[0]--; + }); + } + + return -1 < i; + }; + + function sharedGet(key) { + return this.has(key) ? this._values[i] : undefined; + } + + function has(list, key) { + if (this.objectOnly && key !== Object(key)) throw new TypeError("Invalid value used as weak collection key"); + + if (key != key || key === 0) for (i = list.length; i-- && !is(list[i], key);) {} else i = list.indexOf(key); + return -1 < i; + } + + function setHas(value) { + return has.call(this, this._values, value); + } + + function mapHas(value) { + return has.call(this, this._keys, value); + } + + function sharedSet(key, value) { + this.has(key) ? this._values[i] = value : this._values[this._keys.push(key) - 1] = value; + return this; + } + + function sharedAdd(value) { + if (!this.has(value)) this._values.push(value); + return this; + } + + function sharedClear() { + (this._keys || 0).length = this._values.length = 0; + } + + function sharedKeys() { + return sharedIterator(this._itp, this._keys); + } + + function sharedValues() { + return sharedIterator(this._itp, this._values); + } + + function mapEntries() { + return sharedIterator(this._itp, this._keys, this._values); + } + + function setEntries() { + return sharedIterator(this._itp, this._values, this._values); + } + + function sharedIterator(itp, array, array2) { + var _ref; + + var p = [0], + done = false; + itp.push(p); + return _ref = {}, _ref[Symbol.iterator] = function () { + return this; + }, _ref.next = function next() { + var v, + k = p[0]; + if (!done && k < array.length) { + v = array2 ? [array[k], array2[k]] : array[k]; + p[0]++; + } else { + done = true; + itp.splice(itp.indexOf(p), 1); + } + return { done: done, value: v }; + }, _ref; + } + + function sharedSize() { + return this._values.length; + } + + function sharedForEach(callback, context) { + var it = this.entries(); + for (;;) { + var r = it.next(); + if (r.done) break; + callback.call(context, r.value[1], r.value[0], this); + } + } + })(_aureliaPal.PLATFORM.global); + } + + if (typeof FEATURE_NO_ES2015 === 'undefined') { + (function () { + + var bind = Function.prototype.bind; + + if (typeof _aureliaPal.PLATFORM.global.Reflect === 'undefined') { + _aureliaPal.PLATFORM.global.Reflect = {}; + } + + if (typeof Reflect.defineProperty !== 'function') { + Reflect.defineProperty = function (target, propertyKey, descriptor) { + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' ? target === null : typeof target !== 'function') { + throw new TypeError('Reflect.defineProperty called on non-object'); + } + try { + Object.defineProperty(target, propertyKey, descriptor); + return true; + } catch (e) { + return false; + } + }; + } + + if (typeof Reflect.construct !== 'function') { + Reflect.construct = function (Target, args) { + if (args) { + switch (args.length) { + case 0: + return new Target(); + case 1: + return new Target(args[0]); + case 2: + return new Target(args[0], args[1]); + case 3: + return new Target(args[0], args[1], args[2]); + case 4: + return new Target(args[0], args[1], args[2], args[3]); + } + } + + var a = [null]; + a.push.apply(a, args); + return new (bind.apply(Target, a))(); + }; + } + + if (typeof Reflect.ownKeys !== 'function') { + Reflect.ownKeys = function (o) { + return Object.getOwnPropertyNames(o).concat(Object.getOwnPropertySymbols(o)); + }; + } + })(); + } + + if (typeof FEATURE_NO_ESNEXT === 'undefined') { + (function () { + + var emptyMetadata = Object.freeze({}); + var metadataContainerKey = '__metadata__'; + + if (typeof Reflect.getOwnMetadata !== 'function') { + Reflect.getOwnMetadata = function (metadataKey, target, targetKey) { + if (target.hasOwnProperty(metadataContainerKey)) { + return (target[metadataContainerKey][targetKey] || emptyMetadata)[metadataKey]; + } + }; + } + + if (typeof Reflect.defineMetadata !== 'function') { + Reflect.defineMetadata = function (metadataKey, metadataValue, target, targetKey) { + var metadataContainer = target.hasOwnProperty(metadataContainerKey) ? target[metadataContainerKey] : target[metadataContainerKey] = {}; + var targetContainer = metadataContainer[targetKey] || (metadataContainer[targetKey] = {}); + targetContainer[metadataKey] = metadataValue; + }; + } + + if (typeof Reflect.metadata !== 'function') { + Reflect.metadata = function (metadataKey, metadataValue) { + return function (target, targetKey) { + Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); + }; + }; + } + })(); + } +}); +define('aurelia-path',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.relativeToFile = relativeToFile; + exports.join = join; + exports.buildQueryString = buildQueryString; + exports.parseQueryString = parseQueryString; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + function trimDots(ary) { + for (var i = 0; i < ary.length; ++i) { + var part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + if (i === 0 || i === 1 && ary[2] === '..' || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + function relativeToFile(name, file) { + var fileParts = file && file.split('/'); + var nameParts = name.trim().split('/'); + + if (nameParts[0].charAt(0) === '.' && fileParts) { + var normalizedBaseParts = fileParts.slice(0, fileParts.length - 1); + nameParts.unshift.apply(nameParts, normalizedBaseParts); + } + + trimDots(nameParts); + + return nameParts.join('/'); + } + + function join(path1, path2) { + if (!path1) { + return path2; + } + + if (!path2) { + return path1; + } + + var schemeMatch = path1.match(/^([^/]*?:)\//); + var scheme = schemeMatch && schemeMatch.length > 0 ? schemeMatch[1] : ''; + path1 = path1.substr(scheme.length); + + var urlPrefix = void 0; + if (path1.indexOf('///') === 0 && scheme === 'file:') { + urlPrefix = '///'; + } else if (path1.indexOf('//') === 0) { + urlPrefix = '//'; + } else if (path1.indexOf('/') === 0) { + urlPrefix = '/'; + } else { + urlPrefix = ''; + } + + var trailingSlash = path2.slice(-1) === '/' ? '/' : ''; + + var url1 = path1.split('/'); + var url2 = path2.split('/'); + var url3 = []; + + for (var i = 0, ii = url1.length; i < ii; ++i) { + if (url1[i] === '..') { + url3.pop(); + } else if (url1[i] === '.' || url1[i] === '') { + continue; + } else { + url3.push(url1[i]); + } + } + + for (var _i = 0, _ii = url2.length; _i < _ii; ++_i) { + if (url2[_i] === '..') { + url3.pop(); + } else if (url2[_i] === '.' || url2[_i] === '') { + continue; + } else { + url3.push(url2[_i]); + } + } + + return scheme + urlPrefix + url3.join('/') + trailingSlash; + } + + var encode = encodeURIComponent; + var encodeKey = function encodeKey(k) { + return encode(k).replace('%24', '$'); + }; + + function buildParam(key, value, traditional) { + var result = []; + if (value === null || value === undefined) { + return result; + } + if (Array.isArray(value)) { + for (var i = 0, l = value.length; i < l; i++) { + if (traditional) { + result.push(encodeKey(key) + '=' + encode(value[i])); + } else { + var arrayKey = key + '[' + (_typeof(value[i]) === 'object' && value[i] !== null ? i : '') + ']'; + result = result.concat(buildParam(arrayKey, value[i])); + } + } + } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !traditional) { + for (var propertyName in value) { + result = result.concat(buildParam(key + '[' + propertyName + ']', value[propertyName])); + } + } else { + result.push(encodeKey(key) + '=' + encode(value)); + } + return result; + } + + function buildQueryString(params, traditional) { + var pairs = []; + var keys = Object.keys(params || {}).sort(); + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + pairs = pairs.concat(buildParam(key, params[key], traditional)); + } + + if (pairs.length === 0) { + return ''; + } + + return pairs.join('&'); + } + + function processScalarParam(existedParam, value) { + if (Array.isArray(existedParam)) { + existedParam.push(value); + return existedParam; + } + if (existedParam !== undefined) { + return [existedParam, value]; + } + + return value; + } + + function parseComplexParam(queryParams, keys, value) { + var currentParams = queryParams; + var keysLastIndex = keys.length - 1; + for (var j = 0; j <= keysLastIndex; j++) { + var key = keys[j] === '' ? currentParams.length : keys[j]; + if (j < keysLastIndex) { + var prevValue = !currentParams[key] || _typeof(currentParams[key]) === 'object' ? currentParams[key] : [currentParams[key]]; + currentParams = currentParams[key] = prevValue || (isNaN(keys[j + 1]) ? {} : []); + } else { + currentParams = currentParams[key] = value; + } + } + } + + function parseQueryString(queryString) { + var queryParams = {}; + if (!queryString || typeof queryString !== 'string') { + return queryParams; + } + + var query = queryString; + if (query.charAt(0) === '?') { + query = query.substr(1); + } + + var pairs = query.replace(/\+/g, ' ').split('&'); + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i].split('='); + var key = decodeURIComponent(pair[0]); + if (!key) { + continue; + } + + var keys = key.split(']['); + var keysLastIndex = keys.length - 1; + + if (/\[/.test(keys[0]) && /\]$/.test(keys[keysLastIndex])) { + keys[keysLastIndex] = keys[keysLastIndex].replace(/\]$/, ''); + keys = keys.shift().split('[').concat(keys); + keysLastIndex = keys.length - 1; + } else { + keysLastIndex = 0; + } + + if (pair.length >= 2) { + var value = pair[1] ? decodeURIComponent(pair[1]) : ''; + if (keysLastIndex) { + parseComplexParam(queryParams, keys, value); + } else { + queryParams[key] = processScalarParam(queryParams[key], value); + } + } else { + queryParams[key] = true; + } + } + return queryParams; + } +}); +define('aurelia-pal',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.AggregateError = AggregateError; + exports.initializePAL = initializePAL; + exports.reset = reset; + function AggregateError(message, innerError, skipIfAlreadyAggregate) { + if (innerError) { + if (innerError.innerError && skipIfAlreadyAggregate) { + return innerError; + } + + var separator = '\n------------------------------------------------\n'; + + message += separator + 'Inner Error:\n'; + + if (typeof innerError === 'string') { + message += 'Message: ' + innerError; + } else { + if (innerError.message) { + message += 'Message: ' + innerError.message; + } else { + message += 'Unknown Inner Error Type. Displaying Inner Error as JSON:\n ' + JSON.stringify(innerError, null, ' '); + } + + if (innerError.stack) { + message += '\nInner Error Stack:\n' + innerError.stack; + message += '\nEnd Inner Error Stack'; + } + } + + message += separator; + } + + var e = new Error(message); + if (innerError) { + e.innerError = innerError; + } + + return e; + } + + var FEATURE = exports.FEATURE = {}; + + var PLATFORM = exports.PLATFORM = { + noop: function noop() {}, + eachModule: function eachModule() {}, + moduleName: function (_moduleName) { + function moduleName(_x) { + return _moduleName.apply(this, arguments); + } + + moduleName.toString = function () { + return _moduleName.toString(); + }; + + return moduleName; + }(function (moduleName) { + return moduleName; + }) + }; + + PLATFORM.global = function () { + if (typeof self !== 'undefined') { + return self; + } + + if (typeof global !== 'undefined') { + return global; + } + + return new Function('return this')(); + }(); + + var DOM = exports.DOM = {}; + var isInitialized = exports.isInitialized = false; + function initializePAL(callback) { + if (isInitialized) { + return; + } + exports.isInitialized = isInitialized = true; + if (typeof Object.getPropertyDescriptor !== 'function') { + Object.getPropertyDescriptor = function (subject, name) { + var pd = Object.getOwnPropertyDescriptor(subject, name); + var proto = Object.getPrototypeOf(subject); + while (typeof pd === 'undefined' && proto !== null) { + pd = Object.getOwnPropertyDescriptor(proto, name); + proto = Object.getPrototypeOf(proto); + } + return pd; + }; + } + + callback(PLATFORM, FEATURE, DOM); + } + function reset() { + exports.isInitialized = isInitialized = false; + } +}); +define('aurelia-pal-browser',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports._DOM = exports._FEATURE = exports._PLATFORM = undefined; + exports.initialize = initialize; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + var _PLATFORM = exports._PLATFORM = { + location: window.location, + history: window.history, + addEventListener: function addEventListener(eventName, callback, capture) { + this.global.addEventListener(eventName, callback, capture); + }, + removeEventListener: function removeEventListener(eventName, callback, capture) { + this.global.removeEventListener(eventName, callback, capture); + }, + + performance: window.performance, + requestAnimationFrame: function requestAnimationFrame(callback) { + return this.global.requestAnimationFrame(callback); + } + }; + + if (typeof FEATURE_NO_IE === 'undefined') { + var test = function test() {}; + + if (test.name === undefined) { + Object.defineProperty(Function.prototype, 'name', { + get: function get() { + var name = this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; + + Object.defineProperty(this, 'name', { value: name }); + return name; + } + }); + } + } + + if (typeof FEATURE_NO_IE === 'undefined') { + if (!('classList' in document.createElement('_')) || document.createElementNS && !('classList' in document.createElementNS('http://www.w3.org/2000/svg', 'g'))) { + var protoProp = 'prototype'; + var strTrim = String.prototype.trim; + var arrIndexOf = Array.prototype.indexOf; + var emptyArray = []; + + var DOMEx = function DOMEx(type, message) { + this.name = type; + this.code = DOMException[type]; + this.message = message; + }; + + var checkTokenAndGetIndex = function checkTokenAndGetIndex(classList, token) { + if (token === '') { + throw new DOMEx('SYNTAX_ERR', 'An invalid or illegal string was specified'); + } + + if (/\s/.test(token)) { + throw new DOMEx('INVALID_CHARACTER_ERR', 'String contains an invalid character'); + } + + return arrIndexOf.call(classList, token); + }; + + var ClassList = function ClassList(elem) { + var trimmedClasses = strTrim.call(elem.getAttribute('class') || ''); + var classes = trimmedClasses ? trimmedClasses.split(/\s+/) : emptyArray; + + for (var i = 0, ii = classes.length; i < ii; ++i) { + this.push(classes[i]); + } + + this._updateClassName = function () { + elem.setAttribute('class', this.toString()); + }; + }; + + var classListProto = ClassList[protoProp] = []; + + DOMEx[protoProp] = Error[protoProp]; + + classListProto.item = function (i) { + return this[i] || null; + }; + + classListProto.contains = function (token) { + token += ''; + return checkTokenAndGetIndex(this, token) !== -1; + }; + + classListProto.add = function () { + var tokens = arguments; + var i = 0; + var ii = tokens.length; + var token = void 0; + var updated = false; + + do { + token = tokens[i] + ''; + if (checkTokenAndGetIndex(this, token) === -1) { + this.push(token); + updated = true; + } + } while (++i < ii); + + if (updated) { + this._updateClassName(); + } + }; + + classListProto.remove = function () { + var tokens = arguments; + var i = 0; + var ii = tokens.length; + var token = void 0; + var updated = false; + var index = void 0; + + do { + token = tokens[i] + ''; + index = checkTokenAndGetIndex(this, token); + while (index !== -1) { + this.splice(index, 1); + updated = true; + index = checkTokenAndGetIndex(this, token); + } + } while (++i < ii); + + if (updated) { + this._updateClassName(); + } + }; + + classListProto.toggle = function (token, force) { + token += ''; + + var result = this.contains(token); + var method = result ? force !== true && 'remove' : force !== false && 'add'; + + if (method) { + this[method](token); + } + + if (force === true || force === false) { + return force; + } + + return !result; + }; + + classListProto.toString = function () { + return this.join(' '); + }; + + Object.defineProperty(Element.prototype, 'classList', { + get: function get() { + return new ClassList(this); + }, + enumerable: true, + configurable: true + }); + } else { + var testElement = document.createElement('_'); + testElement.classList.add('c1', 'c2'); + + if (!testElement.classList.contains('c2')) { + var createMethod = function createMethod(method) { + var original = DOMTokenList.prototype[method]; + + DOMTokenList.prototype[method] = function (token) { + for (var i = 0, ii = arguments.length; i < ii; ++i) { + token = arguments[i]; + original.call(this, token); + } + }; + }; + + createMethod('add'); + createMethod('remove'); + } + + testElement.classList.toggle('c3', false); + + if (testElement.classList.contains('c3')) { + var _toggle = DOMTokenList.prototype.toggle; + + DOMTokenList.prototype.toggle = function (token, force) { + if (1 in arguments && !this.contains(token) === !force) { + return force; + } + + return _toggle.call(this, token); + }; + } + + testElement = null; + } + } + + if (typeof FEATURE_NO_IE === 'undefined') { + var _filterEntries = function _filterEntries(key, value) { + var i = 0, + n = _entries.length, + result = []; + for (; i < n; i++) { + if (_entries[i][key] == value) { + result.push(_entries[i]); + } + } + return result; + }; + + var _clearEntries = function _clearEntries(type, name) { + var i = _entries.length, + entry; + while (i--) { + entry = _entries[i]; + if (entry.entryType == type && (name === void 0 || entry.name == name)) { + _entries.splice(i, 1); + } + } + }; + + // @license http://opensource.org/licenses/MIT + if ('performance' in window === false) { + window.performance = {}; + } + + if ('now' in window.performance === false) { + var nowOffset = Date.now(); + + if (performance.timing && performance.timing.navigationStart) { + nowOffset = performance.timing.navigationStart; + } + + window.performance.now = function now() { + return Date.now() - nowOffset; + }; + } + + var startOffset = Date.now ? Date.now() : +new Date(); + var _entries = []; + var _marksIndex = {}; + + ; + + if (!window.performance.mark) { + window.performance.mark = window.performance.webkitMark || function (name) { + var mark = { + name: name, + entryType: "mark", + startTime: window.performance.now(), + duration: 0 + }; + + _entries.push(mark); + _marksIndex[name] = mark; + }; + } + + if (!window.performance.measure) { + window.performance.measure = window.performance.webkitMeasure || function (name, startMark, endMark) { + startMark = _marksIndex[startMark].startTime; + endMark = _marksIndex[endMark].startTime; + + _entries.push({ + name: name, + entryType: "measure", + startTime: startMark, + duration: endMark - startMark + }); + }; + } + + if (!window.performance.getEntriesByType) { + window.performance.getEntriesByType = window.performance.webkitGetEntriesByType || function (type) { + return _filterEntries("entryType", type); + }; + } + + if (!window.performance.getEntriesByName) { + window.performance.getEntriesByName = window.performance.webkitGetEntriesByName || function (name) { + return _filterEntries("name", name); + }; + } + + if (!window.performance.clearMarks) { + window.performance.clearMarks = window.performance.webkitClearMarks || function (name) { + _clearEntries("mark", name); + }; + } + + if (!window.performance.clearMeasures) { + window.performance.clearMeasures = window.performance.webkitClearMeasures || function (name) { + _clearEntries("measure", name); + }; + } + + _PLATFORM.performance = window.performance; + } + + if (typeof FEATURE_NO_IE === 'undefined') { + var con = window.console = window.console || {}; + var nop = function nop() {}; + + if (!con.memory) con.memory = {}; + ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',').forEach(function (m) { + if (!con[m]) con[m] = nop; + }); + + if (_typeof(con.log) === 'object') { + 'log,info,warn,error,assert,dir,clear,profile,profileEnd'.split(',').forEach(function (method) { + console[method] = this.bind(console[method], console); + }, Function.prototype.call); + } + } + + if (typeof FEATURE_NO_IE === 'undefined') { + if (!window.CustomEvent || typeof window.CustomEvent !== 'function') { + var _CustomEvent = function _CustomEvent(event, params) { + params = params || { + bubbles: false, + cancelable: false, + detail: undefined + }; + + var evt = document.createEvent('CustomEvent'); + evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); + return evt; + }; + + _CustomEvent.prototype = window.Event.prototype; + window.CustomEvent = _CustomEvent; + } + } + + if (Element && !Element.prototype.matches) { + var proto = Element.prototype; + proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; + } + + var _FEATURE = exports._FEATURE = { + shadowDOM: !!HTMLElement.prototype.attachShadow, + scopedCSS: 'scoped' in document.createElement('style'), + htmlTemplateElement: function () { + var d = document.createElement('div'); + d.innerHTML = ''; + return 'content' in d.children[0]; + }(), + mutationObserver: !!(window.MutationObserver || window.WebKitMutationObserver), + ensureHTMLTemplateElement: function ensureHTMLTemplateElement(t) { + return t; + } + }; + + if (typeof FEATURE_NO_IE === 'undefined') { + var isSVGTemplate = function isSVGTemplate(el) { + return el.tagName === 'template' && el.namespaceURI === 'http://www.w3.org/2000/svg'; + }; + + var fixSVGTemplateElement = function fixSVGTemplateElement(el) { + var template = el.ownerDocument.createElement('template'); + var attrs = el.attributes; + var length = attrs.length; + var attr = void 0; + + el.parentNode.insertBefore(template, el); + + while (length-- > 0) { + attr = attrs[length]; + template.setAttribute(attr.name, attr.value); + el.removeAttribute(attr.name); + } + + el.parentNode.removeChild(el); + + return fixHTMLTemplateElement(template); + }; + + var fixHTMLTemplateElement = function fixHTMLTemplateElement(template) { + var content = template.content = document.createDocumentFragment(); + var child = void 0; + + while (child = template.firstChild) { + content.appendChild(child); + } + + return template; + }; + + var fixHTMLTemplateElementRoot = function fixHTMLTemplateElementRoot(template) { + var content = fixHTMLTemplateElement(template).content; + var childTemplates = content.querySelectorAll('template'); + + for (var i = 0, ii = childTemplates.length; i < ii; ++i) { + var child = childTemplates[i]; + + if (isSVGTemplate(child)) { + fixSVGTemplateElement(child); + } else { + fixHTMLTemplateElement(child); + } + } + + return template; + }; + + if (!_FEATURE.htmlTemplateElement) { + _FEATURE.ensureHTMLTemplateElement = fixHTMLTemplateElementRoot; + } + } + + var shadowPoly = window.ShadowDOMPolyfill || null; + + var _DOM = exports._DOM = { + Element: Element, + NodeList: NodeList, + SVGElement: SVGElement, + boundary: 'aurelia-dom-boundary', + addEventListener: function addEventListener(eventName, callback, capture) { + document.addEventListener(eventName, callback, capture); + }, + removeEventListener: function removeEventListener(eventName, callback, capture) { + document.removeEventListener(eventName, callback, capture); + }, + adoptNode: function adoptNode(node) { + return document.adoptNode(node); + }, + createAttribute: function createAttribute(name) { + return document.createAttribute(name); + }, + createElement: function createElement(tagName) { + return document.createElement(tagName); + }, + createTextNode: function createTextNode(text) { + return document.createTextNode(text); + }, + createComment: function createComment(text) { + return document.createComment(text); + }, + createDocumentFragment: function createDocumentFragment() { + return document.createDocumentFragment(); + }, + createTemplateElement: function createTemplateElement() { + var template = document.createElement('template'); + return _FEATURE.ensureHTMLTemplateElement(template); + }, + createMutationObserver: function createMutationObserver(callback) { + return new (window.MutationObserver || window.WebKitMutationObserver)(callback); + }, + createCustomEvent: function createCustomEvent(eventType, options) { + return new window.CustomEvent(eventType, options); + }, + dispatchEvent: function dispatchEvent(evt) { + document.dispatchEvent(evt); + }, + getComputedStyle: function getComputedStyle(element) { + return window.getComputedStyle(element); + }, + getElementById: function getElementById(id) { + return document.getElementById(id); + }, + querySelector: function querySelector(query) { + return document.querySelector(query); + }, + querySelectorAll: function querySelectorAll(query) { + return document.querySelectorAll(query); + }, + nextElementSibling: function nextElementSibling(element) { + if (element.nextElementSibling) { + return element.nextElementSibling; + } + do { + element = element.nextSibling; + } while (element && element.nodeType !== 1); + return element; + }, + createTemplateFromMarkup: function createTemplateFromMarkup(markup) { + var parser = document.createElement('div'); + parser.innerHTML = markup; + + var temp = parser.firstElementChild; + if (!temp || temp.nodeName !== 'TEMPLATE') { + throw new Error('Template markup must be wrapped in a