Initial KnockoutSpa template

This commit is contained in:
SteveSandersonMS
2016-03-08 12:16:22 +00:00
parent 7d7e974b5f
commit bbdbb449d5
45 changed files with 2609 additions and 0 deletions

235
templates/KnockoutSpa/.gitignore vendored Normal file
View File

@@ -0,0 +1,235 @@
/Properties/launchSettings.json
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
/wwwroot/dist/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config
# Windows Store app package directory
AppPackages/
BundleArtifacts/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
# FAKE - F# Make
.fake/

View File

@@ -0,0 +1,23 @@
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import './css/site.css';
import * as ko from 'knockout';
import appLayout from './components/app-layout/app-layout';
ko.components.register('app-layout', appLayout);
ko.applyBindings();
// Basic hot reloading support. Automatically reloads and restarts the Knockout app each time
// you modify source files. This will not preserve any application state other than the URL.
declare var module: any;
if (module.hot) {
module.hot.dispose(() => {
ko.cleanNode(document.body);
// TODO: Need a better API for this
Object.getOwnPropertyNames((<any>ko).components._allRegisteredComponents).forEach(componentName => {
ko.components.unregister(componentName);
});
});
module.hot.accept();
}

View File

@@ -0,0 +1,8 @@
<div class='container-fluid'>
<div class='row'>
<div class='col-sm-3'>
<nav-menu params='route: route'></nav-menu>
</div>
<div class='col-sm-9' data-bind='component: { name: route().page, params: route }'></div>
</div>
</div>

View File

@@ -0,0 +1,8 @@
import * as ko from 'knockout';
import * as router from '../../router';
class AppLayoutViewModel {
public route = router.instance().currentRoute;
}
export default { viewModel: AppLayoutViewModel, template: require('./app-layout.html') };

View File

@@ -0,0 +1,7 @@
<h2>Counter</h2>
<p>This is a simple example of a Knockout component.</p>
<p>Current count: <strong data-bind='text: currentCount'></strong></p>
<button data-bind='click: incrementCounter'>Increment</button>

View File

@@ -0,0 +1,12 @@
import * as ko from 'knockout';
class CounterExampleViewModel {
public currentCount = ko.observable(0);
public incrementCounter() {
let prevCount = this.currentCount();
this.currentCount(prevCount + 1);
}
}
export default { viewModel: CounterExampleViewModel, template: require('./counter-example.html') };

View File

@@ -0,0 +1,24 @@
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
<p data-bind='ifnot: forecasts'><em>Loading...</em></p>
<table class='table' data-bind='if: forecasts'>
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody data-bind='foreach: forecasts'>
<tr>
<td data-bind='text: dateFormatted'></td>
<td data-bind='text: temperatureC'></td>
<td data-bind='text: temperatureF'></td>
<td data-bind='text: summary'></td>
</tr>
</tbody>
</table>

View File

@@ -0,0 +1,22 @@
import * as ko from 'knockout';
interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
class FetchDataViewModel {
public forecasts = ko.observableArray<WeatherForecast>();
constructor() {
fetch('/api/SampleData/WeatherForecasts')
.then(response => response.json())
.then((data: WeatherForecast[]) => {
this.forecasts(data);
});
}
}
export default { viewModel: FetchDataViewModel, template: require('./fetch-data.html') };

View File

@@ -0,0 +1,15 @@
<h1>Hello, world!</h1>
<p>Welcome to your new single-page application, built with:</p>
<ul>
<li><a href='https://get.asp.net/'>ASP.NET Core</a> and <a href='https://msdn.microsoft.com/en-us/library/67ef8sbd.aspx'>C#</a> for cross-platform server-side code</li>
<li><a href='http://knockoutjs.com/'>Knockout.js</a> and <a href='http://www.typescriptlang.org/'>TypeScript</a> for client-side code</li>
<li><a href='https://webpack.github.io/'>Webpack</a> for building and bundling client-side resources</li>
<li><a href='http://getbootstrap.com/'>Bootstrap</a> for layout and styling</li>
</ul>
<p>To help you get started, we've also set up:</p>
<ul>
<li><strong>Client-side navigation</strong>. For example, click <em>Counter</em> then <em>Back</em> to return here.</li>
<li><strong>Webpack dev middleware</strong>. In development mode, there's no need to run the <code>webpack</code> build tool. Your client-side resources are dynamically built on demand. Updates are available as soon as you modify any file.</li>
<li><strong>Hot module replacement</strong>. In development mode, you don't even need to reload the page after making most changes. Within seconds of saving changes to files, your Knockout app will be rebuilt and a new instance injected is into the page.</li>
<li><strong>Efficient production builds</strong>. In production mode, development-time features are disabled, and the <code>webpack</code> build tool produces minified static CSS and JavaScript files.</li>
</ul>

View File

@@ -0,0 +1,6 @@
import * as ko from 'knockout';
class HomePageViewModel {
}
export default { viewModel: HomePageViewModel, template: require('./home-page.html') };

View File

@@ -0,0 +1,33 @@
<div class='main-nav'>
<div class='navbar navbar-inverse'>
<div class='navbar-header'>
<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>
<span class='sr-only'>Toggle navigation</span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</button>
<a class='navbar-brand' href='#'>WebApplicationBasic</a>
</div>
<div class='clearfix'></div>
<div class='navbar-collapse collapse'>
<ul class='nav navbar-nav'>
<li>
<a class='navbar-brand' href='#' data-bind='css: { active: route().page === "home-page" }'>
<span class='glyphicon glyphicon-home'></span> Home
</a>
</li>
<li>
<a class='navbar-brand' href='#counter' data-bind='css: { active: route().page === "counter-example" }'>
<span class='glyphicon glyphicon-education'></span> Counter
</a>
</li>
<li>
<a class='navbar-brand' href='#fetch-data' data-bind='css: { active: route().page === "fetch-data" }'>
<span class='glyphicon glyphicon-th-list'></span> Fetch data
</a>
</li>
</ul>
</div>
</div>
</div>

View File

@@ -0,0 +1,19 @@
import * as ko from 'knockout';
import { Route } from '../../router';
interface NavMenuParams {
route: KnockoutObservable<Route>;
}
class NavMenuViewModel {
public route: KnockoutObservable<Route>;
constructor(params: NavMenuParams) {
// This viewmodel doesn't do anything except pass through the 'route' parameter to the view.
// You could remove this viewmodel entirely, and define 'nav-menu' as a template-only component.
// But in most apps, you'll want some viewmodel logic to determine what navigation options appear.
this.route = params.route;
}
}
export default { viewModel: NavMenuViewModel, template: require('./nav-menu.html') };

View File

@@ -0,0 +1,66 @@
.main-nav li .glyphicon {
margin-right: 10px;
}
/* Highlighting rules for nav menu items */
.main-nav li a.active,
.main-nav li a.active:hover,
.main-nav li a.active:focus {
background-color: #4189C7;
color: white;
}
/* Keep the nav menu independent of scrolling and on top of other items */
.main-nav {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 1;
}
@media (max-width: 767px) {
/* On small screens, the nav menu spans the full width of the screen. Leave a space for it. */
body {
padding-top: 50px;
}
}
@media (min-width: 768px) {
/* On small screens, convert the nav menu to a vertical sidebar */
.main-nav {
height: 100%;
width: calc(25% - 20px);
}
.main-nav .navbar {
border-radius: 0px;
border-width: 0px;
height: 100%;
}
.main-nav .navbar-header {
float: none;
}
.main-nav .navbar-collapse {
border-top: 1px solid #444;
padding: 0px;
}
.main-nav .navbar ul {
float: none;
}
.main-nav .navbar li {
float: none;
font-size: 15px;
margin: 6px;
}
.main-nav .navbar li a {
padding: 10px 16px;
border-radius: 4px;
}
.main-nav .navbar a {
/* If a menu item's text is too long, truncate it */
width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}

View File

@@ -0,0 +1,44 @@
import * as ko from 'knockout';
import * as crossroads from 'crossroads';
import * as hasher from 'hasher';
import { routes } from './routes';
// This module configures crossroads.js, a routing library. If you prefer, you
// can use any other routing library (or none at all) as Knockout is designed to
// compose cleanly with external libraries.
//
// You *don't* have to follow the pattern established here (each route entry
// specifies a 'page', which is a Knockout component) - there's nothing built into
// Knockout that requires or even knows about this technique. It's just one of
// many possible ways of setting up client-side routes.
export class Router {
public currentRoute = ko.observable<Route>({});
constructor(routes: Route[]) {
// Configure Crossroads route handlers
routes.forEach(route => {
crossroads.addRoute(route.url, (requestParams) => {
this.currentRoute(ko.utils.extend(requestParams, route.params));
});
});
// Activate Crossroads
crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
hasher.initialized.add(hash => crossroads.parse(hash));
hasher.changed.add(hash => crossroads.parse(hash));
hasher.init();
}
}
export interface Route {
url?: string;
params?: any;
}
export function instance() {
// Ensure there's only one instance. This is needed to support hot module replacement.
const windowOrDefault: any = typeof window === 'undefined' ? {} : window;
windowOrDefault._router = windowOrDefault._router || new Router(routes);
return windowOrDefault._router;
}

View File

@@ -0,0 +1,18 @@
import * as ko from 'knockout';
import { Route } from './router';
import navMenu from './components/nav-menu/nav-menu';
import homePage from './components/home-page/home-page';
import counterExample from './components/counter-example/counter-example';
import fetchData from './components/fetch-data/fetch-data';
ko.components.register('nav-menu', navMenu);
ko.components.register('home-page', homePage);
ko.components.register('counter-example', counterExample);
ko.components.register('fetch-data', fetchData);
export const routes: Route[] = [
{ url: '', params: { page: 'home-page' } },
{ url: 'counter', params: { page: 'counter-example' } },
{ url: 'fetch-data', params: { page: 'fetch-data' } }
];

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace WebApplicationBasic.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
return View();
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace WebApplicationBasic.Controllers
{
[Route("api/[controller]")]
public class SampleDataController : Controller
{
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet, Route("[action]")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
public class WeatherForecast
{
public string DateFormatted { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF
{
get
{
return 32 + (int)(this.TemperatureC / 0.5556);
}
}
}
}
}

View File

@@ -0,0 +1,11 @@
FROM microsoft/aspnet:1.0.0-rc1-update1
RUN printf "deb http://ftp.us.debian.org/debian jessie main\n" >> /etc/apt/sources.list
RUN apt-get -qq update && apt-get install -qqy sqlite3 libsqlite3-dev && rm -rf /var/lib/apt/lists/*
COPY . /app
WORKDIR /app
RUN ["dnu", "restore"]
EXPOSE 5000/tcp
ENTRYPOINT ["dnx", "-p", "project.json", "web"]

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>85231b41-6998-49ae-abd2-5124c83dbef2</ProjectGuid>
<RootNamespace>KnockoutSpa</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\NodeServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\NodeServices.sln\artifacts\bin\$(MSBuildProjectName)\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>2018</DevelopmentServerPort>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@@ -0,0 +1,40 @@
# Welcome to ASP.NET 5
We've made some big updates in this release, so its **important** that you spend a few minutes to learn whats new.
You've created a new ASP.NET 5 project. [Learn what's new](http://go.microsoft.com/fwlink/?LinkId=518016)
## This application consists of:
* Sample pages using ASP.NET MVC 6
* [Gulp](http://go.microsoft.com/fwlink/?LinkId=518007) and [Bower](http://go.microsoft.com/fwlink/?LinkId=518004) for managing client-side libraries
* Theming using [Bootstrap](http://go.microsoft.com/fwlink/?LinkID=398939)
## How to
* [Add a Controller and View](http://go.microsoft.com/fwlink/?LinkID=398600)
* [Add an appsetting in config and access it in app.](http://go.microsoft.com/fwlink/?LinkID=699562)
* [Manage User Secrets using Secret Manager.](http://go.microsoft.com/fwlink/?LinkId=699315)
* [Use logging to log a message.](http://go.microsoft.com/fwlink/?LinkId=699316)
* [Add packages using NuGet.](http://go.microsoft.com/fwlink/?LinkId=699317)
* [Add client packages using Bower.](http://go.microsoft.com/fwlink/?LinkId=699318)
* [Target development, staging or production environment.](http://go.microsoft.com/fwlink/?LinkId=699319)
## Overview
* [Conceptual overview of what is ASP.NET 5](http://go.microsoft.com/fwlink/?LinkId=518008)
* [Fundamentals of ASP.NET 5 such as Startup and middleware.](http://go.microsoft.com/fwlink/?LinkId=699320)
* [Working with Data](http://go.microsoft.com/fwlink/?LinkId=398602)
* [Security](http://go.microsoft.com/fwlink/?LinkId=398603)
* [Client side development](http://go.microsoft.com/fwlink/?LinkID=699321)
* [Develop on different platforms](http://go.microsoft.com/fwlink/?LinkID=699322)
* [Read more on the documentation site](http://go.microsoft.com/fwlink/?LinkID=699323)
## Run & Deploy
* [Run your app](http://go.microsoft.com/fwlink/?LinkID=517851)
* [Run your app on .NET Core](http://go.microsoft.com/fwlink/?LinkID=517852)
* [Run commands in your project.json](http://go.microsoft.com/fwlink/?LinkID=517853)
* [Publish to Microsoft Azure Web Apps](http://go.microsoft.com/fwlink/?LinkID=398609)
We would love to hear your [feedback](http://go.microsoft.com/fwlink/?LinkId=518015)

View File

@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
namespace WebApplicationBasic
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler();
if (env.IsDevelopment())
{
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
// Entry point for the application.
public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args);
}
}

View File

@@ -0,0 +1,9 @@
@{
ViewData["Title"] = "Home Page";
}
<app-layout></app-layout>
@section scripts {
<script src="~/dist/main.js" asp-append-version="true"></script>
}

View File

@@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

View File

@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebApplicationBasic</title>
<link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" />
<environment names="Staging,Production">
<link rel="stylesheet" href="~/dist/site.css" asp-append-version="true" />
</environment>
</head>
<body>
@RenderBody()
<script src="~/dist/vendor.js" asp-append-version="true"></script>
@RenderSection("scripts", required: false)
</body>
</html>

View File

@@ -0,0 +1,3 @@
@using WebApplicationBasic
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "*, Microsoft.AspNet.SpaServices"

View File

@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@@ -0,0 +1,10 @@
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Verbose",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@@ -0,0 +1,28 @@
{
"name": "WebApplicationBasic",
"version": "0.0.0",
"devDependencies": {
"bootstrap": "^3.3.6",
"css-loader": "^0.23.1",
"express": "^4.13.4",
"extendify": "^1.0.0",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.8.5",
"jquery": "^2.2.1",
"raw-loader": "^0.5.1",
"style-loader": "^0.13.0",
"ts-loader": "^0.8.1",
"typescript": "^1.8.2",
"url-loader": "^0.5.7",
"webpack": "^1.12.14",
"webpack-dev-middleware": "^1.5.1",
"webpack-hot-middleware": "^2.7.1"
},
"dependencies": {
"crossroads": "^0.12.2",
"domain-task": "^1.0.0",
"es6-promise": "^3.1.2",
"hasher": "^1.2.0",
"knockout": "^3.4.0"
}
}

View File

@@ -0,0 +1,54 @@
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"tooling": {
"defaultNamespace": "WebApplicationBasic"
},
"dependencies": {
"Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.AspNet.SpaServices": "1.0.0-alpha7-1"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
},
"frameworks": {
"dnx451": {},
"dnxcore50": {}
},
"exclude": [
"wwwroot",
"node_modules",
],
"publishExclude": [
"node_modules",
"**.xproj",
"**.user",
"**.vspscc"
],
"scripts": {
"prepare": [
"npm install",
"webpack --config webpack.config.vendor.js"
],
"prepublish": [
"webpack"
]
}
}

View File

@@ -0,0 +1,11 @@
{
"compilerOptions": {
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"skipDefaultLibCheck": true
},
"exclude": [
"node_modules"
]
}

View File

@@ -0,0 +1,30 @@
{
"version": "v4",
"repo": "borisyankov/DefinitelyTyped",
"ref": "master",
"path": "typings",
"bundle": "typings/tsd.d.ts",
"installed": {
"whatwg-fetch/whatwg-fetch.d.ts": {
"commit": "dade4414712ce84e3c63393f1aae407e9e7e6af7"
},
"crossroads/crossroads.d.ts": {
"commit": "9f0f926a12026287b5a4a229e5672c01e7549313"
},
"js-signals/js-signals.d.ts": {
"commit": "9f0f926a12026287b5a4a229e5672c01e7549313"
},
"hasher/hasher.d.ts": {
"commit": "9f0f926a12026287b5a4a229e5672c01e7549313"
},
"knockout/knockout.d.ts": {
"commit": "9f0f926a12026287b5a4a229e5672c01e7549313"
},
"requirejs/require.d.ts": {
"commit": "9f0f926a12026287b5a4a229e5672c01e7549313"
},
"es6-promise/es6-promise.d.ts": {
"commit": "9f0f926a12026287b5a4a229e5672c01e7549313"
}
}
}

View File

@@ -0,0 +1,159 @@
// Type definitions for Crossroads.js
// Project: http://millermedeiros.github.io/crossroads.js/
// Definitions by: Diullei Gomes <https://github.com/diullei>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../js-signals/js-signals.d.ts" />
declare module CrossroadsJs {
export interface Route {
matched: Signal;
/**
* Signal dispatched every time a request "leaves" the route.
*/
switched: Signal;
/**
* Object used to configure parameters/segments validation rules.
*/
rules: any;
/**
* If crossroads should try to match this Route even after matching another Route.
*/
greedy: boolean;
/**
* Remove route from crossroads and destroy it, releasing memory.
*/
dispose(): void;
/**
* Test if Route matches against request. Return true if request validate against route rules and pattern.
*/
match(request: any): boolean;
/**
* Return a string that matches the route replacing the capturing groups with the values provided in the replacements object.
*/
interpolate(replacements: any): string;
/**
* Add a listener to the signal.
*
* @param listener Signal handler function.
* @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
*/
add(listener: Function, listenerContext?: any, priority?: Number): SignalBinding;
}
export interface CrossRoadsStatic {
NORM_AS_ARRAY: Function;
NORM_AS_OBJECT: Function;
/**
* Creates a new route pattern listener and add it to crossroads routes collection.
*
* @param pattern String pattern or Regular Expression that should be used to match against requests.
* @param handler Function that should be executed when a request matches the Route pattern.
* @param priority Route execution priority.
*/
addRoute(pattern: any, handler?: Function, priority?: number): Route;
/**
* Remove a single route from crossroads collection.
*
* @param route Reference to the Route object returned by crossroads.addRoute().
*/
removeRoute(route: Route): void;
/**
* Remove all routes from crossroads collection.
*/
removeAllRoutes(): void;
/**
* Parse a string input and dispatch matched Signal of the first Route that matches the request.
*
* @param request String that should be evaluated and matched against Routes to define which Route handlers should be executed and which parameters should be passed to the handlers.
* @param defaultargs Array containing values passed to matched/routed/bypassed signals as first arguments. Useful for node.js in case you need to access the request and response objects.
*/
parse(request: string, ...defaultArgs: any[]): void;
/**
* Get number of Routes contained on the crossroads collection.
*/
getNumRoutes(): number;
/**
* Signal dispatched every time that crossroads.parse can't find a Route that matches the request. Useful for debuging and error handling.
*/
bypassed: Signal;
/**
* Signal dispatched every time that crossroads.parse find a Route that matches the request. Useful for debuging and for executing tasks that should happen at each routing.
*/
routed: Signal;
/**
* Create a new independent Router instance.
*/
create(): CrossRoadsStatic;
/**
* Sets a default function that should be used to normalize parameters before passing them to the Route.matched, works similarly to Route.rules.normalize_.
*/
normalizeFn: Function;
/**
* Set if crossroads should typecast route paths. Default value is false (IMPORTANT: on v0.5.0 it was true by default).
*/
shouldTypecast: boolean;
/**
* String representation of the crossroads version number (e.g. "0.6.0").
*/
VERSION: string;
/**
* Sets global route matching behavior to greedy so crossroads will try to match every single route with the supplied request (if true it won't stop at first match).
*/
greedy: boolean;
/**
* Sets if the greedy routes feature is enabled. If false it won't try to match multiple routes (faster).
*/
greedyEnabled: boolean;
/**
* Resets the Router internal state. Will clear reference to previously matched routes (so they won't dispatch switched signal when matching a new route) and reset last request.
*/
resetState(): void;
/**
* Sets if Router should care about previous state, so multiple crossroads.parse() calls passing same argument would not trigger the routed, matched and bypassed signals.
*/
ignoreState: boolean;
/**
* Pipe routers, so all crossroads.parse() calls will be forwarded to the other router as well.
*/
pipe(router: CrossRoadsStatic): void;
/**
* "Ceci n'est pas une pipe"
*/
unpipe(router: CrossRoadsStatic): void;
}
}
declare var crossroads: CrossroadsJs.CrossRoadsStatic;
declare module 'crossroads'{
export = crossroads;
}

View File

@@ -0,0 +1,75 @@
// Type definitions for es6-promise
// Project: https://github.com/jakearchibald/ES6-Promise
// Definitions by: François de Campredon <https://github.com/fdecampredon/>, vvakame <https://github.com/vvakame>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Thenable<T> {
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>;
catch<U>(onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
}
declare class Promise<T> implements Thenable<T> {
/**
* If you call resolve in the body of the callback passed to the constructor,
* your promise is fulfilled with result object passed to resolve.
* If you call reject your promise is rejected with the object passed to reject.
* For consistency and debugging (eg stack traces), obj should be an instanceof Error.
* Any errors thrown in the constructor callback will be implicitly passed to reject().
*/
constructor(callback: (resolve : (value?: T | Thenable<T>) => void, reject: (error?: any) => void) => void);
/**
* onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
* Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
* Both callbacks have a single parameter , the fulfillment value or rejection reason.
* "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
* If an error is thrown in the callback, the returned promise rejects with that error.
*
* @param onFulfilled called when/if "promise" resolves
* @param onRejected called when/if "promise" rejects
*/
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<U>;
/**
* Sugar for promise.then(undefined, onRejected)
*
* @param onRejected called when/if "promise" rejects
*/
catch<U>(onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
}
declare module Promise {
/**
* Make a new promise from the thenable.
* A thenable is promise-like in as far as it has a "then" method.
*/
function resolve<T>(value?: T | Thenable<T>): Promise<T>;
/**
* Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error
*/
function reject(error: any): Promise<any>;
function reject<T>(error: T): Promise<T>;
/**
* Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects.
* the array passed to all can be a mixture of promise-like objects and other objects.
* The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value.
*/
function all<T>(promises: (T | Thenable<T>)[]): Promise<T[]>;
/**
* Make a Promise that fulfills when any item fulfills, and rejects if any item rejects.
*/
function race<T>(promises: (T | Thenable<T>)[]): Promise<T>;
}
declare module 'es6-promise' {
var foo: typeof Promise; // Temp variable to reference Promise in local context
module rsvp {
export var Promise: typeof foo;
}
export = rsvp;
}

View File

@@ -0,0 +1,116 @@
// Type definitions for Hasher.js
// Project: https://github.com/millermedeiros/hasher/
// Definitions by: flyfishMT <https://github.com/flyfishMT/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../js-signals/js-signals.d.ts" />
declare module HasherJs {
export interface HasherStatic {
// {string} hasher.appendHash
// String that should always be added to the end of Hash value.
appendHash(): string;
// default value: '';
// will be automatically removed from `hasher.getHash()`
// avoid conflicts with elements that contain ID equal to hash value;
// <static> {signals.Signal} hasher.changed
// Signal dispatched when hash value changes. - pass current hash as 1st parameter to listeners and previous hash value as 2nd parameter.
changed: Signal;
// <static> {signals.Signal} hasher.initialized
// Signal dispatched when hasher is initialized. - pass current hash as first parameter to listeners.
initialized: Signal;
// <static> {string} hasher.prependHash
// String that should always be added to the beginning of Hash value.
prependHash: string;
// default value: '/';
// will be automatically removed from `hasher.getHash()`
// avoid conflicts with elements that contain ID equal to hash value;
// <static> {string} hasher.separator
// String used to split hash paths; used by hasher.getHashAsArray() to split paths.
separator: string;
// default value: '/';
// <static> {signals.Signal} hasher.stopped
// Signal dispatched when hasher is stopped. - pass current hash as first parameter to listeners
stopped: Signal;
// <static> <constant> {string} hasher.VERSION
// hasher Version Number
VERSION: string;
// Method Detail
// <static> hasher.dispose()
// Removes all event listeners, stops hasher and destroy hasher object. - IMPORTANT: hasher won't work after calling this method, hasher Object will be deleted.
dispose(): void;
// <static> {string} hasher.getBaseURL()
// Returns:
// {string} Retrieve URL without query string and hash.
getBaseURL(): string;
// <static> {string} hasher.getHash()
// Returns:
// {string} Hash value without '#', `hasher.appendHash` and `hasher.prependHash`.
getHash(): string;
// <static> {Array.} hasher.getHashAsArray()
// Returns:
// {Array.} Hash value split into an Array.
getHashAsArray(): string[];
// <static> {string} hasher.getURL()
// Returns:
// {string} Full URL.
getURL(): string;
// <static> hasher.init()
// Start listening/dispatching changes in the hash/history.
init(): void;
// hasher won't dispatch CHANGE events by manually typing a new value or pressing the back/forward buttons before calling this method.
// <static> {boolean} hasher.isActive()
// Returns:
// {boolean} If hasher is listening to changes on the browser history and/or hash value.
isActive(): boolean;
// <static> hasher.replaceHash(path)
// Set Hash value without keeping previous hash on the history record. Similar to calling window.location.replace("#/hash") but will also work on IE6-7.
// hasher.replaceHash('lorem', 'ipsum', 'dolor') -> '#/lorem/ipsum/dolor'
// Parameters:
// {...string} path
// Hash value without '#'. Hasher will join path segments using `hasher.separator` and prepend/append hash value with `hasher.appendHash` and `hasher.prependHash`
replaceHash(...path: string[]): void;
// <static> hasher.setHash(path)
// Set Hash value, generating a new history record.
// hasher.setHash('lorem', 'ipsum', 'dolor') -> '#/lorem/ipsum/dolor'
// Parameters:
// {...string} path
// Hash value without '#'. Hasher will join path segments using `hasher.separator` and prepend/append hash value with `hasher.appendHash` and `hasher.prependHash`
setHash(...path: string[]): void;
// <static> hasher.stop()
// Stop listening/dispatching changes in the hash/history.
// hasher won't dispatch CHANGE events by manually typing a new value or pressing the back/forward buttons after calling this method, unless you call hasher.init() again.
// hasher will still dispatch changes made programatically by calling hasher.setHash();
stop(): void;
// <static> {string} hasher.toString()
// Returns:
// {string} A string representation of the object.
toString(): string;
}
}
declare var hasher: HasherJs.HasherStatic;
// AMD
declare module 'hasher'{
export = hasher;
}

View File

@@ -0,0 +1,110 @@
// Type definitions for JS-Signals
// Project: http://millermedeiros.github.io/js-signals/
// Definitions by: Diullei Gomes <https://github.com/diullei>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var signals: SignalWrapper;
declare module "signals" {
export = signals;
}
interface SignalWrapper {
Signal: Signal
}
interface SignalBinding {
active: boolean;
context: any;
params: any;
detach(): Function;
execute(paramsArr?:any[]): any;
getListener(): Function;
getSignal(): Signal;
isBound(): boolean;
isOnce(): boolean;
}
interface Signal {
/**
* Custom event broadcaster
* <br />- inspired by Robert Penner's AS3 Signals.
* @name Signal
* @author Miller Medeiros
* @constructor
*/
new(): Signal;
/**
* If Signal is active and should broadcast events.
*/
active: boolean;
/**
* If Signal should keep record of previously dispatched parameters and automatically
* execute listener during add()/addOnce() if Signal was already dispatched before.
*/
memorize: boolean;
/**
* Signals Version Number
*/
VERSION: string;
/**
* Add a listener to the signal.
*
* @param listener Signal handler function.
* @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
*/
add(listener: Function, listenerContext?: any, priority?: Number): SignalBinding;
/**
* Add listener to the signal that should be removed after first execution (will be executed only once).
*
* @param listener Signal handler function.
* @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
*/
addOnce(listener: Function, listenerContext?: any, priority?: Number): SignalBinding;
/**
* Dispatch/Broadcast Signal to all listeners added to the queue.
*
* @param params Parameters that should be passed to each handler.
*/
dispatch(...params: any[]): void;
/**
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
*/
dispose(): void;
/**
* Forget memorized arguments.
*/
forget(): void;
/**
* Returns a number of listeners attached to the Signal.
*/
getNumListeners(): number;
/**
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
*/
halt(): void;
/**
* Check if listener was attached to Signal.
*/
has(listener: Function, context?: any): boolean;
/**
* Remove a single listener from the dispatch queue.
*/
remove(listener: Function, context?: any): Function;
removeAll(): void;
}

View File

@@ -0,0 +1,631 @@
// Type definitions for Knockout v3.2.0
// Project: http://knockoutjs.com
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Igor Oleinikov <https://github.com/Igorbek/>, Clément Bourgeois <https://github.com/moonpyk/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface KnockoutSubscribableFunctions<T> {
[key: string]: KnockoutBindingHandler;
notifySubscribers(valueToWrite?: T, event?: string): void;
}
interface KnockoutComputedFunctions<T> {
[key: string]: KnockoutBindingHandler;
}
interface KnockoutObservableFunctions<T> {
[key: string]: KnockoutBindingHandler;
equalityComparer(a: any, b: any): boolean;
}
interface KnockoutObservableArrayFunctions<T> {
// General Array functions
indexOf(searchElement: T, fromIndex?: number): number;
slice(start: number, end?: number): T[];
splice(start: number): T[];
splice(start: number, deleteCount: number, ...items: T[]): T[];
pop(): T;
push(...items: T[]): void;
shift(): T;
unshift(...items: T[]): number;
reverse(): KnockoutObservableArray<T>;
sort(): KnockoutObservableArray<T>;
sort(compareFunction: (left: T, right: T) => number): KnockoutObservableArray<T>;
// Ko specific
[key: string]: KnockoutBindingHandler;
replace(oldItem: T, newItem: T): void;
remove(item: T): T[];
remove(removeFunction: (item: T) => boolean): T[];
removeAll(items: T[]): T[];
removeAll(): T[];
destroy(item: T): void;
destroy(destroyFunction: (item: T) => boolean): void;
destroyAll(items: T[]): void;
destroyAll(): void;
}
interface KnockoutSubscribableStatic {
fn: KnockoutSubscribableFunctions<any>;
new <T>(): KnockoutSubscribable<T>;
}
interface KnockoutSubscription {
dispose(): void;
}
interface KnockoutSubscribable<T> extends KnockoutSubscribableFunctions<T> {
subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription;
subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription;
extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable<T>;
getSubscriptionsCount(): number;
}
interface KnockoutComputedStatic {
fn: KnockoutComputedFunctions<any>;
<T>(): KnockoutComputed<T>;
<T>(func: () => T, context?: any, options?: any): KnockoutComputed<T>;
<T>(def: KnockoutComputedDefine<T>, context?: any): KnockoutComputed<T>;
}
interface KnockoutComputed<T> extends KnockoutObservable<T>, KnockoutComputedFunctions<T> {
fn: KnockoutComputedFunctions<any>;
dispose(): void;
isActive(): boolean;
getDependenciesCount(): number;
extend(requestedExtenders: { [key: string]: any; }): KnockoutComputed<T>;
}
interface KnockoutObservableArrayStatic {
fn: KnockoutObservableArrayFunctions<any>;
<T>(value?: T[]): KnockoutObservableArray<T>;
}
interface KnockoutObservableArray<T> extends KnockoutObservable<T[]>, KnockoutObservableArrayFunctions<T> {
extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray<T>;
}
interface KnockoutObservableStatic {
fn: KnockoutObservableFunctions<any>;
<T>(value?: T): KnockoutObservable<T>;
}
interface KnockoutObservable<T> extends KnockoutSubscribable<T>, KnockoutObservableFunctions<T> {
(): T;
(value: T): void;
peek(): T;
valueHasMutated?:{(): void;};
valueWillMutate?:{(): void;};
extend(requestedExtenders: { [key: string]: any; }): KnockoutObservable<T>;
}
interface KnockoutComputedDefine<T> {
read(): T;
write? (value: T): void;
disposeWhenNodeIsRemoved?: Node;
disposeWhen? (): boolean;
owner?: any;
deferEvaluation?: boolean;
pure?: boolean;
}
interface KnockoutBindingContext {
$parent: any;
$parents: any[];
$root: any;
$data: any;
$rawData: any | KnockoutObservable<any>;
$index?: KnockoutObservable<number>;
$parentContext?: KnockoutBindingContext;
$component: any;
$componentTemplateNodes: Node[];
extend(properties: any): any;
createChildContext(dataItemOrAccessor: any, dataItemAlias?: any, extendCallback?: Function): any;
}
interface KnockoutAllBindingsAccessor {
(): any;
get(name: string): any;
has(name: string): boolean;
}
interface KnockoutBindingHandler {
after?: Array<string>;
init?: (element: any, valueAccessor: () => any, allBindingsAccessor?: KnockoutAllBindingsAccessor, viewModel?: any, bindingContext?: KnockoutBindingContext) => void | { controlsDescendantBindings: boolean; };
update?: (element: any, valueAccessor: () => any, allBindingsAccessor?: KnockoutAllBindingsAccessor, viewModel?: any, bindingContext?: KnockoutBindingContext) => void;
options?: any;
preprocess?: (value: string, name: string, addBindingCallback?: (name: string, value: string) => void) => string;
}
interface KnockoutBindingHandlers {
[bindingHandler: string]: KnockoutBindingHandler;
// Controlling text and appearance
visible: KnockoutBindingHandler;
text: KnockoutBindingHandler;
html: KnockoutBindingHandler;
css: KnockoutBindingHandler;
style: KnockoutBindingHandler;
attr: KnockoutBindingHandler;
// Control Flow
foreach: KnockoutBindingHandler;
if: KnockoutBindingHandler;
ifnot: KnockoutBindingHandler;
with: KnockoutBindingHandler;
// Working with form fields
click: KnockoutBindingHandler;
event: KnockoutBindingHandler;
submit: KnockoutBindingHandler;
enable: KnockoutBindingHandler;
disable: KnockoutBindingHandler;
value: KnockoutBindingHandler;
textInput: KnockoutBindingHandler;
hasfocus: KnockoutBindingHandler;
checked: KnockoutBindingHandler;
options: KnockoutBindingHandler;
selectedOptions: KnockoutBindingHandler;
uniqueName: KnockoutBindingHandler;
// Rendering templates
template: KnockoutBindingHandler;
// Components (new for v3.2)
component: KnockoutBindingHandler;
}
interface KnockoutMemoization {
memoize(callback: () => string): string;
unmemoize(memoId: string, callbackParams: any[]): boolean;
unmemoizeDomNodeAndDescendants(domNode: any, extraCallbackParamsArray: any[]): boolean;
parseMemoText(memoText: string): string;
}
interface KnockoutVirtualElement {}
interface KnockoutVirtualElements {
allowedBindings: { [bindingName: string]: boolean; };
emptyNode(node: KnockoutVirtualElement ): void;
firstChild(node: KnockoutVirtualElement ): KnockoutVirtualElement;
insertAfter( container: KnockoutVirtualElement, nodeToInsert: Node, insertAfter: Node ): void;
nextSibling(node: KnockoutVirtualElement): Node;
prepend(node: KnockoutVirtualElement, toInsert: Node ): void;
setDomNodeChildren(node: KnockoutVirtualElement, newChildren: { length: number;[index: number]: Node; } ): void;
childNodes(node: KnockoutVirtualElement ): Node[];
}
interface KnockoutExtenders {
throttle(target: any, timeout: number): KnockoutComputed<any>;
notify(target: any, notifyWhen: string): any;
rateLimit(target: any, timeout: number): any;
rateLimit(target: any, options: { timeout: number; method?: string; }): any;
trackArrayChanges(target: any): any;
}
//
// NOTE TO MAINTAINERS AND CONTRIBUTORS : pay attention to only include symbols that are
// publicly exported in the minified version of ko, without that you can give the false
// impression that some functions will be available in production builds.
//
interface KnockoutUtils {
//////////////////////////////////
// utils.domData.js
//////////////////////////////////
domData: {
get (node: Element, key: string): any;
set (node: Element, key: string, value: any): void;
getAll(node: Element, createIfNotFound: boolean): any;
clear(node: Element): boolean;
};
//////////////////////////////////
// utils.domNodeDisposal.js
//////////////////////////////////
domNodeDisposal: {
addDisposeCallback(node: Element, callback: Function): void;
removeDisposeCallback(node: Element, callback: Function): void;
cleanNode(node: Node): Element;
removeNode(node: Node): void;
};
addOrRemoveItem<T>(array: T[] | KnockoutObservable<T>, value: T, included: T): void;
arrayFilter<T>(array: T[], predicate: (item: T) => boolean): T[];
arrayFirst<T>(array: T[], predicate: (item: T) => boolean, predicateOwner?: any): T;
arrayForEach<T>(array: T[], action: (item: T, index: number) => void): void;
arrayGetDistinctValues<T>(array: T[]): T[];
arrayIndexOf<T>(array: T[], item: T): number;
arrayMap<T, U>(array: T[], mapping: (item: T) => U): U[];
arrayPushAll<T>(array: T[] | KnockoutObservableArray<T>, valuesToPush: T[]): T[];
arrayRemoveItem(array: any[], itemToRemove: any): void;
compareArrays<T>(a: T[], b: T[]): Array<KnockoutArrayChange<T>>;
extend(target: Object, source: Object): Object;
fieldsIncludedWithJsonPost: any[];
getFormFields(form: any, fieldName: string): any[];
objectForEach(obj: any, action: (key: any, value: any) => void): void;
parseHtmlFragment(html: string): any[];
parseJson(jsonString: string): any;
postJson(urlOrForm: any, data: any, options: any): void;
peekObservable<T>(value: KnockoutObservable<T>): T;
range(min: any, max: any): any;
registerEventHandler(element: any, eventType: any, handler: Function): void;
setHtml(node: Element, html: () => string): void;
setHtml(node: Element, html: string): void;
setTextContent(element: any, textContent: string | KnockoutObservable<string>): void;
stringifyJson(data: any, replacer?: Function, space?: string): string;
toggleDomNodeCssClass(node: any, className: string, shouldHaveClass: boolean): void;
triggerEvent(element: any, eventType: any): void;
unwrapObservable<T>(value: KnockoutObservable<T> | T): T;
// NOT PART OF THE MINIFIED API SURFACE (ONLY IN knockout-{version}.debug.js) https://github.com/SteveSanderson/knockout/issues/670
// forceRefresh(node: any): void;
// ieVersion: number;
// isIe6: boolean;
// isIe7: boolean;
// jQueryHtmlParse(html: string): any[];
// makeArray(arrayLikeObject: any): any[];
// moveCleanedNodesToContainerElement(nodes: any[]): HTMLElement;
// replaceDomNodes(nodeToReplaceOrNodeArray: any, newNodesArray: any[]): void;
// setDomNodeChildren(domNode: any, childNodes: any[]): void;
// setElementName(element: any, name: string): void;
// setOptionNodeSelectionState(optionNode: any, isSelected: boolean): void;
// simpleHtmlParse(html: string): any[];
// stringStartsWith(str: string, startsWith: string): boolean;
// stringTokenize(str: string, delimiter: string): string[];
// stringTrim(str: string): string;
// tagNameLower(element: any): string;
}
interface KnockoutArrayChange<T> {
status: string;
value: T;
index: number;
moved?: number;
}
//////////////////////////////////
// templateSources.js
//////////////////////////////////
interface KnockoutTemplateSourcesDomElement {
text(): any;
text(value: any): void;
data(key: string): any;
data(key: string, value: any): any;
}
interface KnockoutTemplateAnonymous extends KnockoutTemplateSourcesDomElement {
nodes(): any;
nodes(value: any): void;
}
interface KnockoutTemplateSources {
domElement: {
prototype: KnockoutTemplateSourcesDomElement
new (element: Element): KnockoutTemplateSourcesDomElement
};
anonymousTemplate: {
prototype: KnockoutTemplateAnonymous;
new (element: Element): KnockoutTemplateAnonymous;
};
}
//////////////////////////////////
// nativeTemplateEngine.js
//////////////////////////////////
interface KnockoutNativeTemplateEngine {
renderTemplateSource(templateSource: Object, bindingContext?: KnockoutBindingContext, options?: Object): any[];
}
//////////////////////////////////
// templateEngine.js
//////////////////////////////////
interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine {
createJavaScriptEvaluatorBlock(script: string): string;
makeTemplateSource(template: any, templateDocument?: Document): any;
renderTemplate(template: any, bindingContext: KnockoutBindingContext, options: Object, templateDocument: Document): any;
isTemplateRewritten(template: any, templateDocument: Document): boolean;
rewriteTemplate(template: any, rewriterCallback: Function, templateDocument: Document): void;
}
/////////////////////////////////
interface KnockoutStatic {
utils: KnockoutUtils;
memoization: KnockoutMemoization;
bindingHandlers: KnockoutBindingHandlers;
getBindingHandler(handler: string): KnockoutBindingHandler;
virtualElements: KnockoutVirtualElements;
extenders: KnockoutExtenders;
applyBindings(viewModelOrBindingContext?: any, rootNode?: any): void;
applyBindingsToDescendants(viewModelOrBindingContext: any, rootNode: any): void;
applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, bindingContext: KnockoutBindingContext): void;
applyBindingAccessorsToNode(node: Node, bindings: {}, bindingContext: KnockoutBindingContext): void;
applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, viewModel: any): void;
applyBindingAccessorsToNode(node: Node, bindings: {}, viewModel: any): void;
applyBindingsToNode(node: Node, bindings: any, viewModelOrBindingContext?: any): any;
subscribable: KnockoutSubscribableStatic;
observable: KnockoutObservableStatic;
computed: KnockoutComputedStatic;
pureComputed<T>(evaluatorFunction: () => T, context?: any): KnockoutComputed<T>;
pureComputed<T>(options: KnockoutComputedDefine<T>, context?: any): KnockoutComputed<T>;
observableArray: KnockoutObservableArrayStatic;
contextFor(node: any): any;
isSubscribable(instance: any): boolean;
toJSON(viewModel: any, replacer?: Function, space?: any): string;
toJS(viewModel: any): any;
isObservable(instance: any): boolean;
isWriteableObservable(instance: any): boolean;
isComputed(instance: any): boolean;
dataFor(node: any): any;
removeNode(node: Element): void;
cleanNode(node: Element): Element;
renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any;
renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any;
unwrap<T>(value: KnockoutObservable<T> | T): T;
computedContext: KnockoutComputedContext;
//////////////////////////////////
// templateSources.js
//////////////////////////////////
templateSources: KnockoutTemplateSources;
//////////////////////////////////
// templateEngine.js
//////////////////////////////////
templateEngine: {
prototype: KnockoutTemplateEngine;
new (): KnockoutTemplateEngine;
};
//////////////////////////////////
// templateRewriting.js
//////////////////////////////////
templateRewriting: {
ensureTemplateIsRewritten(template: Node, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any;
ensureTemplateIsRewritten(template: string, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any;
memoizeBindingAttributeSyntax(htmlString: string, templateEngine: KnockoutTemplateEngine): any;
applyMemoizedBindingsToNextSibling(bindings: any, nodeName: string): string;
};
//////////////////////////////////
// nativeTemplateEngine.js
//////////////////////////////////
nativeTemplateEngine: {
prototype: KnockoutNativeTemplateEngine;
new (): KnockoutNativeTemplateEngine;
instance: KnockoutNativeTemplateEngine;
};
//////////////////////////////////
// jqueryTmplTemplateEngine.js
//////////////////////////////////
jqueryTmplTemplateEngine: {
prototype: KnockoutTemplateEngine;
renderTemplateSource(templateSource: Object, bindingContext: KnockoutBindingContext, options: Object): Node[];
createJavaScriptEvaluatorBlock(script: string): string;
addTemplate(templateName: string, templateMarkup: string): void;
};
//////////////////////////////////
// templating.js
//////////////////////////////////
setTemplateEngine(templateEngine: KnockoutNativeTemplateEngine): void;
renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any;
renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any;
renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any;
renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any;
renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any;
renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any;
renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any;
renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any;
renderTemplateForEach(template: Function, arrayOrObservableArray: any[], options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any;
renderTemplateForEach(template: any, arrayOrObservableArray: any[], options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any;
renderTemplateForEach(template: Function, arrayOrObservableArray: KnockoutObservable<any>, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any;
renderTemplateForEach(template: any, arrayOrObservableArray: KnockoutObservable<any>, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any;
expressionRewriting: {
bindingRewriteValidators: any;
parseObjectLiteral: { (objectLiteralString: string): any[] }
};
/////////////////////////////////
bindingProvider: {
instance: KnockoutBindingProvider;
new (): KnockoutBindingProvider;
}
/////////////////////////////////
// selectExtensions.js
/////////////////////////////////
selectExtensions: {
readValue(element: HTMLElement): any;
writeValue(element: HTMLElement, value: any): void;
};
components: KnockoutComponents;
}
interface KnockoutBindingProvider {
nodeHasBindings(node: Node): boolean;
getBindings(node: Node, bindingContext: KnockoutBindingContext): {};
getBindingAccessors?(node: Node, bindingContext: KnockoutBindingContext): { [key: string]: string; };
}
interface KnockoutComputedContext {
getDependenciesCount(): number;
isInitial: () => boolean;
isSleeping: boolean;
}
//
// refactored types into a namespace to reduce global pollution
// and used Union Types to simplify overloads (requires TypeScript 1.4)
//
declare module KnockoutComponentTypes {
interface Config {
viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule;
template: string | Node[]| DocumentFragment | TemplateElement | AMDModule;
synchronous?: boolean;
}
interface ComponentConfig {
viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule;
template: any;
createViewModel?: any;
}
interface EmptyConfig {
}
// common AMD type
interface AMDModule {
require: string;
}
// viewmodel types
interface ViewModelFunction {
(params?: any): any;
}
interface ViewModelSharedInstance {
instance: any;
}
interface ViewModelFactoryFunction {
createViewModel: (params?: any, componentInfo?: ComponentInfo) => any;
}
interface ComponentInfo {
element: Node;
templateNodes: Node[];
}
interface TemplateElement {
element: string | Node;
}
interface Loader {
getConfig? (componentName: string, callback: (result: ComponentConfig) => void): void;
loadComponent? (componentName: string, config: ComponentConfig, callback: (result: Definition) => void): void;
loadTemplate? (componentName: string, templateConfig: any, callback: (result: Node[]) => void): void;
loadViewModel? (componentName: string, viewModelConfig: any, callback: (result: any) => void): void;
suppressLoaderExceptions?: boolean;
}
interface Definition {
template: Node[];
createViewModel? (params: any, options: { element: Node; }): any;
}
}
interface KnockoutComponents {
// overloads for register method:
register(componentName: string, config: KnockoutComponentTypes.Config | KnockoutComponentTypes.EmptyConfig): void;
isRegistered(componentName: string): boolean;
unregister(componentName: string): void;
get(componentName: string, callback: (definition: KnockoutComponentTypes.Definition) => void): void;
clearCachedDefinition(componentName: string): void
defaultLoader: KnockoutComponentTypes.Loader;
loaders: KnockoutComponentTypes.Loader[];
getComponentNameForNode(node: Node): string;
}
declare var ko: KnockoutStatic;
declare module "knockout" {
export = ko;
}

View File

@@ -0,0 +1,397 @@
// Type definitions for RequireJS 2.1.20
// Project: http://requirejs.org/
// Definitions by: Josh Baldwin <https://github.com/jbaldwin/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/*
require-2.1.8.d.ts may be freely distributed under the MIT license.
Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/require.d.ts
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.
*/
declare module 'module' {
var mod: {
config: () => any;
id: string;
uri: string;
}
export = mod;
}
interface RequireError extends Error {
/**
* The error ID that maps to an ID on a web page.
**/
requireType: string;
/**
* Required modules.
**/
requireModules: string[];
/**
* The original error, if there is one (might be null).
**/
originalError: Error;
}
interface RequireShim {
/**
* List of dependencies.
**/
deps?: string[];
/**
* Name the module will be exported as.
**/
exports?: string;
/**
* Initialize function with all dependcies passed in,
* if the function returns a value then that value is used
* as the module export value instead of the object
* found via the 'exports' string.
* @param dependencies
* @return
**/
init?: (...dependencies: any[]) => any;
}
interface RequireConfig {
// The root path to use for all module lookups.
baseUrl?: string;
// Path mappings for module names not found directly under
// baseUrl.
paths?: { [key: string]: any; };
// Dictionary of Shim's.
// does not cover case of key->string[]
shim?: { [key: string]: RequireShim; };
/**
* For the given module prefix, instead of loading the
* module with the given ID, substitude a different
* module ID.
*
* @example
* requirejs.config({
* map: {
* 'some/newmodule': {
* 'foo': 'foo1.2'
* },
* 'some/oldmodule': {
* 'foo': 'foo1.0'
* }
* }
* });
**/
map?: {
[id: string]: {
[id: string]: string;
};
};
/**
* Allows pointing multiple module IDs to a module ID that contains a bundle of modules.
*
* @example
* requirejs.config({
* bundles: {
* 'primary': ['main', 'util', 'text', 'text!template.html'],
* 'secondary': ['text!secondary.html']
* }
* });
**/
bundles?: { [key: string]: string[]; };
/**
* AMD configurations, use module.config() to access in
* define() functions
**/
config?: { [id: string]: {}; };
/**
* Configures loading modules from CommonJS packages.
**/
packages?: {};
/**
* The number of seconds to wait before giving up on loading
* a script. The default is 7 seconds.
**/
waitSeconds?: number;
/**
* A name to give to a loading context. This allows require.js
* to load multiple versions of modules in a page, as long as
* each top-level require call specifies a unique context string.
**/
context?: string;
/**
* An array of dependencies to load.
**/
deps?: string[];
/**
* A function to pass to require that should be require after
* deps have been loaded.
* @param modules
**/
callback?: (...modules: any[]) => void;
/**
* If set to true, an error will be thrown if a script loads
* that does not call define() or have shim exports string
* value that can be checked.
**/
enforceDefine?: boolean;
/**
* If set to true, document.createElementNS() will be used
* to create script elements.
**/
xhtml?: boolean;
/**
* Extra query string arguments appended to URLs that RequireJS
* uses to fetch resources. Most useful to cache bust when
* the browser or server is not configured correctly.
*
* @example
* urlArgs: "bust= + (new Date()).getTime()
**/
urlArgs?: string;
/**
* Specify the value for the type="" attribute used for script
* tags inserted into the document by RequireJS. Default is
* "text/javascript". To use Firefox's JavasScript 1.8
* features, use "text/javascript;version=1.8".
**/
scriptType?: string;
/**
* If set to true, skips the data-main attribute scanning done
* to start module loading. Useful if RequireJS is embedded in
* a utility library that may interact with other RequireJS
* library on the page, and the embedded version should not do
* data-main loading.
**/
skipDataMain?: boolean;
/**
* Allow extending requirejs to support Subresource Integrity
* (SRI).
**/
onNodeCreated?: (node: HTMLScriptElement, config: RequireConfig, moduleName: string, url: string) => void;
}
// todo: not sure what to do with this guy
interface RequireModule {
/**
*
**/
config(): {};
}
/**
*
**/
interface RequireMap {
/**
*
**/
prefix: string;
/**
*
**/
name: string;
/**
*
**/
parentMap: RequireMap;
/**
*
**/
url: string;
/**
*
**/
originalName: string;
/**
*
**/
fullName: string;
}
interface Require {
/**
* Configure require.js
**/
config(config: RequireConfig): Require;
/**
* CommonJS require call
* @param module Module to load
* @return The loaded module
*/
(module: string): any;
/**
* Start the main app logic.
* Callback is optional.
* Can alternatively use deps and callback.
* @param modules Required modules to load.
**/
(modules: string[]): void;
/**
* @see Require()
* @param ready Called when required modules are ready.
**/
(modules: string[], ready: Function): void;
/**
* @see http://requirejs.org/docs/api.html#errbacks
* @param ready Called when required modules are ready.
**/
(modules: string[], ready: Function, errback: Function): void;
/**
* Generate URLs from require module
* @param module Module to URL
* @return URL string
**/
toUrl(module: string): string;
/**
* Returns true if the module has already been loaded and defined.
* @param module Module to check
**/
defined(module: string): boolean;
/**
* Returns true if the module has already been requested or is in the process of loading and should be available at some point.
* @param module Module to check
**/
specified(module: string): boolean;
/**
* On Error override
* @param err
**/
onError(err: RequireError, errback?: (err: RequireError) => void): void;
/**
* Undefine a module
* @param module Module to undefine.
**/
undef(module: string): void;
/**
* Semi-private function, overload in special instance of undef()
**/
onResourceLoad(context: Object, map: RequireMap, depArray: RequireMap[]): void;
}
interface RequireDefine {
/**
* Define Simple Name/Value Pairs
* @param config Dictionary of Named/Value pairs for the config.
**/
(config: { [key: string]: any; }): void;
/**
* Define function.
* @param func: The function module.
**/
(func: () => any): void;
/**
* Define function with dependencies.
* @param deps List of dependencies module IDs.
* @param ready Callback function when the dependencies are loaded.
* callback param deps module dependencies
* callback return module definition
**/
(deps: string[], ready: Function): void;
/**
* Define module with simplified CommonJS wrapper.
* @param ready
* callback require requirejs instance
* callback exports exports object
* callback module module
* callback return module definition
**/
(ready: (require: Require, exports: { [key: string]: any; }, module: RequireModule) => any): void;
/**
* Define a module with a name and dependencies.
* @param name The name of the module.
* @param deps List of dependencies module IDs.
* @param ready Callback function when the dependencies are loaded.
* callback deps module dependencies
* callback return module definition
**/
(name: string, deps: string[], ready: Function): void;
/**
* Define a module with a name.
* @param name The name of the module.
* @param ready Callback function when the dependencies are loaded.
* callback return module definition
**/
(name: string, ready: Function): void;
/**
* Used to allow a clear indicator that a global define function (as needed for script src browser loading) conforms
* to the AMD API, any global define function SHOULD have a property called "amd" whose value is an object.
* This helps avoid conflict with any other existing JavaScript code that could have defined a define() function
* that does not conform to the AMD API.
* define.amd.jQuery is specific to jQuery and indicates that the loader is able to account for multiple version
* of jQuery being loaded simultaneously.
*/
amd: Object;
}
// Ambient declarations for 'require' and 'define'
declare var requirejs: Require;
declare var require: Require;
declare var define: RequireDefine;

View File

@@ -0,0 +1,7 @@
/// <reference path="crossroads/crossroads.d.ts" />
/// <reference path="hasher/hasher.d.ts" />
/// <reference path="js-signals/js-signals.d.ts" />
/// <reference path="knockout/knockout.d.ts" />
/// <reference path="requirejs/require.d.ts" />
/// <reference path="whatwg-fetch/whatwg-fetch.d.ts" />
/// <reference path="es6-promise/es6-promise.d.ts" />

View File

@@ -0,0 +1,85 @@
// Type definitions for fetch API
// Project: https://github.com/github/fetch
// Definitions by: Ryan Graham <https://github.com/ryan-codingintrigue>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class Request extends Body {
constructor(input: string|Request, init?:RequestInit);
method: string;
url: string;
headers: Headers;
context: string|RequestContext;
referrer: string;
mode: string|RequestMode;
credentials: string|RequestCredentials;
cache: string|RequestCache;
}
interface RequestInit {
method?: string;
headers?: HeaderInit|{ [index: string]: string };
body?: BodyInit;
mode?: string|RequestMode;
credentials?: string|RequestCredentials;
cache?: string|RequestCache;
}
declare enum RequestContext {
"audio", "beacon", "cspreport", "download", "embed", "eventsource", "favicon", "fetch",
"font", "form", "frame", "hyperlink", "iframe", "image", "imageset", "import",
"internal", "location", "manifest", "object", "ping", "plugin", "prefetch", "script",
"serviceworker", "sharedworker", "subresource", "style", "track", "video", "worker",
"xmlhttprequest", "xslt"
}
declare enum RequestMode { "same-origin", "no-cors", "cors" }
declare enum RequestCredentials { "omit", "same-origin", "include" }
declare enum RequestCache { "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached" }
declare class Headers {
append(name: string, value: string): void;
delete(name: string):void;
get(name: string): string;
getAll(name: string): Array<string>;
has(name: string): boolean;
set(name: string, value: string): void;
}
declare class Body {
bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
formData(): Promise<FormData>;
json(): Promise<any>;
json<T>(): Promise<T>;
text(): Promise<string>;
}
declare class Response extends Body {
constructor(body?: BodyInit, init?: ResponseInit);
error(): Response;
redirect(url: string, status: number): Response;
type: string|ResponseType;
url: string;
status: number;
ok: boolean;
statusText: string;
headers: Headers;
clone(): Response;
}
declare enum ResponseType { "basic", "cors", "default", "error", "opaque" }
interface ResponseInit {
status: number;
statusText?: string;
headers?: HeaderInit;
}
declare type HeaderInit = Headers|Array<string>;
declare type BodyInit = Blob|FormData|string;
declare type RequestInfo = Request|string;
interface Window {
fetch(url: string|Request, init?: RequestInit): Promise<Response>;
}
declare var fetch: typeof window.fetch;

View File

@@ -0,0 +1,8 @@
module.exports = {
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /\.css/, loader: 'style!css' }
]
}
};

View File

@@ -0,0 +1,32 @@
var path = require('path');
var webpack = require('webpack');
var merge = require('extendify')({ isDeep: true, arrays: 'concat' });
var devConfig = require('./webpack.config.dev');
var prodConfig = require('./webpack.config.prod');
var isDevelopment = process.env.ASPNET_ENV === 'Development';
module.exports = merge({
resolve: {
extensions: [ '', '.js', '.ts' ]
},
module: {
loaders: [
{ test: /\.ts(x?)$/, include: /ClientApp/, loader: 'ts-loader' },
{ test: /\.html$/, loader: 'raw-loader' }
]
},
entry: {
main: ['./ClientApp/boot.ts'],
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
filename: '[name].js',
publicPath: '/dist/'
},
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
]
}, isDevelopment ? devConfig : prodConfig);

View File

@@ -0,0 +1,16 @@
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('site.css');
module.exports = {
module: {
loaders: [
{ test: /\.css/, loader: extractCSS.extract(['css']) },
]
},
plugins: [
extractCSS,
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
]
};

View File

@@ -0,0 +1,36 @@
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');
var isDevelopment = process.env.ASPNET_ENV === 'Development';
module.exports = {
resolve: {
extensions: [ '', '.js' ]
},
module: {
loaders: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' },
{ test: /\.css/, loader: extractCSS.extract(['css']) }
]
},
entry: {
vendor: ['bootstrap', 'bootstrap/dist/css/bootstrap.css', 'knockout', 'crossroads', 'hasher', 'style-loader', 'jquery'],
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
filename: '[name].js',
library: '[name]_[hash]',
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevelopment ? [] : [
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
])
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
</handlers>
<httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false"/>
</system.webServer>
</configuration>