Merge pull request #2 from seawerst/requirejs

Requirejs
This commit is contained in:
Marc
2016-09-19 15:25:11 -04:00
committed by GitHub
123 changed files with 23001 additions and 6920 deletions
+1
View File
@@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii)
* [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000)
* [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped)
* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped)
* [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak)
* [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT)
@@ -0,0 +1,31 @@
/// <reference path="angular-feature-flags.d.ts" />
let myApp = angular.module('myApp', ['feature-flags']);
const flagsData: Array<angular.featureflags.FlagData> = [
{
key: '1',
active: true,
name: 'flag1',
description: 'This is the first flag'
},
{
key: '2',
active: false,
name: 'flag2',
description: 'This is the second flag'
}
];
myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) {
featureFlagsProvider.setInitialFlags(flagsData);
});
myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) {
let deferred = $q.defer();
deferred.resolve(flagsData);
featureFlags.set(deferred.promise);
featureFlags.set($http.get('/data/flags.json'));
});
+38
View File
@@ -0,0 +1,38 @@
// Type definitions for angular-feature-flags 1.4.0
// Project: https://github.com/mjt01/angular-feature-flags
// Definitions by: Borislav Zhivkov <https://github.com/borislavjivkov/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare namespace angular.featureflags {
export interface FlagData {
/**
* Unique key that is used from the markup to resolve whether a flag is active or not.
*/
key: string;
/**
* Boolean value for enabling/disabling the feature
*/
active: boolean;
/**
* A short name of the flag (only visible in the list of flags)
*/
name: string;
/**
* A long description of the flag to further explain the feature being toggled (only visible in the list of flags)
*/
description: string;
}
export interface FeatureFlagsProvider {
setInitialFlags(flags: Array<FlagData>): void;
}
export interface FeatureFlagsService {
set(flagsPromise: angular.IPromise<FlagData> | angular.IHttpPromise<FlagData>): void;
}
}
+4 -1
View File
@@ -132,7 +132,10 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!'));
$scope['openToast'] = () => {
$mdToast.show($mdToast.simple().textContent('Hello!'));
$mdToast.updateTextContent('New Content');
}
$scope['customToast'] = () => {
var options = {
+2 -1
View File
@@ -177,7 +177,8 @@ declare namespace angular.material {
showSimple(content: string): angular.IPromise<any>;
simple(): ISimpleToastPreset;
build(): IToastPreset<any>;
updateContent(): void;
updateContent(newContent: string): void;
updateTextContent(newContent: string): void
hide(response?: any): void;
cancel(response?: any): void;
}
+11
View File
@@ -400,6 +400,17 @@ declare namespace angular.ui.bootstrap {
* @default 'body'
*/
appendTo?: angular.IAugmentedJQuery;
/**
* A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set.
*
* It supports these bindings:
* - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}`
* - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}`
* - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`.
* - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details.
*/
component?: string;
}
interface IModalStackService {
+3 -2
View File
@@ -42,9 +42,10 @@ declare namespace angular.ui {
*/
topVisibleScope: ng.IRepeatScope;
/**
* calling this method reinitializes and reloads the scroller content.
* calling this method reinitializes and reloads the scroller content.
* @param startIndex is an integer indicating what item index the scroller will use to start the load process.
*/
reload(): void;
reload(startIndex?: number): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
+14 -3
View File
@@ -42,15 +42,20 @@ declare namespace angular.resource {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<IResource<any>>;
actions?: IActionHash, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): U;
actions?: IActionHash, options?: IResourceOptions): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<T>;
actions?: IActionHash, options?: IResourceOptions): IResourceClass<T>;
}
// Hash of action descriptors allows custom action names
interface IActionHash {
[action: string]: IActionDescriptor
}
// Just a reference to facilitate describing new actions
@@ -186,6 +191,12 @@ declare namespace angular {
/** creating a resource service factory */
factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction<any>): IModule;
}
namespace auto {
interface IInjectorService {
get(name: '$resource'): ng.resource.IResourceService;
}
}
}
interface Array<T>
+6
View File
@@ -946,9 +946,14 @@ declare namespace AtomCore {
registry: any;
repository: Object;
scopeName: string;
tokenizeLines: (text: string) => any;
// TBD
}
interface IGrammars {
grammarForScopeName(scope: string): IGrammar;
}
interface IPane /* extends Theorist.Model */ {
itemForURI: (uri:string)=>IEditor;
@@ -1302,6 +1307,7 @@ declare namespace AtomCore {
deserializers:IDeserializerManager;
config: IConfig;
commands: ICommandRegistry;
grammars: IGrammars;
keymaps: IKeymapManager;
keymap: IKeymapManager;
packages: IPackageManager;
+1 -1
View File
@@ -92,7 +92,7 @@ interface Auth0LockConstructorOptions {
initialScreen?: "login" | "signUp" | "forgotPassword";
language?: string;
languageDictionary?: any;
loginAfterSignup?: boolean;
loginAfterSignUp?: boolean;
mustAcceptTerms?: boolean;
popupOptions?: Auth0LockPopupOptions;
prefill?: { email?: string, username?: string};
+5
View File
@@ -236,6 +236,11 @@ declare module "aws-sdk" {
listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void;
listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void;
waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
uploadPart(params: any, callback: (err: Error, data: any) => void): void;
listParts(params: any, callback: (err: Error, data: any) => void): void;
completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
}
export class STS {
+91
View File
@@ -0,0 +1,91 @@
/// <reference path="axe-core.d.ts" />
var context:any = document
var $fixture:any = {}
// axe.a11yCheck config
axe.a11yCheck(context, {}, (results) => {
// axe's results object
console.log(results.passes.length)
console.log(results.violations.length)
});
// axe.a11yCheck include/exclude
axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => {
console.log(results)
})
axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => {
console.log(results)
})
var tagConfigRunOnly: axe.RunOnly = {
type: 'tag',
values: ['wcag2a']
}
var tagConfig = {
runOnly: tagConfigRunOnly
}
axe.a11yCheck(context, tagConfig, (results) => {
console.log(results)
})
var includeExcludeTagsRunOnly: axe.RunOnly = {
type: 'tags',
value: {
include: ['wcag2a', 'wcag2aa'],
exclude: ['experimental']
}
}
var includeExcludeTagsConfig = {
runOnly: includeExcludeTagsRunOnly
}
axe.a11yCheck(context, includeExcludeTagsConfig, (results) => {
console.log(results)
})
var someRulesConfig = {
rules: {
"color-contrast": {enabled: 'false'},
"heading-order": {enabled: 'true'}
}
}
axe.a11yCheck(context, someRulesConfig, (results) => {
console.log(results)
})
// axe.configure
var spec: axe.Spec = {
branding: {
brand: 'foo',
application: 'bar'
},
reporter: 'v1',
checks: [{
id: 'custom-check',
evaluate: function() {
return true
}
}],
rules: [{
id: 'custom-rule',
any: ['custom-check']
}]
}
axe.configure(spec)
axe.reset()
axe.getRules(['wcag2aa'])
typeof axe.getRules() === 'object'
// Plugins
var pluginSrc: axe.AxePlugin = {
id: 'doStuff',
run: (data:any, callback:Function) => {
callback()
},
commands: [{
id: 'run-doStuff',
callback: (data:any, callback:Function) => {
axe.plugins['doStuff'].run(data, callback)
}
}]
}
axe.registerPlugin(pluginSrc)
axe.cleanup()
+159
View File
@@ -0,0 +1,159 @@
// Type definitions for axe-core 2.0.5
// Project: https://github.com/dequelabs/axe-core
// Definitions by: Marcy Sutton <https://github.com/marcysutton>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace axe {
export type ImpactValue = "minor" | "moderate" | "serious" | "critical";
export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice";
export type ReporterVersion = "v1" | "v2";
export type RunOnlyType = "rule" | "rules" | "tag" | "tags";
export interface ElementContext {
node?: Object,
selector?: string,
include?: any[],
exclude?: any[]
}
export interface RunOnly {
type: RunOnlyType,
value?: {
include?: string[],
exclude?: string[]
}
values?: TagValue[]
}
export interface AxeResults {
url: string,
timestamp: string,
passes: Pass[],
violations: Violation[]
}
export interface Pass {
description: string,
help: string,
helpUrl: string,
id: string,
impact: ImpactValue,
tags: TagValue[],
nodes: NodeResult[]
}
export interface Violation {
description: string,
help: string,
helpUrl: string,
id: string,
impact: ImpactValue,
tags: TagValue[],
nodes: NodeResult[]
}
export interface NodeResult {
html: string,
impact: ImpactValue,
target: string[],
any: CheckResult[],
all: CheckResult[],
none: CheckResult[]
}
export interface CheckResult {
id: string,
impact: string,
message: string,
data: any,
relatedNodes?: RelatedNode[]
}
export interface RelatedNode {
target: string[],
html: string
}
export interface Spec {
branding?: {
brand: string,
application: string
},
reporter?: ReporterVersion,
checks?: Check[],
rules?: Rule[]
}
export interface Check {
id: string,
evaluate: Function,
after?: Function,
options?: any,
matches?: string,
enabled?: boolean
}
export interface Rule {
id: string,
selector?: string,
excludeHidden?: boolean,
enabled?: boolean,
pageLevel?: boolean,
any?: string[],
all?: string[],
none?: string[],
tags?: string[],
matches?: string
}
export interface AxePlugin {
id: string,
run(...args:any[]): any,
commands: {
id: string,
callback(...args:any[]): void
}[],
cleanup?(callback:Function): void
}
export let plugins: any
/**
* Starts analysis on the current document and its subframes
*
* @param {Object} context The `Context` specification object @see Context
* @param {Array} options Options passed into rules or checks, temporarily modifyint them.
* @param {Function} callback The function to invoke when analysis is complete.
* @returns {Object} results The aXe results object
*/
export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults
/**
* Method for configuring the data format used by aXe. Helpful for adding new
* rules, which must be registered with the library to execute.
* @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data
*/
export function configure(spec: Spec): void
/**
* Searches and returns rules that contain a tag in the list of tags.
* @param {Array} tags Optional array of tags
* @return {Array} Array of rules
*/
export function getRules(tags?: string[]): Object[]
/**
* Restores the default axe configuration
*/
export function reset(): void
/**
* Function to register a plugin configuration in document and its subframes
* @param {Object} plugin A plugin configuration object
*/
export function registerPlugin(plugin: AxePlugin): void
/**
* Function to clean up plugin configuration in document and its subframes
*/
export function cleanup(): void
}
// axe is also available as a module
declare module "axe-core" {
export = axe;
}
@@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]);
table.read.use(function () {}, function () {});
table.use(function () {}).use(function () {}).read(function () {}).use(function () {})
table.access = undefined;
table.access = 'authenticated';
table.read.access = 'anonymous';
table.update.access = 'disabled';
table.delete.access = 'authenticated';
table.insert.access = 'authenticated';
// Express.Table, instantiated from the static require('azure-mobile-apps').table()
// This is going to be interesting if we ever support more than one provider
var table2 = mobileApps.table();
+4
View File
@@ -47,6 +47,7 @@ declare namespace Azure.MobileApps {
interface Table {
authorize?: boolean;
access?: AccessType;
autoIncrement?: boolean;
dynamicSchema?: boolean;
name: string;
@@ -66,8 +67,11 @@ declare namespace Azure.MobileApps {
(operationHandler: (context: Context) => void): Table;
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
access: AccessType;
}
type AccessType = 'anonymous' | 'authenticated' | 'disabled';
interface Tables {
configuration: Configuration;
add(name: string, definition?: Table | TableDefinition): void;
+36
View File
@@ -0,0 +1,36 @@
/// <reference path="bunnymq.d.ts"/>
import * as bunnymq from "bunnymq";
// Basic usage
var instance = bunnymq({ host: 'amqp://localhost' });
// Publisher
instance.producer.produce('queue:name', 'Hello World!');
// Subscriber
instance.consumer.consume('queue:name', message => { });
// RPC Support
instance.producer.produce('queue:name', { message: 'content' }, { rpc: true })
.then(function (consumerResponse) {
console.log(consumerResponse);
});
// Routing keys
instance.producer.produce('queue:name', { message: 'content' }, { routingKey: 'my-routing-key' });
// Config
var custom = bunnymq({
host: 'amqp://localhost',
//number of fetched messages at once on the channel
prefetch: 5,
//requeue put back message into the broker if consumer crashes/trigger exception
requeue: true,
//time between two reconnect (ms)
timeout: 1000,
consumerSuffix: '',
//generate a hostname so we can track this connection on the broker (rabbitmq management plugin)
hostname: "",
//the transport to use to debug. if provided, bunnymq will show some logs
transport: new Object()
});
+120
View File
@@ -0,0 +1,120 @@
// Type definitions for node-bunnymq 2.2.1
// Project: https://github.com/dial-once/node-bunnymq
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "bunnymq" {
namespace bunnymq {
export type ConsumerCallback = (message: Object) => void;
/**
* Consumer.
* @interface
*/
export interface Consumer {
/**
* Handle messages from a named queue.
* @param {string} queue A named queue.
* @param {ConsumerCallback} callback A callback.
*/
consume(queue: string, callback: ConsumerCallback): void;
}
/**
* bunnymq instance.
* @interface
*/
export interface Instance {
/**
* Consumer.
* @type {Consumer}
*/
consumer: Consumer;
/**
* Producer.
* @type {Producer}
*/
producer: Producer;
}
/**
* Options.
* @interface
*/
export interface Options {
/**
* Consumer suffix.
* @type {string}
*/
consumerSuffix?: string;
/**
* Host.
* @type {string}
*/
host?: string;
/**
* Hostname.
* @type {string}
*/
hostname?: string;
/**
* Number of fetched messages at once on the channel.
* @type {number}
*/
prefetch?: number;
/**
* Requeue put back message into the broker if consumer crashes/trigger exception.
* @type {boolean}
*/
requeue?: boolean;
/**
* Time between two reconnect (in milliseconds).
* @type {number}
*/
timeout?: number;
/**
* Transport.
* @type {any}
*/
transport?: any;
}
/**
* Producer.
* @inteface
*/
export interface Producer {
/**
* Send messages to a named queue.
* @param {string} queue A named queue.
* @param {Object} message A message.
* @return {Object} The consumer response.
*/
produce(queue: string, message: Object, options?: ProducerOptions): PromiseLike<Object>;
}
/**
* Options for producer.
* @interface
*/
export interface ProducerOptions {
routingKey?: string;
rpc?: boolean;
}
}
/**
* Constructor.
* @param {Options} [options] Options.
* @return {Instance} A instance of bunnymq.
*/
function bunnymq(options?: bunnymq.Options): bunnymq.Instance;
export = bunnymq;
}
+39
View File
@@ -0,0 +1,39 @@
/// <reference path="busboy.d.ts"/>
/// <reference path="../node/node.d.ts" />
import * as Busboy from 'busboy';
import * as http from 'http';
import * as util from 'util';
function serverFn(req: http.ServerRequest, res: http.ServerResponse) {
if (req.method === 'POST') {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data: Buffer) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + util.inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end('<html><head></head><body>\
<form method="POST" enctype="multipart/form-data">\
<input type="text" name="textfield"><br />\
<input type="file" name="filefield"><br />\
<input type="submit">\
</form>\
</body></html>');
}
}
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for busboy v0.2.13
// Project: https://www.npmjs.com/package/busboy
// Definitions by: Jacob Baskin <https://github.com/jacobbaskin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare namespace busboy {
interface Options {
headers: any;
}
interface BusboyConfig {
headers?: any;
highWaterMark?: number;
fileHwm?: number;
defCharset?: string;
preservePath?: boolean;
limits?: {
fieldNameSize?: number;
fieldSize?: number;
fields?: number;
fileSize?: number;
files?: number;
parts?: number;
headerPairs?: number;
};
}
interface Busboy extends NodeJS.WritableStream {
on(event: 'field',
listener: (
fieldname: string,
val: any,
fieldnameTruncated: boolean,
valTruncated: boolean,
encoding: string,
mimetype: string) => void): this;
on(event: 'file',
listener: (
fieldname: string,
file: NodeJS.ReadableStream,
filename: string,
encoding: string,
mimetype: string) => void): this;
on(event: 'finish', callback: () => void): this;
on(event: 'partsLimit', callback: () => void): this;
on(event: 'filesLimit', callback: () => void): this;
on(event: 'fieldsLimit', callback: () => void): this;
on(event: string, listener: Function): this;
}
interface BusboyConstructor {
new (options: BusboyConfig): Busboy;
}
}
declare module 'busboy' {
const temp: busboy.BusboyConstructor;
export = temp;
}
Vendored
+1 -1
View File
@@ -681,7 +681,7 @@ declare namespace c3 {
* Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge.
* If undefined returned, the row of that value will be skipped.
*/
value?: (name: string, ratio: number, id: string, index: number) => string;
value?: (value: any, ratio: number, id: string, index: number) => string;
};
/**
* Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left.
+20
View File
@@ -0,0 +1,20 @@
/// <reference path="canvas-gauges.d.ts" />
import {
LinearGaugeOptions,
RadialGaugeOptions,
LinearGauge,
RadialGauge
} from 'canvas-gauges';
let linearOptions: LinearGaugeOptions = {
renderTo: document.createElement('canvas')
};
let radialOptions: RadialGaugeOptions = {
renderTo: 'gauge-id'
};
new LinearGauge(linearOptions);
new RadialGauge(radialOptions);
console.log(document.gauges.length);
+263
View File
@@ -0,0 +1,263 @@
// Type definitions for canvas-gauges
// Project: https://github.com/Mikhus/canvas-gauges
// Definitions by: Mikhus <https://github.com/Mikhus>
// Definitions: https://github.com/Mikhus/DefinitelyTyped
declare namespace CanvasGauges {
export type RenderTarget = string|HTMLElement;
export interface AnimationRule {
(percent: number): number;
}
export interface Highlight {
from: number,
to: number,
color: string
}
export type MajorTicks = string[]|number[];
export interface GenericOptions {
renderTo: RenderTarget,
width?: number,
height?: number,
minValue?: number,
maxValue?: number,
value?: number,
units?: string|boolean,
majorTicks?: MajorTicks,
minorTicks?: number,
strokeTicks?: boolean,
animatedValue?: boolean,
title?: string|boolean,
borders?: boolean,
valueInt?: number,
valueDec?: number,
majorTicksInt?: number,
majorTicksDec?: number,
animation?: boolean,
animationDuration?: number,
animationRule?: string|AnimationRule,
colorPlate?: string,
colorMajorTicks?: string,
colorMinorTicks?: string,
colorTitle?: string,
colorUnits?: string,
colorNumbers?: string,
colorNeedle?: string,
colorNeedleEnd?: string,
colorValueText?: string,
colorValueTextShadow?: string,
colorBorderShadow?: string,
colorBorderOuter?: string,
colorBorderOuterEnd?: string,
colorBorderMiddle?: string,
colorBorderMiddleEnd?: string,
colorBorderInner?: string,
colorBorderInnerEnd?: string,
colorValueBoxRect?: string,
colorValueBoxRectEnd?: string,
colorValueBoxBackground?: string,
colorValueBoxShadow?: string,
colorNeedleShadowUp?: string,
colorNeedleShadowDown?: string,
needle?: boolean,
needleShadow?: boolean,
needleType?: string,
needleStart?: number,
needleEnd?: number,
needleWidth?: number,
borderOuterWidth?: number,
borderMiddleWidth?: number,
borderInnerWidth?: number,
borderShadowWidth?: number,
valueBox?: boolean,
valueBoxStroke?: number,
valueText?: string,
valueTextShadow?: boolean,
valueBoxBorderRadius?: number,
highlights?: Highlight[],
fontNumbers?: string,
fontTitle?: string,
fontUnits?: string,
fontValue?: string,
fontTitleSize?: number,
fontValueSize?: number,
fontUnitsSize?: number,
fontNumbersSize?: number
}
export interface RadialGaugeOptions extends GenericOptions {
ticksAngle?: number,
startAngle?: number,
colorNeedleCircleOuter?: string,
colorNeedleCircleOuterEnd?: string,
colorNeedleCircleInner?: string,
colorNeedleCircleInnerEnd?: string,
needleCircleSize?: number,
needleCircleInner?: boolean,
needleCircleOuter?: boolean,
animationTarget?: string
}
export interface LinearGaugeOptions extends GenericOptions {
borderRadius?: number,
barBeginCircle?: number,
barWidth?: number,
barStrokeWidth?: number,
barProgress?: boolean,
colorBar?: string,
colorBarEnd?: string,
colorBarStroke?: string,
colorBarProgress?: string,
colorBarProgressEnd?: string,
tickSide?: string,
needleSide?: string,
numberSide?: string,
ticksWidth?: number,
ticksWidthMinor?: number,
ticksPadding?: number,
barLength?: number
}
export interface DrawEventCallback {
(percent: number): any;
}
export interface EndEventCallback {
(): any;
}
export interface rules {
linear: AnimationRule,
quad: AnimationRule,
dequad: AnimationRule,
quint: AnimationRule,
dequint: AnimationRule,
cycle: AnimationRule,
decycle: AnimationRule,
bounce: AnimationRule,
debounce: AnimationRule,
elastic: AnimationRule,
delastic: AnimationRule
}
export class Animation {
public duration: number;
public rule: string|AnimationRule;
public draw: DrawEventCallback;
public end: EndEventCallback;
public static rules: rules;
constructor(rule?: string|AnimationRule, duration?: number,
draw?: DrawEventCallback, end?: EndEventCallback);
public animate(draw?: DrawEventCallback, end?: EndEventCallback): any;
public destroy(): any;
}
export class SmartCanvas {
public element: HTMLCanvasElement;
public elementClone: HTMLCanvasElement;
public context: CanvasRenderingContext2D;
public contextClone: CanvasRenderingContext2D;
public drawWidth: number;
public drawHeight: number;
public drawX: number;
public drawY: number;
public minSide: number;
public width: number;
public height: number;
constructor(element: HTMLCanvasElement,
width?: number,
height?: number);
public init(): any;
public onRedraw(): any;
public destroy(): any;
public commit(): SmartCanvas;
public redraw(): SmartCanvas;
public pixelRatio: number;
public static redraw(): any;
public static collection: Array<SmartCanvas>;
}
export class DomObserver {
public Type: BaseGauge;
public mutationsObserved: boolean;
public isObservable: boolean;
public options: GenericOptions;
public element: string;
public type: string;
constructor(options: GenericOptions,
element: string,
type: string);
public isValidNode(node: Node|HTMLElement): boolean;
public traverse(): any;
public observe(records: MutationRecord[]): any;
public process(node: Node|HTMLElement): BaseGauge;
public static parse(value: any): any;
public static toDashed(camelCase: string): string;
public static toAttributeName(str: string): string;
static domReady(handler: Function): any;
}
export abstract class BaseGauge {
public type: BaseGauge;
public options: GenericOptions;
public canvas: SmartCanvas;
public animation: Animation;
public value: number;
constructor(options: GenericOptions);
public update(options: GenericOptions): BaseGauge;
public destroy(): any;
public abstract draw(): BaseGauge;
public static initialize(type: string, options: GenericOptions): any;
}
export class RadialGauge extends BaseGauge {
public type: RadialGauge;
public options: RadialGaugeOptions;
constructor(options: RadialGaugeOptions);
public draw(): RadialGauge;
}
export class LinearGauge extends BaseGauge {
public type: LinearGauge;
public options: LinearGaugeOptions;
constructor(options: LinearGaugeOptions);
public draw(): LinearGauge;
}
export interface Collection extends Array<BaseGauge> {
get: (id: number | string) => BaseGauge;
}
}
declare module 'canvas-gauges' {
export = CanvasGauges;
}
interface Document {
gauges: CanvasGauges.Collection;
}
interface Window {
BaseGauge: CanvasGauges.BaseGauge;
RadialGauge: CanvasGauges.RadialGauge;
LinearGauge: CanvasGauges.LinearGauge;
}
+8
View File
@@ -114,8 +114,16 @@ declare namespace Chance {
capitalize(str: string): string;
mixin(desc: MixinDescriptor): any;
pad(num: number, width: number, padChar?: string): string;
/**
* @deprecated Use pickone
*/
pick<T>(arr: T[]): T;
pickone<T>(arr: T[]): T;
/**
* @deprecated Use pickset
*/
pick<T>(arr: T[], count: number): T[];
pickset<T>(arr: T[], count: number): T[];
set: Setter;
shuffle<T>(arr: T[]): T[];
+124
View File
@@ -0,0 +1,124 @@
/// <reference path="change-emitter.d.ts"/>
import { createChangeEmitter, ChangeEmitterOf0 } from "change-emitter";
function usage() {
// https://github.com/acdlite/change-emitter#usage
const emitter = createChangeEmitter()
// Called `listen` instead of `subscribe` to avoid confusion with observable spec
const unlisten = emitter.listen((...args) => {
console.log(args)
})
emitter.emit(1, 2, 3) // logs `[1, 2, 3]`
unlisten()
emitter.emit(4, 5, 6) // doesn't log
}
function largerExample() {
// https://github.com/acdlite/change-emitter#larger-example
const createStore = (reducer: Function, initialState: any) => {
let state = initialState
const emitter = createChangeEmitter()
function dispatch(action: any) {
state = reducer(state, action)
emitter.emit()
return action
}
function getState() {
return state
}
return {
dispatch,
getState,
subscribe: emitter.listen
}
}
}
function untypedEmitter() {
const { emit, listen } = createChangeEmitter();
const unlisten0 = listen(() => {/* do something */});
const unlisten1 = listen(value => {/* do something with value */});
const unlisten2 = listen((value1, value2) => {/* do something with values */});
const unlistenArgs = listen((...args: any[]) => {/* do something with values */});
emit();
emit("hello");
emit("hello", "world");
emit(1, 2, 3, 4, 5);
unlisten0();
unlisten1();
unlisten2();
unlistenArgs();
}
function emitterOf0Args() {
const { emit, listen }: ChangeEmitterOf0 = createChangeEmitter();
const unlisten = listen(() => { });
// const unlisten = listen(value => {}); // SYNTAX ERROR
emit();
// emit("hello"); // SYNTAX ERROR
unlisten();
}
function emitterOf1Args() {
const { emit, listen } = createChangeEmitter<string>();
const unlisten = listen(value => { value.length });
emit("hello");
unlisten();
}
function emitterOf2Args() {
const { emit, listen } = createChangeEmitter<string, boolean>();
const unlisten = listen((value, success) => { value.length > 0 === success });
emit("hello", true);
unlisten();
}
function emitterOf3Args() {
const { emit, listen } = createChangeEmitter<string, boolean, number>();
const unlisten = listen((value, success, count) => { value.length > count === success });
emit("hello", true, 3);
unlisten();
}
function emitterOf4Args() {
const { emit, listen } = createChangeEmitter<string, boolean, number, Date>();
const unlisten = listen((v1, v2, v3, v4) => { });
emit("hello", true, 3, new Date());
unlisten();
}
function emitterOf5Args() {
const { emit, listen } = createChangeEmitter<string, boolean, number, Date, string>();
const unlisten = listen((v1, v2, v3, v4, v5) => { });
emit("hello", true, 3, new Date(), "world");
unlisten();
}
+58
View File
@@ -0,0 +1,58 @@
// Type definitions for change-emitter v0.1.2
// Project: https://github.com/acdlite/change-emitter
// Definitions by: Iskander Sierra <https://github.com/iskandersierra>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'change-emitter' {
type Unlisten = () => void;
type Listener = (...args: any[]) => void;
type ListenerOf0 = () => void;
type ListenerOf1<T> = (value: T) => void;
type ListenerOf2<T1, T2> = (value1: T1, value2: T2) => void;
type ListenerOf3<T1, T2, T3> = (value1: T1, value2: T2, value3: T3) => void;
type ListenerOf4<T1, T2, T3, T4> = (value1: T1, value2: T2, value3: T3, value4: T4) => void;
type ListenerOf5<T1, T2, T3, T4, T5> = (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => void;
interface ChangeEmitter {
listen(listener: Listener): Unlisten;
emit(...args: any[]): void;
}
interface ChangeEmitterOf1<T> {
listen(listener: ListenerOf1<T>): Unlisten;
emit(value: T): void;
}
interface ChangeEmitterOf0 {
listen(listener: ListenerOf0): Unlisten;
emit(): void;
}
interface ChangeEmitterOf2<T1, T2> {
listen(listener: ListenerOf2<T1, T2>): Unlisten;
emit(value1: T1, value2: T2): void;
}
interface ChangeEmitterOf3<T1, T2, T3> {
listen(listener: ListenerOf3<T1, T2, T3>): Unlisten;
emit(value1: T1, value2: T2, value3: T3): void;
}
interface ChangeEmitterOf4<T1, T2, T3, T4> {
listen(listener: ListenerOf4<T1, T2, T3, T4>): Unlisten;
emit(value1: T1, value2: T2, value3: T3, value4: T4): void;
}
interface ChangeEmitterOf5<T1, T2, T3, T4, T5> {
listen(listener: ListenerOf5<T1, T2, T3, T4, T5>): Unlisten;
emit(value1: T1, value2: T2, value3: T3, value4: T4, value5: T5): void;
}
export function createChangeEmitter(): ChangeEmitter;
export function createChangeEmitter<T>(): ChangeEmitterOf1<T>;
export function createChangeEmitter<T1, T2>(): ChangeEmitterOf2<T1, T2>;
export function createChangeEmitter<T1, T2, T3>(): ChangeEmitterOf3<T1, T2, T3>;
export function createChangeEmitter<T1, T2, T3, T4>(): ChangeEmitterOf4<T1, T2, T3, T4>;
export function createChangeEmitter<T1, T2, T3, T4, T5>(): ChangeEmitterOf5<T1, T2, T3, T4, T5>;
}
+1 -1
View File
@@ -73,7 +73,7 @@ interface ChartOptions {
onClick?: (any?: any) => any;
title?: ChartTitleOptions;
legend?: ChartLegendOptions;
tooltip?: ChartTooltipOptions;
tooltips?: ChartTooltipOptions;
hover?: ChartHoverOptions;
animation?: ChartAnimationOptions;
elements?: ChartElementsOptions;
+2
View File
@@ -8,9 +8,11 @@ colors.enabled = true;
console.log(colors.black.underline('test'));
console.log(colors.rainbow.black.blue.gray('test'));
console.log(colors.random.reset.bgWhite.dim('test'));
console.log(colors.random.reset.bgWhite.strip('test'));
console.log('test'.black.underline);
console.log('test'.rainbow.black.blue.gray);
console.log('test'.random.reset.bgWhite.dim);
console.log('test'.random.reset.bgWhite.dim.stripColors);
colors.enabled = false;
+9
View File
@@ -7,6 +7,9 @@ declare module "colors" {
interface Color {
(text: string): string;
strip: Color;
stripColors: Color;
black: Color;
red: Color;
green: Color;
@@ -49,6 +52,9 @@ declare module "colors" {
export var enabled: boolean;
export var strip: Color;
export var stripColors: Color;
export var black: Color;
export var red: Color;
export var green: Color;
@@ -90,6 +96,9 @@ declare module "colors" {
}
interface String {
strip: string;
stripColors: string;
black: string;
red: string;
green: string;
+5
View File
@@ -0,0 +1,5 @@
/// <reference path="./concaveman.d.ts" />
import * as concaveman from 'concaveman';
var points = [[10, 20], [30, 12.5]];
var polygon = concaveman(points);
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for concaveman 1.1.0
// Project: https://github.com/mapbox/concaveman
// Definitions by: Denis Carriere <https://github.com/DenisCarriere>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "concaveman" {
/**
* A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set).
*
* @name concaveman
* @param {Array<Array<number>>} points is an array of [x, y] points.
* @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes.
* @param {number} [lengthThreshold=0] when a segment length is under this threshold, it stops being considered for further detalization. Higher values result in simpler shapes.
* @return {Array<Array<number>>}
* @example
* var points = [[10, 20], [30, 12.5], ...];
* var polygon = concaveman(points);
*
* //=hull
*/
function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][];
namespace concaveman {}
export = concaveman;
}
+2 -2
View File
@@ -1889,7 +1889,7 @@ declare module "core-js/fn/number/max-safe-integer" {
var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER;
export = MAX_SAFE_INTEGER;
}
declare module "core-js/fn/number/min-safe-interger" {
declare module "core-js/fn/number/min-safe-integer" {
var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER;
export = MIN_SAFE_INTEGER;
}
@@ -2668,7 +2668,7 @@ declare module "core-js/library/fn/number/max-safe-integer" {
var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER;
export = MAX_SAFE_INTEGER;
}
declare module "core-js/library/fn/number/min-safe-interger" {
declare module "core-js/library/fn/number/min-safe-integer" {
var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER;
export = MIN_SAFE_INTEGER;
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="date-fns.d.ts" />
import {addDays, closestIndexTo, differenceInCalendarWeeks, max, isDate} from 'date-fns';
import * as addHours from 'date-fns/add_hours';
function test() {
addDays(new Date(), 5);
closestIndexTo(new Date(), [new Date(), new Date()]);
addHours(new Date(), 5);
differenceInCalendarWeeks(new Date(), new Date());
differenceInCalendarWeeks(new Date(), new Date(), {weekStartsOn: 1});
max(new Date(), new Date());
isDate({});
}
+1195
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -650,6 +650,7 @@ declare namespace createjs {
autoReset: boolean;
static buildDate: string;
currentFrame: number;
totalFrames: number;
currentLabel: string;
frameBounds: Rectangle[];
framerate: number;
@@ -662,6 +663,7 @@ declare namespace createjs {
startPosition: number;
static SYNCHED: string;
timeline: Timeline;
duration: number;
static version: string;
// methods
+40
View File
@@ -45,4 +45,44 @@ client.create({
index: 'index',
type: 'type'
}, (err, repsonse, status) => {
});
client.cluster.getSettings({
masterTimeout: 100
}, (err, response) => {
});
client.cluster.health({
masterTimeout: 100
}, (err, response) => {
});
client.cluster.pendingTasks({
ignore: 1
}, (err, response) => {
});
client.cluster.putSettings({
ignore: 1
}, (err, response) => {
});
client.cluster.putSettings({
ignore: 1
}, (err, response) => {
});
client.cluster.reroute({
ignore: 1
}, (err, response) => {
});
client.cluster.state({
ignore: 1
}, (err, response) => {
});
client.cluster.stats({
ignore: 1
}, (err, response) => {
});
+104 -7
View File
@@ -1,26 +1,28 @@
// Type definitions for elasticsearch
// Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
// Definitions by: Casper Skydt <https://github.com/CasperSkydt/DefinitelyTyped>
// Definitions by: Casper Skydt <https://github.com/CasperSkydt>, Blake Smith <https://github.com/bfsmith>, Dave Dunkin <https://github.com/ddunkin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module Elasticsearch {
export class Client {
constructor(params: ConfigOptions);
indices: Indices;
cluster: Cluster;
cat: Cat;
bulk(params: BulkIndexDocumentsParams): PromiseLike<any>;
bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void;
create(params: CreateDocumentParams): PromiseLike<any>;
create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void;
delete(params: DeleteDocumentParams): PromiseLike<any>;
delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void;
get(params: GetParams, callback: (error: any, response: any) => void): void;
get<T>(params: GetParams, callback: (error: any, response: GetResponse<T>) => void): void;
get<T>(params: GetParams): PromiseLike<GetResponse<T>>;
index<T>(params: IndexDocumentParams<T>): PromiseLike<any>;
index<T>(params: IndexDocumentParams<T>, callback: (error: any, response: any) => void): void;
mget(params: MGetParams, callback: (error: any, response: any) => void): void;
mget<T>(params: MGetParams): PromiseLike<GetResponse<T>>;
msearch(params: MSearchParams, callback: (error: any, response: any) => void): void;
msearch<T>(params: MSearchParams): PromiseLike<GetResponse<T>>;
mget<T>(params: MGetParams, callback: (error: any, response: MGetResponse<T>) => void): void;
mget<T>(params: MGetParams): PromiseLike<MGetResponse<T>>;
msearch<T>(params: MSearchParams, callback: (error: any, response: MSearchResponse<T>) => void): void;
msearch<T>(params: MSearchParams): PromiseLike<MSearchResponse<T>>;
ping(params: PingParams): PromiseLike<any>;
ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void;
scroll(params: ScrollParams): PromiseLike<any>;
@@ -194,7 +196,8 @@ declare module Elasticsearch {
versionType?: string;
}
export interface GetResponse<T> extends GenericParams {
export interface GetResponse<T> {
_index: string;
_type: string;
_id: string;
_version: number;
@@ -230,6 +233,7 @@ declare module Elasticsearch {
scroll?: string;
search_type?: string;
fields?: string[];
from?: number;
size?: number;
sort?: string | string[] | boolean;
_source?: string | string[] | boolean;
@@ -276,6 +280,10 @@ declare module Elasticsearch {
search_type?: string;
}
export interface MSearchResponse<T> {
responses?: SearchResponse<T>[];
}
export interface MGetParams extends GenericParams {
fields?: string | string[] | Boolean;
preference?: string;
@@ -287,6 +295,10 @@ declare module Elasticsearch {
type?: string;
}
export interface MGetResponse<T> {
docs?: GetResponse<T>[];
}
export interface IndicesIndexExitsParams extends GenericParams {
index: string | string[] | boolean;
ignoreUnavailable?: boolean;
@@ -333,6 +345,91 @@ declare module Elasticsearch {
body: string | any;
index: string | string[] | boolean;
}
export interface Cat {
health(params: CatHealthOptions, callback: (error: any, response: any) => void): void;
health(params: CatHealthOptions): PromiseLike<any>
}
export interface CatHealthOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
h?: string | string[] | boolean;
help?: boolean;
ts?: boolean;
v?: boolean;
}
export interface Cluster {
getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void;
getSettings(params: ClusterGetSettingsOptions): PromiseLike<any>;
health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void;
health(params: ClusterHealthOptions): PromiseLike<any>;
pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void;
pendingTasks(params: ClusterPendingTasksOptions): PromiseLike<any>;
putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void;
putSettings(params: ClusterPutSettingsOptions): PromiseLike<any>;
reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void;
reroute(params: ClusterRerouteOptions): PromiseLike<any>;
state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void;
state(params: ClusterStateOptions): PromiseLike<any>;
stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void;
stats(params: ClusterStatsOptions): PromiseLike<any>;
}
export interface ClusterGetSettingsOptions extends GenericParams {
flatSettings?: boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterHealthOptions extends GenericParams {
level?: string; // cluster, indices, shards
local?: boolean;
masterTimeout?: number | Date;
waitForActiveShards?: number;
waitForNodes?: string;
waitForRelocatingShards?: number;
waitForStatus?: string; // green, yellow, red
index?: string | string[] | boolean;
}
export interface ClusterPendingTasksOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
}
export interface ClusterPutSettingsOptions extends GenericParams {
flatSettings?: boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterRerouteOptions extends GenericParams {
dryRun?: boolean;
explain?: boolean;
metric?: string | string[] | boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterStateOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
flatSettings?: boolean;
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
expandWildcards?: string; // open, closed, none, all (default open)
index?: string | string[] | boolean;
metric?: string | string[] | boolean;
}
export interface ClusterStatsOptions extends GenericParams {
flatSettings?: boolean;
human?: boolean;
timeout?: number | Date;
nodeId?: string | string[] | boolean;
}
}
declare module "elasticsearch" {
+1
View File
@@ -458,6 +458,7 @@ declare module "enzyme" {
export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
unmount(): ReactWrapper<any, any>;
mount(): ReactWrapper<any, any>;
render(): CheerioWrapper<P, S>;
/**
* Returns a wrapper of the node that matches the provided reference name.
@@ -1046,6 +1046,11 @@ declare module "express-serve-static-core" {
* simply by removing them from this object.
*/
routes: any;
/**
* Using to all registered routes in Express Application
*/
_router: any;
}
interface Express extends Application {
+96 -83
View File
@@ -1,101 +1,114 @@
/// <reference path="express.d.ts" />
/// <reference path="../node/node.d.ts" />
import * as express from 'express';
var app = express();
app.engine('jade', require('jade').__express);
app.engine('html', require('ejs').renderFile);
express.static.mime.define({
'application/fx': ['fx']
});
app.use('/static', express.static(__dirname + '/public'));
// simple logger
app.use(function(req, res, next){
console.log('%s %s', req.method, req.url);
next();
});
app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
console.error(err);
next(err);
});
app.get('/', function(req, res){
res.send('hello world');
});
namespace express_tests {
const router = express.Router();
var app = express();
app.engine('jade', require('jade').__express);
app.engine('html', require('ejs').renderFile);
const pathStr : string = 'test';
const pathRE : RegExp = /test/;
const path = true? pathStr : pathRE;
express.static.mime.define({
'application/fx': ['fx']
});
app.use('/static', express.static(__dirname + '/public'));
router.get(path);
router.put(path)
router.post(path);
router.delete(path);
router.get(pathStr);
router.put(pathStr)
router.post(pathStr);
router.delete(pathStr);
router.get(pathRE);
router.put(pathRE)
router.post(pathRE);
router.delete(pathRE);
router.use((req, res, next) => { next(); })
router.route('/users')
.get((req, res, next) => {
let types: string[] = req.accepts();
let type: string | boolean = req.accepts('json');
type = req.accepts(['json', 'text']);
type = req.accepts('json', 'text');
let charsets: string[] = req.acceptsCharsets();
let charset: string | boolean = req.acceptsCharsets('utf-8');
charset = req.acceptsCharsets(['utf-8', 'utf-16']);
charset = req.acceptsCharsets('utf-8', 'utf-16');
let encodings: string[] = req.acceptsEncodings();
let encoding: string | boolean = req.acceptsEncodings('gzip');
encoding = req.acceptsEncodings(['gzip', 'deflate']);
encoding = req.acceptsEncodings('gzip', 'deflate');
let languages: string[] = req.acceptsLanguages();
let language: string | boolean = req.acceptsLanguages('en');
language = req.acceptsLanguages(['en', 'ja']);
language = req.acceptsLanguages('en', 'ja');
res.send(req.query['token']);
// simple logger
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
router.get('/user/:id', function(req, res, next) {
if (req.params.id == 0) next('route');
else next();
}, function(req, res, next) {
res.render('regular');
});
app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
console.error(err);
next(err);
});
app.use((req, res, next) => {
// hacky trick, router is just a handler
router(req, res, next);
});
app.use(router);
app.get('/', function(req, res) {
res.send('hello world');
});
app.listen(3000);
const router = express.Router();
const next: express.NextFunction = () => {};
const nextWithArgument: express.NextFunction = (err: any) => {};
/**
* The express.Application is compatible with http.createServer
*/
const pathStr: string = 'test';
const pathRE: RegExp = /test/;
const path = true ? pathStr : pathRE;
router.get(path);
router.put(path)
router.post(path);
router.delete(path);
router.get(pathStr);
router.put(pathStr)
router.post(pathStr);
router.delete(pathStr);
router.get(pathRE);
router.put(pathRE)
router.post(pathRE);
router.delete(pathRE);
router.use((req, res, next) => { next(); })
router.route('/users')
.get((req, res, next) => {
let types: string[] = req.accepts();
let type: string | boolean = req.accepts('json');
type = req.accepts(['json', 'text']);
type = req.accepts('json', 'text');
let charsets: string[] = req.acceptsCharsets();
let charset: string | boolean = req.acceptsCharsets('utf-8');
charset = req.acceptsCharsets(['utf-8', 'utf-16']);
charset = req.acceptsCharsets('utf-8', 'utf-16');
let encodings: string[] = req.acceptsEncodings();
let encoding: string | boolean = req.acceptsEncodings('gzip');
encoding = req.acceptsEncodings(['gzip', 'deflate']);
encoding = req.acceptsEncodings('gzip', 'deflate');
let languages: string[] = req.acceptsLanguages();
let language: string | boolean = req.acceptsLanguages('en');
language = req.acceptsLanguages(['en', 'ja']);
language = req.acceptsLanguages('en', 'ja');
res.send(req.query['token']);
});
router.get('/user/:id', function(req, res, next) {
if (req.params.id == 0) next('route');
else next();
}, function(req, res, next) {
res.render('regular');
});
app.use((req, res, next) => {
// hacky trick, router is just a handler
router(req, res, next);
});
app.use(router);
app.listen(3000);
const next: express.NextFunction = () => { };
}
/***************************
* *
* Test with other modules *
* *
***************************/
import * as http from 'http';
http.createServer(app);
namespace node_tests {
{
// http.createServer can take express application
const app: express.Application = express();
http.createServer(app).listen(5678);
}
}
+6
View File
@@ -14,6 +14,12 @@ FB.getLoginStatus(function(response: fb.AuthResponse) {
console.log(response.authResponse.accessToken);
});
FB.getLoginStatus(function(response: fb.AuthResponse) {
console.log(response);
console.log(response.status);
console.log(response.authResponse.accessToken);
}, true);
FB.getAuthResponse(function(response: fb.AuthResponse) {
console.log(response);
console.log(response.status);
+9 -7
View File
@@ -8,10 +8,11 @@ declare var FB: fb.FacebookStatic;
declare namespace facebook {
interface FacebookStatic {
// api: any;
// AppEvents: any;
// Canvas: any;
// Event: any;
api: any;
AppEvents: any;
Canvas: any;
Event: any;
/**
* The method FB.getAuthResponse() is a synchronous accessor for the current authResponse.
* The synchronous nature of this method is what sets it apart from the other login methods.
@@ -25,7 +26,7 @@ declare namespace facebook {
*
* @param callback function to handle the response.
*/
getLoginStatus(callback: (response: AuthResponse) => void): void;
getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void;
/**
* The method FB.init() is used to initialize and setup the SDK.
*
@@ -49,8 +50,9 @@ declare namespace facebook {
* @param callback function to handle the response
*/
logout(callback: (response: AuthResponse) => void): void;
// ui: any;
// XFBML: any;
ui: any;
XFBML: any;
}
interface InitParams {
+1 -1
View File
@@ -6,7 +6,7 @@
// Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts via TSD fs-extra definition
///<reference path="../node/node.d.ts"/>
///<reference path="../bluebird/bluebird-2.0.d.ts"/>
///<reference path="../bluebird/bluebird.d.ts"/>
declare module "fs-extra-promise" {
import stream = require("stream");
@@ -240,6 +240,63 @@ app.setUserTasks([
}
]);
app.setUserTasks([]);
app.setJumpList([
{
type: 'custom',
name: 'Recent Projects',
items: [
{ type: 'file', path: 'C:\\Projects\\project1.proj' },
{ type: 'file', path: 'C:\\Projects\\project2.proj' }
]
},
{ // has a name so type is assumed to be "custom"
name: 'Tools',
items: [
{
type: 'task',
title: 'Tool A',
program: process.execPath,
args: '--run-tool-a',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool A'
},
{
type: 'task',
title: 'Tool B',
program: process.execPath,
args: '--run-tool-b',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool B'
}]
},
{
type: 'frequent'
},
{ // has no name and no type so type is assumed to be "tasks"
items: [
{
type: 'task',
title: 'New Project',
program: process.execPath,
args: '--new-project',
description: 'Create a new project.'
},
{
type: 'separator'
},
{
type: 'task',
title: 'Recover Project',
program: process.execPath,
args: '--recover-project',
description: 'Recover Project'
}]
}
]);
if (app.isUnityRunning()) {
}
if (app.isAccessibilitySupportEnabled()) {
+132 -9
View File
@@ -1,4 +1,4 @@
// Type definitions for Electron v1.3.4
// Type definitions for Electron v1.3.6
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>, rhysd <https://rhysd.github.io>, Milan Burda <https://github.com/miniak/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -62,7 +62,7 @@ declare namespace Electron {
/**
* Emitted when Electron has finished initialization.
*/
on(event: 'ready', listener: Function): this;
on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this;
/**
* Emitted when all windows have been closed.
*
@@ -199,7 +199,7 @@ declare namespace Electron {
* All windows will be closed immediately without asking user
* and the before-quit and will-quit events will not be emitted.
*/
exit(exitCode: number): void;
exit(exitCode?: number): void;
/**
* Relaunches the app when current instance exits.
*
@@ -218,6 +218,10 @@ declare namespace Electron {
args?: string[],
execPath?: string
}): void;
/**
* @returns Whether Electron has finished initializing.
*/
isReady(): boolean;
/**
* On Linux, focuses on the first visible window.
* On macOS, makes the application the active app.
@@ -333,6 +337,19 @@ declare namespace Electron {
* Note: This API is only available on Windows.
*/
setUserTasks(tasks: Task[]): boolean;
/**
* Note: This API is only available on Windows.
*/
getJumpListSettings(): JumpListSettings;
/**
* Sets or removes a custom Jump List for the application.
*
* If categories is null the previously set custom Jump List (if any) will be replaced
* by the standard Jump List for the app (managed by Windows).
*
* Note: This API is only available on Windows.
*/
setJumpList(categories: JumpListCategory[]): SetJumpListResult;
/**
* This method makes your application a Single Instance Application instead of allowing
* multiple instances of your app to run, this will ensure that only a single instance
@@ -560,6 +577,89 @@ declare namespace Electron {
iconIndex?: number;
}
/**
* ok - Nothing went wrong.
* error - One or more errors occured, enable runtime logging to figure out the likely cause.
* invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List.
* Separators are only allowed in the standard Tasks category.
* fileTypeRegistrationError - An attempt was made to add a file link to the Jump List
* for a file type the app isn't registered to handle.
* customCategoryAccessDeniedError - Custom categories can't be added to the Jump List
* due to user privacy or group policy settings.
*/
type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError';
interface JumpListSettings {
/**
* The minimum number of items that will be shown in the Jump List.
*/
minItems: number;
/**
* Items that the user has explicitly removed from custom categories in the Jump List.
*/
removedItems: JumpListItem[];
}
interface JumpListCategory {
/**
* tasks - Items in this category will be placed into the standard Tasks category.
* frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows.
* recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows.
* custom - Displays tasks or file links, name must be set by the app.
*/
type?: 'tasks' | 'frequent' | 'recent' | 'custom';
/**
* Must be set if type is custom, otherwise it should be omitted.
*/
name?: string;
/**
* Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted.
*/
items?: JumpListItem[];
}
interface JumpListItem {
/**
* task - A task will launch an app with specific arguments.
* separator - Can be used to separate items in the standard Tasks category.
* file - A file link will open a file using the app that created the Jump List.
*/
type: 'task' | 'separator' | 'file';
/**
* Path of the file to open, should only be set if type is file.
*/
path?: string;
/**
* Path of the program to execute, usually you should specify process.execPath which opens the current program.
* Should only be set if type is task.
*/
program?: string;
/**
* The command line arguments when program is executed. Should only be set if type is task.
*/
args?: string;
/**
* The text to be displayed for the item in the Jump List. Should only be set if type is task.
*/
title?: string;
/**
* Description of the task (displayed in a tooltip). Should only be set if type is task.
*/
description?: string;
/**
* The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary
* resource file that contains an icon (e.g. .ico, .exe, .dll).
* You can usually specify process.execPath to show the program icon.
*/
iconPath?: string;
/**
* The index of the icon in the resource file. If a resource file contains multiple icons
* this value can be used to specify the zero-based index of the icon that should be displayed
* for this task. If a resource file contains only one icon, this property should be set to zero.
*/
iconIndex?: number;
}
interface LoginItemSettings {
/**
* True if the app is set to open at login.
@@ -1271,6 +1371,12 @@ declare namespace Electron {
}
interface WebPreferences {
/**
* Whether to enable DevTools.
* If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools.
* Default: true.
*/
devTools?: boolean;
/**
* Whether node integration is enabled.
* Default: true.
@@ -1861,7 +1967,7 @@ declare namespace Electron {
interface CrashReporterStartOptions {
/**
* Default: Electron
* Default: app.getName()
*/
productName?: string;
companyName: string;
@@ -3296,16 +3402,18 @@ declare namespace Electron {
interface Shell {
/**
* Show the given file in a file manager. If possible, select the file.
* @returns Whether the item was successfully shown.
*/
showItemInFolder(fullPath: string): void;
showItemInFolder(fullPath: string): boolean;
/**
* Open the given file in the desktop's default manner.
* @returns Whether the item was successfully shown.
*/
openItem(fullPath: string): void;
openItem(fullPath: string): boolean;
/**
* Open the given external protocol URL in the desktop's default manner
* (e.g., mailto: URLs in the default mail user agent).
* @returns true if an application was available to open the URL, false otherwise.
* @returns Whether an application was available to open the URL.
*/
openExternal(url: string, options?: {
/**
@@ -3316,7 +3424,7 @@ declare namespace Electron {
}): boolean;
/**
* Move the given file to trash.
* @returns boolean status for the operation.
* @returns Whether the item was successfully moved to the trash.
*/
moveItemToTrash(fullPath: string): boolean;
/**
@@ -3595,7 +3703,7 @@ declare namespace Electron {
interface WebContentsStatic {
/**
* @returns An array of all web contents. This will contain web contents for all windows,
* @returns An array of all WebContents instances. This will contain web contents for all windows,
* webviews, opened devtools, and devtools extension background pages.
*/
getAllWebContents(): WebContents[];
@@ -3603,6 +3711,10 @@ declare namespace Electron {
* @returns The web contents that is focused in this application, otherwise returns null.
*/
getFocusedWebContents(): WebContents;
/**
* Find a WebContents instance according to its ID.
*/
fromId(id: number): WebContents;
}
/**
@@ -4971,6 +5083,17 @@ declare namespace Electron {
* See webContents.sendInputEvent for detailed description of event object.
*/
sendInputEvent(event: SendInputEvent): void
/**
* Changes the zoom factor to the specified factor.
* Zoom factor is zoom percent divided by 100, so 300% = 3.0.
*/
setZoomFactor(factor: number): void;
/**
* Changes the zoom level to the specified level.
* The original size is 0 and each increment above or below represents
* zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively.
*/
setZoomLevel(level: number): void;
/**
* Shows pop-up dictionary that searches the selected word on the page.
* Note: This API is available only on macOS.
+1 -1
View File
@@ -756,7 +756,7 @@ declare namespace google.maps {
zIndex?: number;
}
export interface PolyMouseEvent {
export interface PolyMouseEvent extends MouseEvent {
edge?: number;
path?: number;
vertex?: number;
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Yang Guan <https://github.com/lookuptable>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
/*
* Configuration object of a heatmap
+312 -3
View File
@@ -1073,6 +1073,125 @@ declare namespace H {
*/
resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect;
}
/**
* A strip is a flat list of latitude, longitude, altitude tuples in a fixed order.
*/
export class Strip {
/**
* Constructor
* @param opt_latLngAlts {Array<number>=} - An optional array of latitude, longitude and altitude triples to initialize the strip with.
* @param opt_ctx {H.geo.AltitudeContext=} - An optional altitude context for all altitudes contained in this strip.
*/
constructor(opt_latLngAlts?: Array<number>, opt_ctx?: H.geo.AltitudeContext);
/**
* This method pushes a lat, lng, alt to the end of this strip.
* @param lat {H.geo.Latitude}
* @param lng {H.geo.Longitude}
* @param alt {H.geo.Altitude}
*/
pushLatLngAlt(lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void;
/**
* This method splices the strip at the provided index, removing the specified number of items at that index and inserting the lat, lng, alt array.
* @param index {number} - The index at which to splice
* @param opt_nRemove {number=} - The number of lat, lng, alt values to remove
* @param opt_latLngAlts {Array<number>=} - The lat, lng, alt values to add
* @returns {Array<number>} - an array of removed elements
*/
spliceLatLngAlts(index: number, opt_nRemove?: number, opt_latLngAlts?: Array<number>): Array<number>;
/**
* This method inserts one set of lat, lng, alt values into the strip at the specified index.
* @param index {number} - the index at which to add the element
* @param lat {H.geo.Latitude} - the latitude to insert
* @param lng {H.geo.Longitude} - the longitude to insert
* @param alt {H.geo.Altitude} - the altitude to insert
*/
insertLatLngAlt(index: number, lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void;
/**
* This method removes one set of lat, lng, alt values from the strip at the specified index.
* @param index {number}
*/
removeLatLngAlt(index: number): void;
/**
* This method pushes the lat, lng, alt values of a H.geo.Point to the end of this strip.
* @param geoPoint {H.geo.IPoint}
*/
pushPoint(geoPoint: H.geo.IPoint): void;
/**
* This method inserts the lat, lng, alt values of a H.geo.Point into the list at the specified index.
* @param pointIndex {number}
* @param geoPoint {H.geo.IPoint}
*/
insertPoint(pointIndex: number, geoPoint: H.geo.IPoint): void;
/**
* This method removes one set of lat, lng, alt values from this strip at the virtual point index specified.
* @param pointIndex {number} - the virtual point index
*/
removePoint(pointIndex: number): void;
/**
* This method extracts a H.geo.Point from this strip at the virtual point index. If the extracted point has an alt value, the strip's altitude context will be supplied to the point.
* @param pointIndex {number} - the virtual point index in the strip
* @param opt_out {H.geo.Point=} - an optional point object to store the lat, lng, alt values
* @returns {H.geo.Point} - returns either the 'opt_out' point object or a new point object.
*/
extractPoint(pointIndex: number, opt_out?: H.geo.Point): H.geo.Point;
/**
* This method is a utility method that iterates over the lat, lng, alt array and calls the provided function for each 3 elements passing lat, lng and alt and the virtual point index as arguments.
* @param eachFn {function(H.geo.Latitude, H.geo.Longitude, H.geo.Altitude, number)} - the function to be called for each 3 elements
* @param opt_start {number=} - an optional start index to iterate from
* @param opt_end {number=} - an optional end index to iterate to
*/
eachLatLngAlt(eachFn: (lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude, n: number) => void, opt_start?: number, opt_end?: number): void;
/**
* This method returns the number of times that legs in this strip cross the date border.
* @param opt_closed {boolean=} - indicates whether the strip is closed (i.e. whether the strip's last and first coordinates form the closing leg of a polygon)
* @returns {number} - the amount of times this strip crosses the date border.
*/
getDBCs(opt_closed?: boolean): number;
/**
* This method return the number of points stored in this strip.
* @returns {number} - the number of points in this strip
*/
getPointCount(): number;
/**
* This method returns the internal array keeping the lat, lng, alt values. Modifying this array directly can destroy the integrity of this strip. Use it only for read access.
* @returns {Array<number>} - returns the raw lat, lng, alt values of this strip
*/
getLatLngAltArray(): Array<number>;
/**
* This method returns the bounding box of this strip.
* @returns {?H.geo.Rect} - this strip's bounding rectangle
*/
getBounds(): H.geo.Rect;
/**
* This method checks whether two longitudes form a leg which crosses the date border.
* @param lng1 {H.geo.Longitude} - the start longitude of the leg
* @param lng2 {H.geo.Longitude} - the end longitude of the leg
* @returns {boolean} - true if the leg crosses the date border, otherwise false
*/
static isDBC(lng1: H.geo.Longitude, lng2: H.geo.Longitude): boolean;
/**
* This method initializes a new strip with an array of lat, lng values. Arrays are expected to have an even length with the format [lat, lng, lat, lng, ...].
* @param latLngs {Array<number>} - the array of lat, lng value.
* @returns {H.geo.Strip} - the strip containing the lat, lng values
*/
static fromLatLngArray(latLngs: Array<number>): H.geo.Strip;
}
}
/***** lang *****/
@@ -1173,6 +1292,78 @@ declare namespace H {
}
}
/**
* A Polygon with a circular shape.
*/
export class Circle extends H.map.Polygon {
/**
* Constructor
* @param center {H.geo.IPoint} - The geographical coordinates of the circle's center
* @param radius {number} - The radius of the circle in meters
* @param opt_options {H.map.Circle.Options=} - An object that specifies circle options and their initial values (among these, precision has a significant impact on the shape of the circle - please see
*/
constructor(center: H.geo.IPoint, radius: number, opt_options?: H.map.Circle.Options);
/**
* To set the geographical center point of this circle. If the specified center is an instance of H.geo.Point you must not modify this Point instance without calling setCenter immediately afterwards.
* @param center {H.geo.IPoint}
*/
setCenter(center: H.geo.IPoint): void;
/**
* To get the center point of this circle You must not modify the returned Point instance without calling setCenter immediately afterwards.
* @returns {H.geo.Point}
*/
getCenter(): H.geo.Point;
/**
* To set the length of the radius of the circle in meters. The value is clamped to the of {@code[0 ... 20015089.27787877]} (half WGS84 mean circumference)
* @param radius {number}
*/
setRadius(radius: number): void;
/**
* To get the length of the radius of the circle in meters.
* @returns {number}
*/
getRadius(): number;
/**
* To set the precision of this circle {@see H.map.Circle.Options#precision}
* @param precision {number}
*/
setPrecision(precision: number): void;
/**
* To get the precision value of this circle
* @returns {number}
*/
getPrecision(): number;
}
export module Circle {
/**
* @property style {H.map.SpatialStyle=} - the style to be used when tracing the polyline
* @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true
* @property precision {number=} - The precision of a circle as a number of segments to be used when rendering the circle. The value is clamped to the range between [4 ... 360], where 60 is the default. Note that the lower the value the more angular and the less circle-like the shape appears and, conversely, the higher the value the smoother and more rounded the result. Thus, starting at the extreme low end of the possible values, 4 produces a square, 6 a hexagon, while 30 results in a circle-like shape, although it appears increasingly angular as the zoom level increases (as you zoom in), and finally 360 produces a smooth circle.
* @property zIndex {number=} - The z-index value of the circle, default is 0
* @property min {number=} - The minimum zoom level for which the circle is visible, default is -Infinity
* @property max {number=} - The maximum zoom level for which the circle is visible, default is Infinity
* @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object.
* @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData
*/
export interface Options {
style?: H.map.SpatialStyle | H.map.SpatialStyle.Options;
visibility?: boolean;
precision?: number;
zIndex?: number;
min?: number;
max?: number;
provider?: H.map.provider.Provider;
data?: any;
}
}
/**
* The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine.
*/
@@ -1242,6 +1433,38 @@ declare namespace H {
}
}
/**
* This class represents a spatial shape in geographic space. It is defined by a path containing the vertices of the shape (lat, lng, alt values).
*/
export class GeoShape extends H.map.Spatial {
/**
* Constructor
* @param isClosed {boolean} - Indicates whether this geographical shape is closed (a polygon)
* @param strip {H.geo.Strip} - The strip describing the shape of the spatial object
* @param options {H.map.Spatial.Options} - The options to apply
*/
constructor(isClosed: boolean, strip: H.geo.Strip, options: H.map.Spatial.Options);
/**
* This method returns the strip which represents the shape of the spatial object.
* @returns {H.geo.Strip} - the strip
*/
getStrip(): H.geo.Strip;
/**
* This method sets the geo-information for the spatial object
* @param strip {?H.geo.Strip} - The strip which represents the shape of the spatial object.
* @returns {H.map.GeoShape} - the Spatial instance itself
*/
setStrip(strip: H.geo.Strip): H.map.GeoShape;
/**
* This method returns the bounding rectangle for this object. The rectangle is the smallest rectangle which encloses all points of the spatial object.
* @returns {H.geo.Rect}
*/
getBounds(): H.geo.Rect;
}
/**
* This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects
*/
@@ -1855,6 +2078,92 @@ declare namespace H {
}
}
/**
* This class represents a polygon in geo-space. It is defined by a strip containing the vertices of a geo shape object (lat, lng, alt values) and a pen to use when rendering the polyline. Polygon represents a closed plane defined by the list of verticies, projected on the map display. List of vericies which define the polygon are is a list of geo coordinates encapsulated by the strip object H.geo.Strip
*/
export class Polygon extends H.map.GeoShape {
/**
* Constructor
* @param strip {H.geo.Strip} - the strip describing this polygon's vertices
* @param opt_options {H.map.Spatial.Options=} - optional initialization parameters
*/
constructor(strip: H.geo.Strip, opt_options?: H.map.Spatial.Options);
/**
* To set the indicator whether this polygon covers the north pole. It's needed for Polygons whose strip is defined as lines arround the world on longitude axis (for example a circle whose center is one of the poles). In this case a additional information is needed to know if the southern or northern part of the world should be covered by the poygon.
* @param flag {boolean} - A value of true means it covers the north pole, false means south pole
* @returns {H.map.Polygon} - the Polygon instance itself
*/
setNorthPoleCovering(flag: boolean): H.map.Polygon;
/**
* See H.map.Polygon#setNorthPoleCovering
* @returns {boolean}
*/
getNorthPoleCovering(): boolean;
}
/**
* This class represents a polyline in geo-space. It is defined by a path containing the vertices of a polyline (lat, lng, alt values) and a pen to use when tracing the path on the map.
*/
export class Polyline extends H.map.GeoShape {
/**
* Constructor
* @param strip {H.geo.Strip} - the strip describing this polygon's vertices
* @param opt_options {H.map.Polyline.Options=} - optional initialization parameters
*/
constructor(strip: H.geo.Strip, opt_options?: H.map.Polyline.Options);
/**
* This method clips this polyline against a rectangular area and returns the intersecting sub-lines.
* @param geoRect {H.geo.Rect}
* @returns {Array<Array<number>>}
*/
clip(geoRect: H.geo.Rect): Array<Array<number>>;
}
export module Polyline {
/**
* Options which are used to initialize a polyline
* @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the polyline
* @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the polyline.
* @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true
* @property zIndex {number=} - The z-index value of the map object, default is 0
* @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity
* @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity
* @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object.
* @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData
*/
export interface Options {
style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options);
arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options);
visibility?: boolean;
zIndex?: number;
min?: number;
max?: number;
provider?: H.map.provider.Provider;
data?: any;
}
}
/**
* A Polygon with a rectangular shape.
*/
export class Rect extends H.map.Polygon {
/**
* Constructor
* @param bounds {H.geo.Rect} - The geographical bounding box for this rectangle
* @param opt_options {H.map.Spatial.Options=}
*/
constructor(bounds: H.geo.Rect, opt_options?: H.map.Spatial.Options);
/**
* To set the bounds of this rectangle.
* @param bounds {H.geo.Rect}
*/
setBounds(bounds: H.geo.Rect): void;
}
/**
* This class represents a spatial map object which provides its projected geometry.
*/
@@ -1985,8 +2294,8 @@ declare namespace H {
miterLimit: number;
lineDash: Array<number>;
lineDashOffset: number;
MAX_LINE_WIDTH: number;
DEFAULT_STYLE: H.map.SpatialStyle;
static MAX_LINE_WIDTH: number;
static DEFAULT_STYLE: H.map.SpatialStyle;
}
export module SpatialStyle {
@@ -2018,7 +2327,7 @@ declare namespace H {
lineCap?: H.map.SpatialStyle.LineCap;
lineJoin?: H.map.SpatialStyle.LineJoin;
miterLimit?: number;
lineDash: Array<number>;
lineDash?: Array<number>;
lineDashOffset?: number;
}
}
+1
View File
@@ -44,6 +44,7 @@ declare namespace jest {
interface Matchers {
not: Matchers;
toThrow(expected?: any): boolean;
toThrowError(expected?: any): boolean;
toBe(expected: any): boolean;
toEqual(expected: any): boolean;
toBeFalsy(): boolean;
+9 -2
View File
@@ -61,8 +61,10 @@ interface KnockoutSubscription {
}
interface KnockoutSubscribable<T> extends KnockoutSubscribableFunctions<T> {
subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription;
subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription;
subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription;
subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription;
extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable<T>;
getSubscriptionsCount(): number;
}
@@ -91,6 +93,11 @@ interface KnockoutObservableArrayStatic {
}
interface KnockoutObservableArray<T> extends KnockoutObservable<T[]>, KnockoutObservableArrayFunctions<T> {
subscribe(callback: (newValue: KnockoutArrayChange<T>[]) => void, target: any, event: "arrayChange"): KnockoutSubscription;
subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription;
subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription;
subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription;
extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray<T>;
}
@@ -325,7 +332,7 @@ interface KnockoutUtils {
}
interface KnockoutArrayChange<T> {
status: string;
status: "added" | "deleted";
value: T;
index: number;
moved?: number;
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference path="./knockout.d.ts" />
import ko = require("knockout");
import ko = require("knockout");
var myArray = ko.observableArray([1, 2, 3]);
+35
View File
@@ -680,3 +680,38 @@ function test_tasks() {
setTimeout(callback, 0);
};
}
function observableEventsTests() {
var observable = ko.observable(1);
observable.subscribe(value => {
var num: number = value;
});
observable.subscribe(value => {
var num: number = value;
}, null, "change");
observable.subscribe(value => {
var num: number = value;
}, null, "beforeChange");
}
function observableArrayEventsTests() {
var observableArray = ko.observableArray([1, 2, 3, 4]);
observableArray.subscribe(array => {
var arr: number[] = array;
});
observableArray.subscribe(array => {
var arr: number[] = array;
}, null, "change");
observableArray.subscribe(array => {
var arr: number[] = array;
}, null, "beforeChange");
var count = 0;
observableArray.subscribe(changes => {
changes.forEach(change => {
if (change.status == "added")
count++;
else if (change.status == "deleted")
count--;
});
}, null, "arrayChange");
}
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
/// <reference path="leaflet-curve.d.ts" />
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Onikiienko <https://github.com/onikiienko>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
/**
+2 -2
View File
@@ -1,4 +1,4 @@
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
/// <reference path="leaflet-draw.d.ts" />
@@ -44,4 +44,4 @@ map.on('draw:created', function (e: L.DrawEvents.Created) {
layer = e.layer;
drawnItems.addLayer(layer);
});
});
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Matt Guest <https://github.com/matt-guest>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
export interface MapOptions {
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Dominic Alie <https://github.com/dalie>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
/**
@@ -1,4 +1,4 @@
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
/// <reference path="leaflet-geocoder-mapzen.d.ts" />
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
+1 -1
View File
@@ -4,7 +4,7 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
namespace Control {
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Wim Looman <https://github.com/Nemo157>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
export interface IconOptions {
+4 -4
View File
@@ -3,7 +3,7 @@
// Definitions by: Robert Imig <https://github.com/rimig>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
export interface MarkerClusterGroupOptions {
@@ -51,7 +51,7 @@ declare namespace L {
/*
* The maximum radius that a cluster will cover from the central marker (in pixels). Default 80.
* Decreasing will make more, smaller clusters. You can also use a function that accepts
* Decreasing will make more, smaller clusters. You can also use a function that accepts
* the current map zoom and returns the maximum cluster radius in pixels
*/
maxClusterRadius?: number | ((zoom: number) => number);
@@ -134,9 +134,9 @@ declare namespace L {
getAllChildMarkers(): Marker[];
/*
* Zooms to show the given marker (spiderfying if required),
* Zooms to show the given marker (spiderfying if required),
* calls the callback when the marker is visible on the map.
*/
*/
zoomToShowLayer(layer: any, callback: () => void): void;
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Egor Komarov <https://github.com/Odrin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare module L {
module AwesomeMarkers {
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: William Comartin <https://github.com/wcomartin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
+427
View File
@@ -0,0 +1,427 @@
/// <reference path="leaflet-0.7.d.ts" />
// initialize the map on the "map" div with a given center and zoom
var div = document.getElementById('map');
var map : L.Map = L.map(div, {
center: L.latLng([51.505, -0.09]),
zoom: 13,
minZoom: 3,
maxZoom: 8,
maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]),
dragging: true,
touchZoom: true,
scrollWheelZoom: true,
boxZoom: true,
tap: true,
tapTolerance: 30,
trackResize: true,
worldCopyJump: false,
closePopupOnClick: true,
bounceAtZoomLimits: true,
keyboard: true,
keyboardPanOffset: 80,
keyboardZoomOffset: 1,
inertia: true,
inertiaDeceleration: 3000,
inertiaMaxSpeed: 1500,
inertiaThreshold: 32,
zoomControl: true,
attributionControl: true,
fadeAnimation: true,
zoomAnimation: true,
zoomAnimationThreshold: 4,
markerZoomAnimation: true
});
map.dragging.enable();
map.touchZoom.enable();
map.scrollWheelZoom.enable();
map.doubleClickZoom.enable();
map.boxZoom.enable();
map.tap.enable();
map.setView(new L.LatLng(42, 51));
map.setView(L.latLng(42, 51));
map.setView(L.latLng(42, 51), 12);
map.setView(L.latLng(42, 51), 12, {
reset: true,
pan: {
animate: true,
duration: 0.25,
easeLinearity: 0.25,
noMoveStart: false
},
zoom: {
animate: true
}
});
map.setZoom(50);
map.setZoom(50, {});
map.zoomIn();
map.zoomOut();
map.zoomIn(2);
map.zoomOut(2);
map.zoomIn(2, { animate: true });
map.zoomOut(2, { animate: true });
map.setZoomAround(L.latLng(42, 51), 8, { animate: false });
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), {
paddingTopLeft: L.point(20, 20),
paddingBottomRight: L.point(20, 20),
padding: L.point(0, 0),
maxZoom: null
});
map.fitWorld();
map.fitWorld({
animate: false
});
map.panTo(L.latLng(42, 42));
map.panTo(L.latLng(42, 42), {
animate: true
});
map.invalidateSize(true);
map.invalidateSize({ reset: true });
map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.locate();
map.locate({
watch: false,
setView: false,
maxZoom: 18,
timeout: 10000,
maximumAge: 0,
enableHighAccuracy: false
});
map.stopLocate();
map.remove();
var center : L.LatLng = map.getCenter();
var zoom : number = map.getZoom();
var minZoom: number = map.getMinZoom();
var maxZoom: number = map.getMaxZoom();
var bounds: L.LatLngBounds = map.getBounds();
var boundsZoom: number = map.getBoundsZoom(bounds, true);
var size: L.Point = map.getSize();
var pixelBounds: L.Bounds = map.getPixelBounds();
var pixelOrigin: L.Point = map.getPixelOrigin();
var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png");
map.addLayer(layer);
map.addLayer(layer, false);
map.eachLayer(l => {});
map.removeLayer(layer);
map.hasLayer(layer);
map.openPopup("canard", L.latLng(42, 51));
var popup = L.popup({
autoPan: true
});
map.openPopup(popup);
map.closePopup(popup);
map.closePopup();
map.addControl(L.control.attribution({position: 'bottomright'}));
map.removeControl(L.control.attribution({ position: 'bottomright' }));
L.control.layers({'Base': layer}).addTo(map);
map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) {
alert(e.name);
});
map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0)));
map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0)));
map.containerPointToLayerPoint(L.point(0, 0));
map.layerPointToContainerPoint(L.point(0, 0));
map.project(map.unproject(L.point(10, 20)));
map.project(map.unproject(L.point(10, 20), 12), 12);
var mouseEvent: L.LeafletMouseEvent;
map.mouseEventToContainerPoint(mouseEvent);
map.mouseEventToLayerPoint(mouseEvent);
map.mouseEventToLatLng(mouseEvent);
map.getContainer().classList.add('roger');
map.getPanes().mapPane.classList.add('roger');
map.getPanes().markerPane.classList.add('roger');
map.getPanes().objectsPane.classList.add('roger');
map.getPanes().overlayPane.classList.add('roger');
map.getPanes().popupPane.classList.add('roger');
map.getPanes().shadowPane.classList.add('roger');
map.getPanes().tilePane.classList.add('roger');
map.whenReady((m: L.Map) => {
m.zoomOut();
});
map.on('click', () => {
map.zoomOut();
});
map.off('dblclick', L.Util.falseFn);
map.once('contextmenu', (e: L.LeafletMouseEvent) => {
map.openPopup('contextmenu', e.latlng);
});
var marker = L.marker(L.latLng(42, 51), {
icon: L.icon({
iconUrl: 'roger.png',
iconRetinaUrl: 'roger-retina.png',
iconSize: L.point(40, 40),
iconAnchor: L.point(20, 0),
shadowUrl: 'roger-shadow.png',
shadowRetinaUrl: 'roger-shadow-retina.png',
shadowSize: L.point(44, 44),
shadowAnchor: L.point(22, 0),
popupAnchor: L.point(0, 0),
className: 'roger-icon'
}),
clickable: true,
draggable: false,
keyboard: true,
title: 'this is an icon',
alt: '',
zIndexOffset: 0,
opacity: 1.0,
riseOnHover: false,
riseOffset: 250
});
marker.addTo(map);
marker.on('click', (e: L.LeafletMouseEvent) => {
map.setView(e.latlng);
});
marker.once('mouseover', () => {
marker.openPopup();
})
marker.setLatLng(marker.getLatLng());
marker.setIcon(L.icon({}));
marker.setZIndexOffset(30);
marker.setOpacity(0.8);
marker.bindPopup(popup);
marker.unbindPopup();
marker.bindPopup('hello', {
closeOnClick: true
});
marker.openPopup();
marker.closePopup();
marker.togglePopup();
marker.togglePopup();
marker.setPopupContent('hello 3')
marker.getPopup().setContent('hello 2');
marker.update();
marker.toGeoJSON();
marker.dragging.enable();
popup = L.popup({
maxWidth: 300,
minWidth: 50,
maxHeight: null,
autoPan: true,
keepInView: false,
closeButton: true,
offset: L.point(0, 6),
autoPanPaddingTopLeft: null,
autoPanPaddingBottomRight: L.point(20, 20),
autoPanPadding: L.point(5, 5),
zoomAnimation: true,
closeOnClick: null,
className: 'roger'
});
popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map);
popup.update();
var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {
minZoom: 0,
maxZoom: 18,
maxNativeZoom: 17,
tileSize: 256,
subdomains: ['a','b','c'],
errorTileUrl: '',
attribution: '',
tms: false,
continuousWorld: false,
noWrap: false,
zoomOffset: 0,
zoomReverse: false,
opacity: 1.0,
zIndex: null,
unloadInvisibleTiles: false,
updateWhenIdle: false,
detectRetina: true,
reuseTiles: true,
bounds: null
});
tileLayer.on('loading', L.Util.falseFn)
.off('loading', L.Util.falseFn)
.once('tileload', L.Util.falseFn);
tileLayer.addTo(map);
tileLayer.bringToBack()
.bringToFront()
.setOpacity(0.7)
.setZIndex(9)
.redraw()
.setUrl('http://perdu.com')
.getContainer();
namespace CustomControl {
export interface Options {
title: string;
position?: string;
}
}
interface CustomControl extends L.Control {
getTitle(): string;
setTitle(title: string): CustomControl;
}
var CustomControl: { new(options: CustomControl.Options): CustomControl };
CustomControl = L.Control.extend<CustomControl.Options, CustomControl>({
initialize: function(options: CustomControl.Options) {
L.Control.prototype.initialize.call(this, {
position: options.position || 'bottomleft',
});
this.title = options.title;
},
getTitle: function() {
return this.title;
},
setTitle: function(title: string) {
this.title = title;
},
});
// Different latLng and latLngBounds expressions
var latLngLiteral = [10, 20];
var latLngObjectLiteral = { lat: 10, lng: 10 };
var boundsLiteral = [[10, 20], [20, 20]];
var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral];
var circle: L.Circle = L.circle(latLngLiteral, 4);
circle = new L.Circle(latLngLiteral, 4);
circle.setLatLng(latLngLiteral);
circle = L.circle(latLngObjectLiteral, 4);
circle = new L.Circle(latLngObjectLiteral, 4);
circle.setLatLng(latLngObjectLiteral);
var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral);
circleMarker = new L.CircleMarker(latLngLiteral);
circleMarker.setLatLng(latLngLiteral);
circleMarker = L.circleMarker(latLngObjectLiteral);
circleMarker = new L.CircleMarker(latLngObjectLiteral);
circleMarker.setLatLng(latLngObjectLiteral);
var latLng: L.LatLng = L.latLng(latLngLiteral);
latLng = new L.LatLng(latLngLiteral);
latLng.distanceTo(latLngLiteral);
latLng.equals(latLngLiteral);
latLng = L.latLng(latLngObjectLiteral);
latLng = new L.LatLng(latLngObjectLiteral);
latLng.distanceTo(latLngObjectLiteral);
latLng.equals(latLngObjectLiteral);
var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral);
bounds = L.latLngBounds(boundLiteralOfLatLngObjects);
bounds = new L.LatLngBounds(boundsLiteral);
bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects);
bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral);
bounds.extend(latLngLiteral);
bounds.extend(latLngObjectLiteral);
bounds.extend(boundsLiteral);
bounds.extend(boundLiteralOfLatLngObjects);
bounds.contains(latLngLiteral);
bounds.contains(boundLiteralOfLatLngObjects);
bounds.contains(boundsLiteral);
bounds.intersects(boundsLiteral);
bounds.intersects(boundLiteralOfLatLngObjects);
bounds.equals(boundsLiteral);
bounds.equals(boundLiteralOfLatLngObjects);
map.setView(latLngLiteral);
map.setView(latLngObjectLiteral);
map.setZoomAround(latLngLiteral, 15);
map.setZoomAround(latLngObjectLiteral, 15);
map.panTo(latLngLiteral);
map.panTo(latLngObjectLiteral);
map.openPopup('test', latLngLiteral);
map.openPopup('test', latLngObjectLiteral);
map.latLngToLayerPoint(latLngLiteral);
map.latLngToLayerPoint(latLngObjectLiteral);
map.latLngToContainerPoint(latLngLiteral);
map.latLngToContainerPoint(latLngObjectLiteral);
map.project(latLngLiteral);
map.project(latLngObjectLiteral);
marker.setLatLng(latLngLiteral);
marker.setLatLng(latLngObjectLiteral);
var polygon: L.Polygon = L.polygon(boundsLiteral);
polygon = L.polygon(boundLiteralOfLatLngObjects);
polygon = new L.Polygon(boundsLiteral);
polygon = new L.Polygon(boundLiteralOfLatLngObjects);
var polyline: L.Polyline = L.polyline(boundsLiteral);
polyline = L.polyline(boundLiteralOfLatLngObjects);
polyline = new L.Polyline(boundsLiteral);
polyline = new L.Polyline(boundLiteralOfLatLngObjects);
polyline.setLatLngs(boundsLiteral);
polyline.setLatLngs(boundLiteralOfLatLngObjects);
polyline.addLatLng(latLngLiteral);
polyline.addLatLng(latLngObjectLiteral);
var popup: L.Popup = L.popup();
popup.setLatLng(latLngLiteral);
popup.setLatLng(latLngObjectLiteral);
var zoomCtrl = L.control.zoom({
position: "topleft",
zoomInText: '+',
zoomOutText: '-'
});
+4382
View File
File diff suppressed because it is too large Load Diff
+265 -425
View File
@@ -1,427 +1,267 @@
/// <reference path="leaflet.d.ts" />
// initialize the map on the "map" div with a given center and zoom
var div = document.getElementById('map');
var map : L.Map = L.map(div, {
center: L.latLng([51.505, -0.09]),
zoom: 13,
minZoom: 3,
maxZoom: 8,
maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]),
dragging: true,
touchZoom: true,
scrollWheelZoom: true,
boxZoom: true,
tap: true,
tapTolerance: 30,
trackResize: true,
worldCopyJump: false,
closePopupOnClick: true,
bounceAtZoomLimits: true,
keyboard: true,
keyboardPanOffset: 80,
keyboardZoomOffset: 1,
inertia: true,
inertiaDeceleration: 3000,
inertiaMaxSpeed: 1500,
inertiaThreshold: 32,
zoomControl: true,
attributionControl: true,
fadeAnimation: true,
zoomAnimation: true,
zoomAnimationThreshold: 4,
markerZoomAnimation: true
});
map.dragging.enable();
map.touchZoom.enable();
map.scrollWheelZoom.enable();
map.doubleClickZoom.enable();
map.boxZoom.enable();
map.tap.enable();
map.setView(new L.LatLng(42, 51));
map.setView(L.latLng(42, 51));
map.setView(L.latLng(42, 51), 12);
map.setView(L.latLng(42, 51), 12, {
reset: true,
pan: {
animate: true,
duration: 0.25,
easeLinearity: 0.25,
noMoveStart: false
},
zoom: {
animate: true
}
});
map.setZoom(50);
map.setZoom(50, {});
map.zoomIn();
map.zoomOut();
map.zoomIn(2);
map.zoomOut(2);
map.zoomIn(2, { animate: true });
map.zoomOut(2, { animate: true });
map.setZoomAround(L.latLng(42, 51), 8, { animate: false });
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), {
paddingTopLeft: L.point(20, 20),
paddingBottomRight: L.point(20, 20),
padding: L.point(0, 0),
maxZoom: null
});
map.fitWorld();
map.fitWorld({
animate: false
});
map.panTo(L.latLng(42, 42));
map.panTo(L.latLng(42, 42), {
animate: true
});
map.invalidateSize(true);
map.invalidateSize({ reset: true });
map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.locate();
map.locate({
watch: false,
setView: false,
maxZoom: 18,
timeout: 10000,
maximumAge: 0,
enableHighAccuracy: false
});
map.stopLocate();
map.remove();
var center : L.LatLng = map.getCenter();
var zoom : number = map.getZoom();
var minZoom: number = map.getMinZoom();
var maxZoom: number = map.getMaxZoom();
var bounds: L.LatLngBounds = map.getBounds();
var boundsZoom: number = map.getBoundsZoom(bounds, true);
var size: L.Point = map.getSize();
var pixelBounds: L.Bounds = map.getPixelBounds();
var pixelOrigin: L.Point = map.getPixelOrigin();
var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png");
map.addLayer(layer);
map.addLayer(layer, false);
map.eachLayer(l => {});
map.removeLayer(layer);
map.hasLayer(layer);
map.openPopup("canard", L.latLng(42, 51));
var popup = L.popup({
autoPan: true
});
map.openPopup(popup);
map.closePopup(popup);
map.closePopup();
map.addControl(L.control.attribution({position: 'bottomright'}));
map.removeControl(L.control.attribution({ position: 'bottomright' }));
L.control.layers({'Base': layer}).addTo(map);
map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) {
alert(e.name);
});
map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0)));
map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0)));
map.containerPointToLayerPoint(L.point(0, 0));
map.layerPointToContainerPoint(L.point(0, 0));
map.project(map.unproject(L.point(10, 20)));
map.project(map.unproject(L.point(10, 20), 12), 12);
var mouseEvent: L.LeafletMouseEvent;
map.mouseEventToContainerPoint(mouseEvent);
map.mouseEventToLayerPoint(mouseEvent);
map.mouseEventToLatLng(mouseEvent);
map.getContainer().classList.add('roger');
map.getPanes().mapPane.classList.add('roger');
map.getPanes().markerPane.classList.add('roger');
map.getPanes().objectsPane.classList.add('roger');
map.getPanes().overlayPane.classList.add('roger');
map.getPanes().popupPane.classList.add('roger');
map.getPanes().shadowPane.classList.add('roger');
map.getPanes().tilePane.classList.add('roger');
map.whenReady((m: L.Map) => {
m.zoomOut();
});
map.on('click', () => {
map.zoomOut();
});
map.off('dblclick', L.Util.falseFn);
map.once('contextmenu', (e: L.LeafletMouseEvent) => {
map.openPopup('contextmenu', e.latlng);
});
var marker = L.marker(L.latLng(42, 51), {
icon: L.icon({
iconUrl: 'roger.png',
iconRetinaUrl: 'roger-retina.png',
iconSize: L.point(40, 40),
iconAnchor: L.point(20, 0),
shadowUrl: 'roger-shadow.png',
shadowRetinaUrl: 'roger-shadow-retina.png',
shadowSize: L.point(44, 44),
shadowAnchor: L.point(22, 0),
popupAnchor: L.point(0, 0),
className: 'roger-icon'
}),
clickable: true,
draggable: false,
keyboard: true,
title: 'this is an icon',
alt: '',
zIndexOffset: 0,
opacity: 1.0,
riseOnHover: false,
riseOffset: 250
});
marker.addTo(map);
marker.on('click', (e: L.LeafletMouseEvent) => {
map.setView(e.latlng);
});
marker.once('mouseover', () => {
marker.openPopup();
})
marker.setLatLng(marker.getLatLng());
marker.setIcon(L.icon({}));
marker.setZIndexOffset(30);
marker.setOpacity(0.8);
marker.bindPopup(popup);
marker.unbindPopup();
marker.bindPopup('hello', {
closeOnClick: true
});
marker.openPopup();
marker.closePopup();
marker.togglePopup();
marker.togglePopup();
marker.setPopupContent('hello 3')
marker.getPopup().setContent('hello 2');
marker.update();
marker.toGeoJSON();
marker.dragging.enable();
popup = L.popup({
maxWidth: 300,
minWidth: 50,
maxHeight: null,
autoPan: true,
keepInView: false,
closeButton: true,
offset: L.point(0, 6),
autoPanPaddingTopLeft: null,
autoPanPaddingBottomRight: L.point(20, 20),
autoPanPadding: L.point(5, 5),
zoomAnimation: true,
closeOnClick: null,
className: 'roger'
});
popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map);
popup.update();
var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {
minZoom: 0,
maxZoom: 18,
maxNativeZoom: 17,
tileSize: 256,
subdomains: ['a','b','c'],
errorTileUrl: '',
attribution: '',
tms: false,
continuousWorld: false,
noWrap: false,
zoomOffset: 0,
zoomReverse: false,
opacity: 1.0,
zIndex: null,
unloadInvisibleTiles: false,
updateWhenIdle: false,
detectRetina: true,
reuseTiles: true,
bounds: null
});
tileLayer.on('loading', L.Util.falseFn)
.off('loading', L.Util.falseFn)
.once('tileload', L.Util.falseFn);
tileLayer.addTo(map);
tileLayer.bringToBack()
.bringToFront()
.setOpacity(0.7)
.setZIndex(9)
.redraw()
.setUrl('http://perdu.com')
.getContainer();
namespace CustomControl {
export interface Options {
title: string;
position?: string;
}
}
interface CustomControl extends L.Control {
getTitle(): string;
setTitle(title: string): CustomControl;
}
var CustomControl: { new(options: CustomControl.Options): CustomControl };
CustomControl = L.Control.extend<CustomControl.Options, CustomControl>({
initialize: function(options: CustomControl.Options) {
L.Control.prototype.initialize.call(this, {
position: options.position || 'bottomleft',
});
this.title = options.title;
},
getTitle: function() {
return this.title;
},
setTitle: function(title: string) {
this.title = title;
},
});
// Different latLng and latLngBounds expressions
var latLngLiteral = [10, 20];
var latLngObjectLiteral = { lat: 10, lng: 10 };
var boundsLiteral = [[10, 20], [20, 20]];
var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral];
var circle: L.Circle = L.circle(latLngLiteral, 4);
circle = new L.Circle(latLngLiteral, 4);
circle.setLatLng(latLngLiteral);
circle = L.circle(latLngObjectLiteral, 4);
circle = new L.Circle(latLngObjectLiteral, 4);
circle.setLatLng(latLngObjectLiteral);
var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral);
circleMarker = new L.CircleMarker(latLngLiteral);
circleMarker.setLatLng(latLngLiteral);
circleMarker = L.circleMarker(latLngObjectLiteral);
circleMarker = new L.CircleMarker(latLngObjectLiteral);
circleMarker.setLatLng(latLngObjectLiteral);
var latLng: L.LatLng = L.latLng(latLngLiteral);
latLng = new L.LatLng(latLngLiteral);
latLng.distanceTo(latLngLiteral);
latLng.equals(latLngLiteral);
latLng = L.latLng(latLngObjectLiteral);
latLng = new L.LatLng(latLngObjectLiteral);
latLng.distanceTo(latLngObjectLiteral);
latLng.equals(latLngObjectLiteral);
var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral);
bounds = L.latLngBounds(boundLiteralOfLatLngObjects);
bounds = new L.LatLngBounds(boundsLiteral);
bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects);
bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral);
bounds.extend(latLngLiteral);
bounds.extend(latLngObjectLiteral);
bounds.extend(boundsLiteral);
bounds.extend(boundLiteralOfLatLngObjects);
bounds.contains(latLngLiteral);
bounds.contains(boundLiteralOfLatLngObjects);
bounds.contains(boundsLiteral);
bounds.intersects(boundsLiteral);
bounds.intersects(boundLiteralOfLatLngObjects);
bounds.equals(boundsLiteral);
bounds.equals(boundLiteralOfLatLngObjects);
map.setView(latLngLiteral);
map.setView(latLngObjectLiteral);
map.setZoomAround(latLngLiteral, 15);
map.setZoomAround(latLngObjectLiteral, 15);
map.panTo(latLngLiteral);
map.panTo(latLngObjectLiteral);
map.openPopup('test', latLngLiteral);
map.openPopup('test', latLngObjectLiteral);
map.latLngToLayerPoint(latLngLiteral);
map.latLngToLayerPoint(latLngObjectLiteral);
map.latLngToContainerPoint(latLngLiteral);
map.latLngToContainerPoint(latLngObjectLiteral);
map.project(latLngLiteral);
map.project(latLngObjectLiteral);
marker.setLatLng(latLngLiteral);
marker.setLatLng(latLngObjectLiteral);
var polygon: L.Polygon = L.polygon(boundsLiteral);
polygon = L.polygon(boundLiteralOfLatLngObjects);
polygon = new L.Polygon(boundsLiteral);
polygon = new L.Polygon(boundLiteralOfLatLngObjects);
var polyline: L.Polyline = L.polyline(boundsLiteral);
polyline = L.polyline(boundLiteralOfLatLngObjects);
polyline = new L.Polyline(boundsLiteral);
polyline = new L.Polyline(boundLiteralOfLatLngObjects);
polyline.setLatLngs(boundsLiteral);
polyline.setLatLngs(boundLiteralOfLatLngObjects);
polyline.addLatLng(latLngLiteral);
polyline.addLatLng(latLngObjectLiteral);
var popup: L.Popup = L.popup();
popup.setLatLng(latLngLiteral);
popup.setLatLng(latLngObjectLiteral);
var zoomCtrl = L.control.zoom({
position: "topleft",
zoomInText: '+',
zoomOutText: '-'
});
import L = require('leaflet');
const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13};
const latLngTuple: L.LatLngTuple = [12, 13];
let latLng: L.LatLng;
latLng = L.latLng(12, 13);
latLng = L.latLng(12, 13, 0);
latLng = L.latLng(latLngLiteral);
latLng = L.latLng({lat: 12, lng: 13, alt: 0});
latLng = L.latLng(latLngTuple);
latLng = L.latLng([12, 13, 0]);
const latLngBoundsLiteral: L.LatLngBoundsLiteral = [[12, 13], latLngTuple];
let latLngBounds: L.LatLngBounds;
latLngBounds = L.latLngBounds(latLng, latLng);
latLngBounds = L.latLngBounds(latLngLiteral, latLngLiteral);
latLngBounds = L.latLngBounds(latLngTuple, latLngTuple);
const pointTuple: L.PointTuple = [0, 0];
let point: L.Point;
point = L.point(12, 13);
point = L.point(12, 13, true);
point = L.point(pointTuple);
point = L.point({x: 12, y: 13});
const boundsLiteral: L.BoundsLiteral = [[1, 1], pointTuple];
let bounds: L.Bounds;
bounds = L.bounds(point, point);
bounds = L.bounds(pointTuple, pointTuple);
bounds = L.bounds([point, point]);
bounds = L.bounds(boundsLiteral);
let mapOptions: L.MapOptions = {};
mapOptions = {
preferCanvas: true,
attributionControl: false,
zoomControl: true,
closePopupOnClick: false,
zoomSnap: 1,
zoomDelta: 1,
trackResize: false,
boxZoom: true,
dragging: true,
// CRS
zoom: 12,
minZoom: 10,
maxZoom: 14,
fadeAnimation: true,
markerZoomAnimation: false,
transform3DLimit: 123,
zoomAnimation: false,
zoomAnimationThreshold: 4,
inertia: false,
inertiaDeceleration: 2000,
inertiaMaxSpeed: 1000,
easeLinearity: 0.5,
worldCopyJump: true,
maxBoundsViscosity: 1.0,
keyboard: false,
keyboardPanDelta: 100,
wheelDebounceTime: 30,
wheelPxPerZoomLevel: 25,
tap: false,
tapTolerance: 10,
bounceAtZoomLimits: false
};
mapOptions.doubleClickZoom = true;
mapOptions.doubleClickZoom = 'center';
mapOptions.center = latLng;
mapOptions.center = latLngLiteral;
mapOptions.center = latLngTuple;
mapOptions.layers = [];
mapOptions.layers = [L.tileLayer('')]; // add layers of other types
mapOptions.maxBounds = latLngBounds;
mapOptions.maxBounds = [];
mapOptions.maxBounds = latLngBoundsLiteral;
// mapOptions.renderer = ?
mapOptions.scrollWheelZoom = true;
mapOptions.scrollWheelZoom = 'center';
mapOptions.touchZoom = false;
mapOptions.touchZoom = 'center';
let layer: L.Layer;
const htmlElement = document.getElementById('foo');
let popupOptions: L.PopupOptions = {};
let tooltipOptions: L.TooltipOptions = {};
let zoomPanOptions: L.ZoomPanOptions = {};
zoomPanOptions = {
animate: false,
duration: 0.5,
easeLinearity: 0.6,
noMoveStart: true
};
let zoomOptions: L.ZoomOptions = {};
let panOptions: L.PanOptions = {};
let fitBoundsOptions: L.FitBoundsOptions = {};
let map = L.map('foo');
map = L.map('foo', mapOptions);
map = L.map(htmlElement);
map = L.map(htmlElement, mapOptions);
let doesItHaveLayer: boolean;
doesItHaveLayer = map.hasLayer(L.tileLayer(''));
// map.getRenderer
let html: HTMLElement;
html = map.createPane('foo');
html = map.createPane('foo', htmlElement)
html = map.getPane('foo');
html = map.getPane(htmlElement);
html = map.getContainer();
const panes = map.getPanes();
html = panes.mapPane;
html = panes.tilePane;
html = panes.overlayPane;
html = panes.shadowPane;
html = panes.markerPane;
html = panes.tooltipPane;
html = panes.popupPane;
html = panes['foo'];
let coordinates: L.LatLng;
coordinates = map.getCenter();
let zoom: number;
zoom = map.getZoom();
zoom = map.getMinZoom();
zoom = map.getMaxZoom();
zoom = map.getBoundsZoom(latLngBounds);
zoom = map.getBoundsZoom(latLngBounds, true);
zoom = map.getBoundsZoom(latLngBoundsLiteral);
zoom = map.getBoundsZoom(latLngBoundsLiteral, true);
let mapLatLngBounds: L.LatLngBounds;
mapLatLngBounds = map.getBounds();
let mapPoint: L.Point;
mapPoint = map.getSize();
mapPoint = map.getPixelOrigin();
let mapPixelBounds: L.Bounds;
mapPixelBounds = map.getPixelBounds();
mapPixelBounds = map.getPixelWorldBounds();
mapPixelBounds = map.getPixelWorldBounds(12);
map = map
// addControl
// removeControl
.addLayer(L.tileLayer(''))
.removeLayer(L.tileLayer('')) // use a different type of layer
.eachLayer((currentLayer) => {
layer = currentLayer;
})
.eachLayer((currentLayer) => {
layer = currentLayer;
}, {})
.openPopup(L.popup())
.openPopup('Hello World', latLng)
.openPopup('Hello World', latLng, popupOptions)
.openPopup('Hello World', latLngLiteral)
.openPopup('Hello World', latLngLiteral, popupOptions)
.openPopup('Hello World', latLngTuple)
.openPopup('Hello World', latLngTuple, popupOptions)
.openPopup(htmlElement, latLng)
.openPopup(htmlElement, latLng, popupOptions)
.openPopup(htmlElement, latLngLiteral)
.openPopup(htmlElement, latLngLiteral, popupOptions)
.openPopup(htmlElement, latLngTuple)
.openPopup(htmlElement, latLngTuple, popupOptions)
.closePopup()
.closePopup(L.popup())
.openTooltip(L.tooltip())
.openTooltip('Hello Word', latLng)
.openTooltip('Hello World', latLng, tooltipOptions)
.openTooltip('Hello World', latLngLiteral)
.openTooltip('Hello World', latLngLiteral, tooltipOptions)
.openTooltip('Hello World', latLngTuple)
.openTooltip('Hello World', latLngTuple, tooltipOptions)
.openTooltip(htmlElement, latLng)
.openTooltip(htmlElement, latLng, tooltipOptions)
.openTooltip(htmlElement, latLngLiteral)
.openTooltip(htmlElement, latLngLiteral, tooltipOptions)
.openTooltip(htmlElement, latLngTuple)
.openTooltip(htmlElement, latLngTuple, tooltipOptions)
.closeTooltip()
.closeTooltip(L.tooltip())
.setView(latLng, 12)
.setView(latLng, 12, zoomPanOptions)
.setView(latLngLiteral, 12)
.setView(latLngLiteral, 12, zoomPanOptions)
.setView(latLngTuple, 12)
.setView(latLngTuple, 12, zoomPanOptions)
.setZoom(12, zoomPanOptions) // investigate if zoomPanOptions are really required
.zoomIn()
.zoomIn(1)
.zoomIn(1, zoomOptions)
.zoomOut()
.zoomOut(1)
.zoomOut(1, zoomOptions)
.setZoomAround(latLng, 12, zoomOptions) // investigate if zoom options are really required
.setZoomAround(latLngLiteral, 12, zoomOptions)
.setZoomAround(latLngTuple, 12, zoomOptions)
.setZoomAround(point, 12, zoomOptions)
.setZoomAround(pointTuple, 11, zoomOptions)
.fitBounds(latLngBounds, fitBoundsOptions) // investigate if fit bounds options are really required
.fitBounds(latLngBoundsLiteral, fitBoundsOptions)
.fitWorld()
.fitWorld(fitBoundsOptions)
.panTo(latLng)
.panTo(latLng, panOptions)
.panTo(latLngLiteral)
.panTo(latLngLiteral, panOptions)
.panTo(latLngTuple)
.panTo(latLngTuple, panOptions)
.panBy(point)
.panBy(pointTuple)
.setMaxBounds(bounds) // investigate if this really receives Bounds instead of LatLngBounds
.setMaxBounds(boundsLiteral)
.setMinZoom(5)
.setMaxZoom(10)
.panInsideBounds(latLngBounds)
.panInsideBounds(latLngBounds, panOptions)
.panInsideBounds(latLngBoundsLiteral)
.panInsideBounds(latLngBoundsLiteral, panOptions)
.invalidateSize(zoomPanOptions)
.invalidateSize(false)
.stop()
.flyTo(latLng)
.flyTo(latLng, 12)
.flyTo(latLng, 12, zoomOptions)
.flyTo(latLngLiteral)
.flyTo(latLngLiteral, 12)
.flyTo(latLngLiteral, 12, zoomPanOptions)
.flyTo(latLngTuple)
.flyTo(latLngTuple, 12)
.flyTo(latLngTuple, 12, zoomPanOptions)
.flyToBounds(latLngBounds)
.flyToBounds(latLngBounds, fitBoundsOptions)
.flyToBounds(latLngBoundsLiteral)
.flyToBounds(latLngBoundsLiteral, fitBoundsOptions)
// addHandler
.remove()
.whenReady(() => {})
.whenReady(() => {}, {});
+820 -4275
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Maxime Fabre <https://github.com/anahkiasen/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts"/>
/// <reference path="../leaflet/leaflet-0.7.d.ts"/>
//////////////////////////////////////////////////////////////////////
///////////////////////////// MAP OBJECT /////////////////////////////
+5 -2
View File
@@ -344,6 +344,9 @@ declare namespace __MaterialUI {
disabledTextColor?: string;
connectorLineColor?: string;
};
svgIcon?: {
color?: string,
};
table?: {
backgroundColor?: string;
};
@@ -513,8 +516,8 @@ declare namespace __MaterialUI {
iconClassNameRight?: string;
iconElementLeft?: React.ReactElement<any>;
iconElementRight?: React.ReactElement<any>;
iconStyleRight?: string;
iconStyleLeft?: string;
iconStyleRight?: React.CSSProperties;
iconStyleLeft?: React.CSSProperties;
onLeftIconButtonTouchTap?: TouchTapEventHandler;
onRightIconButtonTouchTap?: TouchTapEventHandler;
onTitleTouchTap?: TouchTapEventHandler;
@@ -0,0 +1,52 @@
/// <reference path="./mongoose-sequence.d.ts" />
/// <reference path="../mongoose/mongoose.d.ts" />
/// <reference path="../express/express.d.ts" />
/**
* Based on the examples on: https://github.com/ramiel/mongoose-sequence
* Created by Linus Brolin <https://github.com/linusbrolin/>.
*/
import { SequenceDocument, SequenceOptions, SequenceSchema, Document, Schema, Model, model } from 'mongoose';
import * as mongooseSequence from 'mongoose-sequence';
//#region Test Models
interface User extends SequenceDocument {
name: string;
country: string;
city: string;
inhabitant_number: number;
}
const UserSchema: SequenceSchema = new Schema({
name: String,
country: String,
city: String,
inhabitant_number: Number
});
let seqOpts: SequenceOptions = { id: 'inhabitant_seq', inc_field: 'inhabitant_number', reference_fields: ['country', 'city'] };
UserSchema.plugin(mongooseSequence, seqOpts);
let UserModel: Model<User> = model<User>('User', UserSchema);
//#endregion
//#region Test Sequence
let user: User = new UserModel({
name: 'Patrice',
country: 'France',
city: 'Paris'
});
user.save();
console.log(user.inhabitant_number);
user.setNext('inhabitant_seq', function(err: any, user: User) {
if (err) {
console.log(err);
return;
}
if (user) {
console.log(user.inhabitant_number);
}
});
//#endregion
+36
View File
@@ -0,0 +1,36 @@
// Type definitions for mongoose-sequence 3.0.2
// Project: https://github.com/ramiel/mongoose-sequence
// Definitions by: Linus Brolin <https://github.com/linusbrolin/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../mongoose/mongoose.d.ts" />
declare module 'mongoose' {
export interface SequenceOptions {
inc_field: string; // The name of the field to increment. Mandatory, default is _id
id?: string; // Id of the sequence. Is mandatory only for scoped sequences but its use is strongly encouraged.
reference_fields?: Array<string>; // The field to reference for a scoped counter. Optional
disable_hooks?: boolean; // If true, the counter will not be incremented on saving a new document. Default to false
collection_name?: string; // By default the collection name to mantain the status of the counters is counters. You can override it using this option
}
export interface SequenceDocument extends Document {
setNext(sequenceId: string, callback: (err: any, res: SequenceDocument) => void): void;
}
export interface SequenceSchema extends Schema {
plugin(
plugin: (schema: SequenceSchema, options: SequenceOptions) => void,
options: SequenceOptions
): this;
// overload for the default mongoose plugin function
plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this;
}
}
declare module 'mongoose-sequence' {
import mongoose = require('mongoose');
var _: (schema: mongoose.Schema, options?: Object) => void;
export = _;
}
+3 -2
View File
@@ -37,10 +37,11 @@ namespace NavigationTests {
person.navigated = (data) => {};
person.urlEncode = function urlEncode(state: Navigation.State, key: string, val: string, queryString: boolean): string {
return queryString ? val.replace(/\s/g, '+') : encodeURIComponent(val);
}
};
person.urlDecode = function urlDecode(state: Navigation.State, key: string, val: string, queryString: boolean): string {
return queryString ? val.replace(/\+/g, ' ') : decodeURIComponent(val);
}
};
person.validate = (data: any) => data.id > 0;
// Navigation Event
var navigationListener = (oldState: Navigation.State, state: Navigation.State, data: any, asyncData: any) => {
+12 -10
View File
@@ -138,6 +138,12 @@ declare namespace Navigation {
* @param queryString A value indicating the Url value's location
*/
urlDecode(state: State, key: string, val: string, queryString: boolean): string;
/**
* Validates the NavigationData before navigating to the new State
* @param data The new NavigationData
* @returns Validation success indicator
*/
validate(data: any): boolean;
/**
* Truncates the crumb trail whenever a repeated or initial State is
* encountered
@@ -178,9 +184,9 @@ declare namespace Navigation {
*/
getHref(url: string): string;
/**
* Gets a Url from the anchor
* Gets a Url from the anchor or location
*/
getUrl(anchor: HTMLAnchorElement): string;
getUrl(hrefElement: HTMLAnchorElement | Location): string;
/**
* Removes browser history event listeners
*/
@@ -230,9 +236,9 @@ declare namespace Navigation {
*/
getHref(url: string): string;
/**
* Gets a Url from the anchor
* Gets a Url from the anchor or location
*/
getUrl(anchor: HTMLAnchorElement): string;
getUrl(hrefElement: HTMLAnchorElement | Location): string;
/**
* Removes a listener for the hashchange event
*/
@@ -281,9 +287,9 @@ declare namespace Navigation {
*/
getHref(url: string): string;
/**
* Gets a Url from the anchor
* Gets a Url from the anchor or location
*/
getUrl(anchor: HTMLAnchorElement): string;
getUrl(hrefElement: HTMLAnchorElement | Location): string;
/**
* Removes a listener for the popstate event
*/
@@ -381,10 +387,6 @@ declare namespace Navigation {
* Crumb first
*/
crumbs: Crumb[];
/**
* Gets the crumb trail
*/
crumbTrail: string[];
/**
* Gets the next crumb
*/
+170 -150
View File
@@ -28,37 +28,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer
/// Assert Tests : https://nodejs.org/api/assert.html ///
//////////////////////////////////////////////////////////
namespace assert_tests{
namespace assert_tests {
{
assert(1 + 1 - 2 === 0, "The universe isn't how it should.");
assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP");
// TODO: assert.deepStrictEqual
assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator");
assert.doesNotThrow(() => {
const b = false;
if (b) { throw "a hammer at your face"; }
}, undefined, "What the...*crunch*");
assert.equal(3, "3", "uses == comparator");
// TODO: assert.fail
// TODO: assert.ifError
assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator");
// TODO: assert.notDeepStrictEqual
// TODO: assert.notEqual
assert.fail(1, 2, undefined, '>');
assert.ifError(0);
assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator");
assert.notEqual(1, 2, "uses != comparator");
assert.notStrictEqual(2, "2", "uses === comparator");
// TODO: assert.ok
// TODO: assert.strictEqual
assert.ok(true);
assert.ok(1);
assert.strictEqual(1, 1, "uses === comparator");
assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT");
}
}
@@ -109,6 +108,16 @@ namespace events_tests {
result = emitter.emit(event, any, any);
result = emitter.emit(event, any, any, any);
}
{
class Networker extends events.EventEmitter {
constructor() {
super();
this.emit("mingling");
}
}
}
}
////////////////////////////////////////////////////
@@ -136,13 +145,13 @@ namespace fs_tests {
var buffer: Buffer;
content = fs.readFileSync('testfile', 'utf8');
content = fs.readFileSync('testfile', {encoding : 'utf8'});
content = fs.readFileSync('testfile', { encoding: 'utf8' });
buffer = fs.readFileSync('testfile');
buffer = fs.readFileSync('testfile', {flag : 'r'});
buffer = fs.readFileSync('testfile', { flag: 'r' });
fs.readFile('testfile', 'utf8', (err, data) => content = data);
fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data);
fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data);
fs.readFile('testfile', (err, data) => buffer = data);
fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data);
fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data);
}
{
@@ -168,21 +177,13 @@ namespace fs_tests {
}
class Networker extends events.EventEmitter {
constructor() {
super();
this.emit("mingling");
}
}
///////////////////////////////////////////////////////
/// Buffer tests : https://nodejs.org/api/buffer.html
///////////////////////////////////////////////////////
function bufferTests() {
var utf8Buffer = new Buffer('test');
var base64Buffer = new Buffer('','base64');
var base64Buffer = new Buffer('', 'base64');
var octets: Uint8Array = null;
var octetBuffer = new Buffer(octets);
var sharedBuffer = new Buffer(octets.buffer);
@@ -196,7 +197,7 @@ function bufferTests() {
// Class Method: Buffer.from(array)
{
const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
}
// Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
@@ -261,8 +262,8 @@ function bufferTests() {
// Buffer has Uint8Array's buffer field (an ArrayBuffer).
{
let buffer = new Buffer('123');
let octets = new Uint8Array(buffer.buffer);
let buffer = new Buffer('123');
let octets = new Uint8Array(buffer.buffer);
}
}
@@ -274,14 +275,14 @@ function bufferTests() {
namespace url_tests {
{
url.format(url.parse('http://www.example.com/xyz'));
// https://google.com/search?q=you're%20a%20lizard%2C%20gary
url.format({
protocol: 'https',
host: "google.com",
pathname: 'search',
query: { q: "you're a lizard, gary" }
});
});
}
{
@@ -298,7 +299,7 @@ namespace util_tests {
{
// Old and new util.inspect APIs
util.inspect(["This is nice"], false, 5);
util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false });
util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false });
}
}
@@ -315,113 +316,121 @@ function stream_readable_pipe_test() {
r.close();
}
////////////////////////////////////////////////////
/// Crypto tests : http://nodejs.org/api/crypto.html
////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// Crypto tests : http://nodejs.org/api/crypto.html ///
////////////////////////////////////////////////////////
var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex');
namespace crypto_tests {
{
var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex');
}
{
let hmac: crypto.Hmac;
(hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => {
let hash: Buffer|string = hmac.read();
{
let hmac: crypto.Hmac;
(hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => {
let hash: Buffer | string = hmac.read();
});
}
{
//crypto_cipher_decipher_string_test
let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
let clearText: string = "This is the clear text.";
let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
let cipherText: string = cipher.update(clearText, "utf8", "hex");
cipherText += cipher.final("hex");
let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
let clearText2: string = decipher.update(cipherText, "hex", "utf8");
clearText2 += decipher.final("utf8");
assert.equal(clearText2, clearText);
}
{
//crypto_cipher_decipher_buffer_test
let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]);
let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
let cipherBuffers: Buffer[] = [];
cipherBuffers.push(cipher.update(clearText));
cipherBuffers.push(cipher.final());
let cipherText: Buffer = Buffer.concat(cipherBuffers);
let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
let decipherBuffers: Buffer[] = [];
decipherBuffers.push(decipher.update(cipherText));
decipherBuffers.push(decipher.final());
let clearText2: Buffer = Buffer.concat(decipherBuffers);
assert.deepEqual(clearText2, clearText);
}
}
//////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html ///
//////////////////////////////////////////////////
namespace tls_tests {
var ctx: tls.SecureContext = tls.createSecureContext({
key: "NOT REALLY A KEY",
cert: "SOME CERTIFICATE",
});
}
var blah = ctx.context;
function crypto_cipher_decipher_string_test() {
var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
var clearText:string = "This is the clear text.";
var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
var cipherText:string = cipher.update(clearText, "utf8", "hex");
cipherText += cipher.final("hex");
var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
var clearText2:string = decipher.update(cipherText, "hex", "utf8");
clearText2 += decipher.final("utf8");
assert.equal(clearText2, clearText);
}
function crypto_cipher_decipher_buffer_test() {
var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]);
var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
var cipherBuffers:Buffer[] = [];
cipherBuffers.push(cipher.update(clearText));
cipherBuffers.push(cipher.final());
var cipherText:Buffer = Buffer.concat(cipherBuffers);
var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
var decipherBuffers:Buffer[] = [];
decipherBuffers.push(decipher.update(cipherText));
decipherBuffers.push(decipher.final());
var clearText2:Buffer = Buffer.concat(decipherBuffers);
assert.deepEqual(clearText2, clearText);
var connOpts: tls.ConnectionOptions = {
host: "127.0.0.1",
port: 55
};
var tlsSocket = tls.connect(connOpts);
}
////////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html
/// Http tests : http://nodejs.org/api/http.html ///
////////////////////////////////////////////////////
var ctx: tls.SecureContext = tls.createSecureContext({
key: "NOT REALLY A KEY",
cert: "SOME CERTIFICATE",
});
var blah = ctx.context;
var tlsOpts: tls.TlsOptions = {
host: "127.0.0.1",
port: 55
};
var tlsSocket = tls.connect(tlsOpts);
////////////////////////////////////////////////////
// Make sure .listen() and .close() retuern a Server instance
http.createServer().listen(0).close().address();
net.createServer().listen(0).close().address();
var request = http.request('http://0.0.0.0');
request.once('error', function () {});
request.setNoDelay(true);
request.abort();
////////////////////////////////////////////////////
/// Http tests : http://nodejs.org/api/http.html
////////////////////////////////////////////////////
namespace http_tests {
// Status codes
var code = 100;
var codeMessage = http.STATUS_CODES['400'];
var codeMessage = http.STATUS_CODES[400];
{
// Status codes
var codeMessage = http.STATUS_CODES['400'];
var codeMessage = http.STATUS_CODES[400];
}
var agent: http.Agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxFreeSockets: 256
});
{
var agent: http.Agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxFreeSockets: 256
});
var agent: http.Agent = http.globalAgent;
var agent: http.Agent = http.globalAgent;
http.request({
agent: false
});
http.request({
agent: agent
});
http.request({
agent: undefined
});
http.request({ agent: false });
http.request({ agent: agent });
http.request({ agent: undefined });
}
{
// Make sure .listen() and .close() retuern a Server instance
http.createServer().listen(0).close().address();
net.createServer().listen(0).close().address();
}
{
var request = http.request('http://0.0.0.0');
request.once('error', function() { });
request.setNoDelay(true);
request.abort();
}
}
////////////////////////////////////////////////////
/// Https tests : http://nodejs.org/api/https.html
////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// Https tests : http://nodejs.org/api/https.html ///
//////////////////////////////////////////////////////
namespace https_tests {
var agent: https.Agent = new https.Agent({
keepAlive: true,
@@ -478,7 +487,7 @@ namespace dgram_tests {
////////////////////////////////////////////////////
namespace querystring_tests {
type SampleObject = {a: string; b: number;}
type SampleObject = { a: string; b: number; }
{
let obj: SampleObject;
@@ -531,7 +540,7 @@ namespace path_tests {
try {
path.join('foo', {}, 'bar');
}
catch(error) {
catch (error) {
}
@@ -645,11 +654,11 @@ namespace path_tests {
// }
path.format({
root : "/",
dir : "/home/user/dir",
base : "file.txt",
ext : ".txt",
name : "file"
root: "/",
dir: "/home/user/dir",
base: "file.txt",
ext: ".txt",
name: "file"
});
// returns
// '/home/user/dir/file.txt'
@@ -715,7 +724,7 @@ namespace readline_tests {
}
{
let data: string|Buffer;
let data: string | Buffer;
let key: readline.Key;
rl.write(data);
@@ -732,8 +741,8 @@ namespace readline_tests {
{
let stream: NodeJS.WritableStream;
let dx: number|string;
let dy: number|string;
let dx: number | string;
let dy: number | string;
readline.moveCursor(stream, dx, dy);
}
@@ -771,7 +780,7 @@ namespace string_decoder_tests {
namespace child_process_tests {
{
childProcess.exec("echo test");
childProcess.spawnSync("echo test");
childProcess.spawnSync("echo test");
}
}
@@ -779,7 +788,7 @@ namespace child_process_tests {
/// cluster tests: https://nodejs.org/api/cluster.html ///
//////////////////////////////////////////////////////////////////////
namespace cluster_tests {
namespace cluster_tests  {
{
cluster.fork();
Object.keys(cluster.workers).forEach(key => {
@@ -831,7 +840,7 @@ namespace os_tests {
}
{
let result: {[index: string]: os.NetworkInterfaceInfo[]};
let result: { [index: string]: os.NetworkInterfaceInfo[] };
result = os.networkInterfaces();
}
@@ -905,14 +914,13 @@ namespace errors_tests {
///////////////////////////////////////////////////////////
import * as p from "process";
namespace process_tests{
namespace process_tests {
{
var eventEmitter: events.EventEmitter;
eventEmitter = process; // Test that process implements EventEmitter...
var _p: NodeJS.Process = process;
_p = p;
assert(p === process);
}
}
@@ -921,8 +929,20 @@ namespace process_tests{
///////////////////////////////////////////////////////////
import * as c from "console";
namespace console_tests{
namespace console_tests {
{
assert(c === console);
var _c: Console = console;
_c = c;
}
}
///////////////////////////////////////////////////
/// Net Tests : https://nodejs.org/api/net.html ///
///////////////////////////////////////////////////
namespace net_tests {
{
// Make sure .listen() and .close() retuern a Server instance
net.createServer().listen(0).close().address();
}
}
+1 -1
View File
@@ -430,7 +430,7 @@ declare namespace NodeJS {
interface NodeBuffer extends Uint8Array {
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
toJSON(): any;
toJSON(): {type: 'Buffer', data: any[]};
equals(otherBuffer: Buffer): boolean;
compare(otherBuffer: Buffer): number;
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
+212 -192
View File
@@ -30,37 +30,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer
/// Assert Tests : https://nodejs.org/api/assert.html ///
//////////////////////////////////////////////////////////
namespace assert_tests{
namespace assert_tests {
{
assert(1 + 1 - 2 === 0, "The universe isn't how it should.");
assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP");
// TODO: assert.deepStrictEqual
assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator");
assert.doesNotThrow(() => {
const b = false;
if (b) { throw "a hammer at your face"; }
}, undefined, "What the...*crunch*");
assert.equal(3, "3", "uses == comparator");
// TODO: assert.fail
// TODO: assert.ifError
assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator");
// TODO: assert.notDeepStrictEqual
// TODO: assert.notEqual
assert.fail(1, 2, undefined, '>');
assert.ifError(0);
assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator");
assert.notEqual(1, 2, "uses != comparator");
assert.notStrictEqual(2, "2", "uses === comparator");
// TODO: assert.ok
// TODO: assert.strictEqual
assert.ok(true);
assert.ok(1);
assert.strictEqual(1, 1, "uses === comparator");
assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT");
}
}
@@ -119,6 +118,16 @@ namespace events_tests {
result = emitter.eventNames();
}
{
class Networker extends events.EventEmitter {
constructor() {
super();
this.emit("mingling");
}
}
}
}
////////////////////////////////////////////////////
@@ -130,31 +139,31 @@ namespace fs_tests {
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.write(1234, "test");
fs.writeFile("Harry Potter",
"\"You be wizzing, Harry,\" jived Dumbledore.",
{
encoding: "ascii"
},
assert.ifError);
assert.ifError);
}
{
var content: string;
var buffer: Buffer;
content = fs.readFileSync('testfile', 'utf8');
content = fs.readFileSync('testfile', {encoding : 'utf8'});
content = fs.readFileSync('testfile', { encoding: 'utf8' });
buffer = fs.readFileSync('testfile');
buffer = fs.readFileSync('testfile', {flag : 'r'});
buffer = fs.readFileSync('testfile', { flag: 'r' });
fs.readFile('testfile', 'utf8', (err, data) => content = data);
fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data);
fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data);
fs.readFile('testfile', (err, data) => buffer = data);
fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data);
fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data);
}
{
var errno: string;
fs.readFile('testfile', (err, data) => {
@@ -163,71 +172,63 @@ namespace fs_tests {
}
});
}
{
fs.mkdtemp('/tmp/foo-', (err, folder) => {
console.log(folder);
// Prints: /tmp/foo-itXde2
});
}
{
var tempDir: string;
tempDir = fs.mkdtempSync('/tmp/foo-');
}
{
fs.watch('/tmp/foo-', (event, filename) => {
console.log(event, filename);
console.log(event, filename);
});
fs.watch('/tmp/foo-', 'utf8', (event, filename) => {
console.log(event, filename);
console.log(event, filename);
});
fs.watch('/tmp/foo-', {
recursive: true,
persistent: true,
encoding: 'utf8'
recursive: true,
persistent: true,
encoding: 'utf8'
}, (event, filename) => {
console.log(event, filename);
console.log(event, filename);
});
}
{
fs.access('/path/to/folder', (err) => {});
fs.access(Buffer.from(''), (err) => {});
fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => {});
fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => {});
fs.access('/path/to/folder', (err) => { });
fs.access(Buffer.from(''), (err) => { });
fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { });
fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { });
fs.accessSync('/path/to/folder');
fs.accessSync(Buffer.from(''));
fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK);
fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK);
}
}
class Networker extends events.EventEmitter {
constructor() {
super();
this.emit("mingling");
}
}
///////////////////////////////////////////////////////
/// Buffer tests : https://nodejs.org/api/buffer.html
///////////////////////////////////////////////////////
function bufferTests() {
var utf8Buffer = new Buffer('test');
var base64Buffer = new Buffer('','base64');
var base64Buffer = new Buffer('', 'base64');
var octets: Uint8Array = null;
var octetBuffer = new Buffer(octets);
var sharedBuffer = new Buffer(octets.buffer);
@@ -249,7 +250,7 @@ function bufferTests() {
// Class Method: Buffer.from(array)
{
const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
}
// Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
@@ -372,8 +373,8 @@ function bufferTests() {
// Buffer has Uint8Array's buffer field (an ArrayBuffer).
{
let buffer = new Buffer('123');
let octets = new Uint8Array(buffer.buffer);
let buffer = new Buffer('123');
let octets = new Uint8Array(buffer.buffer);
}
}
@@ -385,14 +386,14 @@ function bufferTests() {
namespace url_tests {
{
url.format(url.parse('http://www.example.com/xyz'));
// https://google.com/search?q=you're%20a%20lizard%2C%20gary
url.format({
protocol: 'https',
host: "google.com",
pathname: 'search',
query: { q: "you're a lizard, gary" }
});
});
}
{
@@ -409,7 +410,7 @@ namespace util_tests {
{
// Old and new util.inspect APIs
util.inspect(["This is nice"], false, 5);
util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false });
util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false });
}
}
@@ -429,18 +430,18 @@ function stream_readable_pipe_test() {
// Simplified constructors
function simplified_stream_ctor_test() {
new stream.Readable({
read: function (size) {
read: function(size) {
size.toFixed();
}
});
new stream.Writable({
write: function (chunk, enc, cb) {
write: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb()
},
writev: function (chunks, cb) {
writev: function(chunks, cb) {
chunks[0].chunk.slice(0);
chunks[0].encoding.charAt(0);
cb();
@@ -448,15 +449,15 @@ function simplified_stream_ctor_test() {
});
new stream.Duplex({
read: function (size) {
read: function(size) {
size.toFixed();
},
write: function (chunk, enc, cb) {
write: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb()
},
writev: function (chunks, cb) {
writev: function(chunks, cb) {
chunks[0].chunk.slice(0);
chunks[0].encoding.charAt(0);
cb();
@@ -466,23 +467,23 @@ function simplified_stream_ctor_test() {
});
new stream.Transform({
transform: function (chunk, enc, cb) {
transform: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb();
},
flush: function (cb) {
flush: function(cb) {
cb()
},
read: function (size) {
read: function(size) {
size.toFixed();
},
write: function (chunk, enc, cb) {
write: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb()
},
writev: function (chunks, cb) {
writev: function(chunks, cb) {
chunks[0].chunk.slice(0);
chunks[0].encoding.charAt(0);
cb();
@@ -490,113 +491,121 @@ function simplified_stream_ctor_test() {
})
}
////////////////////////////////////////////////////
/// Crypto tests : http://nodejs.org/api/crypto.html
////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// Crypto tests : http://nodejs.org/api/crypto.html ///
////////////////////////////////////////////////////////
var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex');
namespace crypto_tests {
{
var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex');
}
{
let hmac: crypto.Hmac;
(hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => {
let hash: Buffer|string = hmac.read();
{
let hmac: crypto.Hmac;
(hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => {
let hash: Buffer | string = hmac.read();
});
}
{
//crypto_cipher_decipher_string_test
let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
let clearText: string = "This is the clear text.";
let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
let cipherText: string = cipher.update(clearText, "utf8", "hex");
cipherText += cipher.final("hex");
let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
let clearText2: string = decipher.update(cipherText, "hex", "utf8");
clearText2 += decipher.final("utf8");
assert.equal(clearText2, clearText);
}
{
//crypto_cipher_decipher_buffer_test
let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]);
let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
let cipherBuffers: Buffer[] = [];
cipherBuffers.push(cipher.update(clearText));
cipherBuffers.push(cipher.final());
let cipherText: Buffer = Buffer.concat(cipherBuffers);
let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
let decipherBuffers: Buffer[] = [];
decipherBuffers.push(decipher.update(cipherText));
decipherBuffers.push(decipher.final());
let clearText2: Buffer = Buffer.concat(decipherBuffers);
assert.deepEqual(clearText2, clearText);
}
}
//////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html ///
//////////////////////////////////////////////////
namespace tls_tests {
var ctx: tls.SecureContext = tls.createSecureContext({
key: "NOT REALLY A KEY",
cert: "SOME CERTIFICATE",
});
}
var blah = ctx.context;
function crypto_cipher_decipher_string_test() {
var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
var clearText:string = "This is the clear text.";
var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
var cipherText:string = cipher.update(clearText, "utf8", "hex");
cipherText += cipher.final("hex");
var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
var clearText2:string = decipher.update(cipherText, "hex", "utf8");
clearText2 += decipher.final("utf8");
assert.equal(clearText2, clearText);
}
function crypto_cipher_decipher_buffer_test() {
var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]);
var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
var cipherBuffers:Buffer[] = [];
cipherBuffers.push(cipher.update(clearText));
cipherBuffers.push(cipher.final());
var cipherText:Buffer = Buffer.concat(cipherBuffers);
var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
var decipherBuffers:Buffer[] = [];
decipherBuffers.push(decipher.update(cipherText));
decipherBuffers.push(decipher.final());
var clearText2:Buffer = Buffer.concat(decipherBuffers);
assert.deepEqual(clearText2, clearText);
var connOpts: tls.ConnectionOptions = {
host: "127.0.0.1",
port: 55
};
var tlsSocket = tls.connect(connOpts);
}
////////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html
/// Http tests : http://nodejs.org/api/http.html ///
////////////////////////////////////////////////////
var ctx: tls.SecureContext = tls.createSecureContext({
key: "NOT REALLY A KEY",
cert: "SOME CERTIFICATE",
});
var blah = ctx.context;
var connOpts: tls.ConnectionOptions = {
host: "127.0.0.1",
port: 55
};
var tlsSocket = tls.connect(connOpts);
////////////////////////////////////////////////////
// Make sure .listen() and .close() retuern a Server instance
http.createServer().listen(0).close().address();
net.createServer().listen(0).close().address();
var request = http.request('http://0.0.0.0');
request.once('error', function () {});
request.setNoDelay(true);
request.abort();
////////////////////////////////////////////////////
/// Http tests : http://nodejs.org/api/http.html
////////////////////////////////////////////////////
namespace http_tests {
// Status codes
var code = 100;
var codeMessage = http.STATUS_CODES['400'];
var codeMessage = http.STATUS_CODES[400];
{
// Status codes
var codeMessage = http.STATUS_CODES['400'];
var codeMessage = http.STATUS_CODES[400];
}
var agent: http.Agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxFreeSockets: 256
});
{
var agent: http.Agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxFreeSockets: 256
});
var agent: http.Agent = http.globalAgent;
var agent: http.Agent = http.globalAgent;
http.request({
agent: false
});
http.request({
agent: agent
});
http.request({
agent: undefined
});
http.request({ agent: false });
http.request({ agent: agent });
http.request({ agent: undefined });
}
{
// Make sure .listen() and .close() retuern a Server instance
http.createServer().listen(0).close().address();
net.createServer().listen(0).close().address();
}
{
var request = http.request('http://0.0.0.0');
request.once('error', function() { });
request.setNoDelay(true);
request.abort();
}
}
////////////////////////////////////////////////////
/// Https tests : http://nodejs.org/api/https.html
////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// Https tests : http://nodejs.org/api/https.html ///
//////////////////////////////////////////////////////
namespace https_tests {
var agent: https.Agent = new https.Agent({
keepAlive: true,
@@ -656,7 +665,7 @@ namespace dgram_tests {
////////////////////////////////////////////////////
namespace querystring_tests {
type SampleObject = {a: string; b: number;}
type SampleObject = { a: string; b: number; }
{
let obj: SampleObject;
@@ -709,7 +718,7 @@ namespace path_tests {
try {
path.join('foo', {}, 'bar');
}
catch(error) {
catch (error) {
}
@@ -823,11 +832,11 @@ namespace path_tests {
// }
path.format({
root : "/",
dir : "/home/user/dir",
base : "file.txt",
ext : ".txt",
name : "file"
root: "/",
dir: "/home/user/dir",
base: "file.txt",
ext: ".txt",
name: "file"
});
// returns
// '/home/user/dir/file.txt'
@@ -893,7 +902,7 @@ namespace readline_tests {
}
{
let data: string|Buffer;
let data: string | Buffer;
let key: readline.Key;
rl.write(data);
@@ -910,8 +919,8 @@ namespace readline_tests {
{
let stream: NodeJS.WritableStream;
let dx: number|string;
let dy: number|string;
let dx: number | string;
let dy: number | string;
readline.moveCursor(stream, dx, dy);
}
@@ -952,7 +961,7 @@ namespace string_decoder_tests {
namespace child_process_tests {
{
childProcess.exec("echo test");
childProcess.spawnSync("echo test");
childProcess.spawnSync("echo test");
}
}
@@ -960,7 +969,7 @@ namespace child_process_tests {
/// cluster tests: https://nodejs.org/api/cluster.html ///
//////////////////////////////////////////////////////////////////////
namespace cluster_tests {
namespace cluster_tests  {
{
cluster.fork();
Object.keys(cluster.workers).forEach(key => {
@@ -1012,7 +1021,7 @@ namespace os_tests {
}
{
let result: {[index: string]: os.NetworkInterfaceInfo[]};
let result: { [index: string]: os.NetworkInterfaceInfo[] };
result = os.networkInterfaces();
}
@@ -1073,19 +1082,19 @@ namespace vm_tests {
namespace timers_tests {
{
let immediateId = timers.setImmediate(function(){ console.log("immediate"); });
let immediateId = timers.setImmediate(function() { console.log("immediate"); });
timers.clearImmediate(immediateId);
}
{
let counter = 0;
let timeout = timers.setInterval(function(){ console.log("interval"); }, 20);
let timeout = timers.setInterval(function() { console.log("interval"); }, 20);
timeout.unref();
timeout.ref();
timers.clearInterval(timeout);
}
{
let counter = 0;
let timeout = timers.setTimeout(function(){ console.log("timeout"); }, 20);
let timeout = timers.setTimeout(function() { console.log("timeout"); }, 20);
timeout.unref();
timeout.ref();
timers.clearTimeout(timeout);
@@ -1111,14 +1120,13 @@ namespace errors_tests {
///////////////////////////////////////////////////////////
import * as p from "process";
namespace process_tests{
namespace process_tests {
{
var eventEmitter: events.EventEmitter;
eventEmitter = process; // Test that process implements EventEmitter...
var _p: NodeJS.Process = process;
_p = p;
assert(p === process);
}
}
@@ -1127,9 +1135,21 @@ namespace process_tests{
///////////////////////////////////////////////////////////
import * as c from "console";
namespace console_tests{
namespace console_tests {
{
assert(c === console);
var _c: Console = console;
_c = c;
}
}
///////////////////////////////////////////////////
/// Net Tests : https://nodejs.org/api/net.html ///
///////////////////////////////////////////////////
namespace net_tests {
{
// Make sure .listen() and .close() retuern a Server instance
net.createServer().listen(0).close().address();
}
}
+431 -41
View File
@@ -281,8 +281,8 @@ declare namespace NodeJS {
}
export interface ReadWriteStream extends ReadableStream, WritableStream {
pause(): ReadWriteStream;
resume(): ReadWriteStream;
pause(): ReadWriteStream;
resume(): ReadWriteStream;
}
export interface Events extends EventEmitter { }
@@ -456,7 +456,7 @@ declare namespace NodeJS {
}
}
interface IterableIterator<T> {}
interface IterableIterator<T> { }
/**
* @deprecated
@@ -464,7 +464,7 @@ interface IterableIterator<T> {}
interface NodeBuffer extends Uint8Array {
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
toJSON(): any;
toJSON(): {type: 'Buffer', data: any[]};
equals(otherBuffer: Buffer): boolean;
compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
@@ -588,10 +588,11 @@ declare module "http" {
agent?: Agent | boolean;
}
export interface Server extends events.EventEmitter, net.Server {
export interface Server extends net.Server {
setTimeout(msecs: number, callback: Function): void;
maxHeadersCount: number;
timeout: number;
listening: boolean;
}
/**
* @deprecated Use IncomingMessage
@@ -599,7 +600,7 @@ declare module "http" {
export interface ServerRequest extends IncomingMessage {
connection: net.Socket;
}
export interface ServerResponse extends events.EventEmitter, stream.Writable {
export interface ServerResponse extends stream.Writable {
// Extended base methods
write(buffer: Buffer): boolean;
write(buffer: Buffer, cb?: Function): boolean;
@@ -629,7 +630,7 @@ declare module "http" {
end(str: string, encoding?: string, cb?: Function): void;
end(data?: any, encoding?: string): void;
}
export interface ClientRequest extends events.EventEmitter, stream.Writable {
export interface ClientRequest extends stream.Writable {
// Extended base methods
write(buffer: Buffer): boolean;
write(buffer: Buffer, cb?: Function): boolean;
@@ -655,11 +656,11 @@ declare module "http" {
end(str: string, encoding?: string, cb?: Function): void;
end(data?: any, encoding?: string): void;
}
export interface IncomingMessage extends events.EventEmitter, stream.Readable {
export interface IncomingMessage extends stream.Readable {
httpVersion: string;
httpVersionMajor: string;
httpVersionMinor: string;
connection: any;
connection: net.Socket;
headers: any;
rawHeaders: string[];
trailers: any;
@@ -741,17 +742,30 @@ declare module "http" {
declare module "cluster" {
import * as child from "child_process";
import * as events from "events";
import * as net from "net";
// interfaces
export interface ClusterSettings {
execArgv?: string[]; // default: process.execArgv
exec?: string;
args?: string[];
silent?: boolean;
stdio?: any[];
uid?: number;
gid?: number;
}
export interface ClusterSetupMasterSettings {
exec?: string; // default: process.argv[1]
args?: string[]; // default: process.argv.slice(2)
silent?: boolean; // default: false
stdio?: any[];
}
export interface Address {
address: string;
port: number;
addressType: string;
addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6"
}
export class Worker extends events.EventEmitter {
@@ -764,35 +778,205 @@ declare module "cluster" {
disconnect(): void;
isConnected(): boolean;
isDead(): boolean;
exitedAfterDisconnect: boolean;
/**
* events.EventEmitter
* 1. disconnect
* 2. error
* 3. exit
* 4. listening
* 5. message
* 6. online
*/
addListener(event: string, listener: Function): this;
addListener(event: "disconnect", listener: () => void): this;
addListener(event: "error", listener: (code: number, signal: string) => void): this;
addListener(event: "exit", listener: (code: number, signal: string) => void): this;
addListener(event: "listening", listener: (address: Address) => void): this;
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: () => void): this;
on(event: string, listener: Function): this;
on(event: "disconnect", listener: () => void): this;
on(event: "error", listener: (code: number, signal: string) => void): this;
on(event: "exit", listener: (code: number, signal: string) => void): this;
on(event: "listening", listener: (address: Address) => void): this;
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: () => void): this;
once(event: string, listener: Function): this;
once(event: "disconnect", listener: () => void): this;
once(event: "error", listener: (code: number, signal: string) => void): this;
once(event: "exit", listener: (code: number, signal: string) => void): this;
once(event: "listening", listener: (address: Address) => void): this;
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: () => void): this;
prependListener(event: string, listener: Function): this;
prependListener(event: "disconnect", listener: () => void): this;
prependListener(event: "error", listener: (code: number, signal: string) => void): this;
prependListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependListener(event: "listening", listener: (address: Address) => void): this;
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: "online", listener: () => void): this;
prependOnceListener(event: string, listener: Function): this;
prependOnceListener(event: "disconnect", listener: () => void): this;
prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this;
prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependOnceListener(event: "listening", listener: (address: Address) => void): this;
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: "online", listener: () => void): this;
}
export var settings: ClusterSettings;
export interface Cluster extends events.EventEmitter {
Worker: Worker;
disconnect(callback?: Function): void;
fork(env?: any): Worker;
isMaster: boolean;
isWorker: boolean;
// TODO: cluster.schedulingPolicy
settings: ClusterSettings;
setupMaster(settings?: ClusterSetupMasterSettings): void;
worker: Worker;
workers: {
[index: string]: Worker
};
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
addListener(event: string, listener: Function): this;
addListener(event: "disconnect", listener: (worker: Worker) => void): this;
addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
addListener(event: "fork", listener: (worker: Worker) => void): this;
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: (worker: Worker) => void): this;
addListener(event: "setup", listener: (settings: any) => void): this;
on(event: string, listener: Function): this;
on(event: "disconnect", listener: (worker: Worker) => void): this;
on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
on(event: "fork", listener: (worker: Worker) => void): this;
on(event: "listening", listener: (worker: Worker, address: Address) => void): this;
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: (worker: Worker) => void): this;
on(event: "setup", listener: (settings: any) => void): this;
once(event: string, listener: Function): this;
once(event: "disconnect", listener: (worker: Worker) => void): this;
once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
once(event: "fork", listener: (worker: Worker) => void): this;
once(event: "listening", listener: (worker: Worker, address: Address) => void): this;
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: (worker: Worker) => void): this;
once(event: "setup", listener: (settings: any) => void): this;
prependListener(event: string, listener: Function): this;
prependListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependListener(event: "fork", listener: (worker: Worker) => void): this;
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: "online", listener: (worker: Worker) => void): this;
prependListener(event: "setup", listener: (settings: any) => void): this;
prependOnceListener(event: string, listener: Function): this;
prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependOnceListener(event: "fork", listener: (worker: Worker) => void): this;
prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: "online", listener: (worker: Worker) => void): this;
prependOnceListener(event: "setup", listener: (settings: any) => void): this;
}
export function disconnect(callback ?: Function): void;
export function fork(env?: any): Worker;
export var isMaster: boolean;
export var isWorker: boolean;
export function setupMaster(settings?: ClusterSettings): void;
export function fork(env?: any): Worker;
export function disconnect(callback?: Function): void;
// TODO: cluster.schedulingPolicy
export var settings: ClusterSettings;
export function setupMaster(settings?: ClusterSetupMasterSettings): void;
export var worker: Worker;
export var workers: {
[index: string]: Worker
};
// Event emitter
export function addListener(event: string, listener: Function): void;
export function on(event: "disconnect", listener: (worker: Worker) => void): void;
export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void;
export function on(event: "fork", listener: (worker: Worker) => void): void;
export function on(event: "listening", listener: (worker: Worker, address: any) => void): void;
export function on(event: "message", listener: (worker: Worker, message: any) => void): void;
export function on(event: "online", listener: (worker: Worker) => void): void;
export function on(event: "setup", listener: (settings: any) => void): void;
export function on(event: string, listener: Function): any;
export function once(event: string, listener: Function): void;
export function removeListener(event: string, listener: Function): void;
export function removeAllListeners(event?: string): void;
export function setMaxListeners(n: number): void;
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
export function addListener(event: string, listener: Function): Cluster;
export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster;
export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
export function addListener(event: "online", listener: (worker: Worker) => void): Cluster;
export function addListener(event: "setup", listener: (settings: any) => void): Cluster;
export function on(event: string, listener: Function): Cluster;
export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster;
export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
export function on(event: "fork", listener: (worker: Worker) => void): Cluster;
export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
export function on(event: "online", listener: (worker: Worker) => void): Cluster;
export function on(event: "setup", listener: (settings: any) => void): Cluster;
export function once(event: string, listener: Function): Cluster;
export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster;
export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
export function once(event: "fork", listener: (worker: Worker) => void): Cluster;
export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
export function once(event: "online", listener: (worker: Worker) => void): Cluster;
export function once(event: "setup", listener: (settings: any) => void): Cluster;
export function removeListener(event: string, listener: Function): Cluster;
export function removeAllListeners(event?: string): Cluster;
export function setMaxListeners(n: number): Cluster;
export function getMaxListeners(): number;
export function listeners(event: string): Function[];
export function emit(event: string, ...args: any[]): boolean;
export function listenerCount(type: string): number;
export function prependListener(event: string, listener: Function): Cluster;
export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster;
export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster;
export function prependListener(event: "setup", listener: (settings: any) => void): Cluster;
export function prependOnceListener(event: string, listener: Function): Cluster;
export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster;
export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster;
export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster;
export function eventNames(): string[];
}
declare module "zlib" {
@@ -1019,8 +1203,6 @@ declare module "os" {
export function arch(): string;
export function platform(): string;
export function tmpdir(): string;
export function tmpDir(): string;
export function getNetworkInterfaces(): { [index: string]: NetworkInterfaceInfo[] };
export var EOL: string;
export function endianness(): "BE" | "LE";
}
@@ -1042,7 +1224,7 @@ declare module "https" {
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: any;
SNICallback?: (servername: string, cb:(err:Error,ctx:tls.SecureContext)=>any) => any;
SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any;
}
export interface RequestOptions extends http.RequestOptions {
@@ -1398,18 +1580,24 @@ declare module "url" {
}
declare module "dns" {
export interface MxRecord {
exchange: string,
priority: number
}
export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string;
export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string;
export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) =>void ): string[];
export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[];
export function setServers(servers: string[]): void;
//Error codes
export var NODATA: string;
@@ -1600,16 +1788,92 @@ declare module "fs" {
interface FSWatcher extends events.EventEmitter {
close(): void;
/**
* events.EventEmitter
* 1. change
* 2. error
*/
addListener(event: string, listener: Function): this;
addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
addListener(event: "error", listener: (code: number, signal: string) => void): this;
on(event: string, listener: Function): this;
on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
on(event: "error", listener: (code: number, signal: string) => void): this;
once(event: string, listener: Function): this;
once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
once(event: "error", listener: (code: number, signal: string) => void): this;
prependListener(event: string, listener: Function): this;
prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
prependListener(event: "error", listener: (code: number, signal: string) => void): this;
prependOnceListener(event: string, listener: Function): this;
prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this;
}
export interface ReadStream extends stream.Readable {
close(): void;
destroy(): void;
/**
* events.EventEmitter
* 1. open
* 2. close
*/
addListener(event: string, listener: Function): this;
addListener(event: "open", listener: (fd: number) => void): this;
addListener(event: "close", listener: () => void): this;
on(event: string, listener: Function): this;
on(event: "open", listener: (fd: number) => void): this;
on(event: "close", listener: () => void): this;
once(event: string, listener: Function): this;
once(event: "open", listener: (fd: number) => void): this;
once(event: "close", listener: () => void): this;
prependListener(event: string, listener: Function): this;
prependListener(event: "open", listener: (fd: number) => void): this;
prependListener(event: "close", listener: () => void): this;
prependOnceListener(event: string, listener: Function): this;
prependOnceListener(event: "open", listener: (fd: number) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
}
export interface WriteStream extends stream.Writable {
close(): void;
bytesWritten: number;
path: string | Buffer;
/**
* events.EventEmitter
* 1. open
* 2. close
*/
addListener(event: string, listener: Function): this;
addListener(event: "open", listener: (fd: number) => void): this;
addListener(event: "close", listener: () => void): this;
on(event: string, listener: Function): this;
on(event: "open", listener: (fd: number) => void): this;
on(event: "close", listener: () => void): this;
once(event: string, listener: Function): this;
once(event: "open", listener: (fd: number) => void): this;
once(event: "close", listener: () => void): this;
prependListener(event: string, listener: Function): this;
prependListener(event: "open", listener: (fd: number) => void): this;
prependListener(event: "close", listener: () => void): this;
prependOnceListener(event: string, listener: Function): this;
prependOnceListener(event: "open", listener: (fd: number) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
}
/**
@@ -1855,7 +2119,7 @@ declare module "fs" {
}
export const constants: Constants;
/** Tests a user's permissions for the file specified by path. */
export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void;
export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void;
@@ -2198,7 +2462,7 @@ declare module "tls" {
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: string[] | Buffer;
SNICallback?: (servername: string, cb:(err:Error,ctx:SecureContext)=>any) => any;
SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any;
ecdhCurve?: string;
dhparam?: string | Buffer;
handshakeTimeout?: number;
@@ -2214,7 +2478,7 @@ declare module "tls" {
port?: number;
socket?: net.Socket;
pfx?: string | Buffer
key?: string |string[] | Buffer | Buffer[];
key?: string | string[] | Buffer | Buffer[];
passphrase?: string;
cert?: string | string[] | Buffer | Buffer[];
ca?: string | Buffer | (string | Buffer)[];
@@ -2436,6 +2700,7 @@ declare module "crypto" {
setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void;
}
export function createECDH(curve_name: string): ECDH;
export var DEFAULT_ENCODING: string;
}
declare module "stream" {
@@ -2446,7 +2711,7 @@ declare module "stream" {
}
namespace internal {
export class Stream extends internal {}
export class Stream extends internal { }
export interface ReadableOptions {
highWaterMark?: number;
@@ -2468,14 +2733,73 @@ declare module "stream" {
unshift(chunk: any): void;
wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
push(chunk: any, encoding?: string): boolean;
/**
* Event emitter
* The defined events on documents including:
* 1. close
* 2. data
* 3. end
* 4. readable
* 5. error
**/
addListener(event: string, listener: Function): this;
addListener(event: string, listener: Function): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
addListener(event: "end", listener: () => void): this;
addListener(event: "readable", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
emit(event: string, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "data", chunk: Buffer | string): boolean;
emit(event: "end"): boolean;
emit(event: "readable"): boolean;
emit(event: "error", err: Error): boolean;
on(event: string, listener: Function): this;
on(event: "close", listener: () => void): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this;
on(event: "end", listener: () => void): this;
on(event: "readable", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
once(event: string, listener: Function): this;
once(event: "close", listener: () => void): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this;
once(event: "end", listener: () => void): this;
once(event: "readable", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
prependListener(event: string, listener: Function): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependListener(event: "end", listener: () => void): this;
prependListener(event: "readable", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: string, listener: Function): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "readable", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: string, listener: Function): this;
removeListener(event: "close", listener: () => void): this;
removeListener(event: "data", listener: (chunk: Buffer | string) => void): this;
removeListener(event: "end", listener: () => void): this;
removeListener(event: "readable", listener: () => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
}
export interface WritableOptions {
highWaterMark?: number;
decodeStrings?: boolean;
objectMode?: boolean;
write?: (chunk: string|Buffer, encoding: string, callback: Function) => any;
writev?: (chunks: {chunk: string|Buffer, encoding: string}[], callback: Function) => any;
write?: (chunk: string | Buffer, encoding: string, callback: Function) => any;
writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any;
}
export class Writable extends events.EventEmitter implements NodeJS.WritableStream {
@@ -2487,6 +2811,72 @@ declare module "stream" {
end(): void;
end(chunk: any, cb?: Function): void;
end(chunk: any, encoding?: string, cb?: Function): void;
/**
* Event emitter
* The defined events on documents including:
* 1. close
* 2. drain
* 3. error
* 4. finish
* 5. pipe
* 6. unpipe
**/
addListener(event: string, listener: Function): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "drain", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "finish", listener: () => void): this;
addListener(event: "pipe", listener: (src: Readable) => void): this;
addListener(event: "unpipe", listener: (src: Readable) => void): this;
emit(event: string, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "drain", chunk: Buffer | string): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "finish"): boolean;
emit(event: "pipe", src: Readable): boolean;
emit(event: "unpipe", src: Readable): boolean;
on(event: string, listener: Function): this;
on(event: "close", listener: () => void): this;
on(event: "drain", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "pipe", listener: (src: Readable) => void): this;
on(event: "unpipe", listener: (src: Readable) => void): this;
once(event: string, listener: Function): this;
once(event: "close", listener: () => void): this;
once(event: "drain", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "finish", listener: () => void): this;
once(event: "pipe", listener: (src: Readable) => void): this;
once(event: "unpipe", listener: (src: Readable) => void): this;
prependListener(event: string, listener: Function): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "drain", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "finish", listener: () => void): this;
prependListener(event: "pipe", listener: (src: Readable) => void): this;
prependListener(event: "unpipe", listener: (src: Readable) => void): this;
prependOnceListener(event: string, listener: Function): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "finish", listener: () => void): this;
prependOnceListener(event: "pipe", listener: (src: Readable) => void): this;
prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this;
removeListener(event: string, listener: Function): this;
removeListener(event: "close", listener: () => void): this;
removeListener(event: "drain", listener: () => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: "finish", listener: () => void): this;
removeListener(event: "pipe", listener: (src: Readable) => void): this;
removeListener(event: "unpipe", listener: (src: Readable) => void): this;
}
export interface DuplexOptions extends ReadableOptions, WritableOptions {
@@ -2512,7 +2902,7 @@ declare module "stream" {
}
export interface TransformOptions extends ReadableOptions, WritableOptions {
transform?: (chunk: string|Buffer, encoding: string, callback: Function) => any;
transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any;
flush?: (callback: Function) => any;
}
@@ -2598,7 +2988,7 @@ declare module "assert" {
});
}
export function fail(actual?: any, expected?: any, message?: string, operator?: string): void;
export function fail(actual: any, expected: any, message: string, operator: string): void;
export function ok(value: any, message?: string): void;
export function equal(actual: any, expected: any, message?: string): void;
export function notEqual(actual: any, expected: any, message?: string): void;
@@ -2950,7 +3340,7 @@ declare module "v8" {
space_available_size: number;
physical_space_size: number;
}
export function getHeapStatistics() : {total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number};
export function getHeapStatistics(): { total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number };
export function getHeapSpaceStatistics(): HeapSpaceInfo[];
export function setFlagsFromString(flags: string): void;
}
+2
View File
@@ -159,6 +159,8 @@ declare namespace nv {
interpolate(value: string): this;
rightAlignYAxis(): boolean;
rightAlignYAxis(value: boolean): this;
syncBrushing(): boolean;
syncBrushing(value: boolean): this;
}
interface Nvd3Axis extends d3.svg.Axis {
+3
View File
@@ -74,6 +74,9 @@ declare module 'mongoose' {
plugin: (schema: PassportLocalSchema, options?: PassportLocalOptions) => void,
options?: PassportLocalOptions
): this;
// overload for the default mongoose plugin function
plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this;
}
export function model<T extends Document>(
@@ -0,0 +1,6 @@
/// <reference path="point-in-polygon.d.ts" />
import inside from 'point-in-polygon';
const polygon = [ [ 1, 1 ], [ 1, 2 ], [ 2, 2 ], [ 2, 1 ] ];
const inPolygon: boolean = inside([ 1.5, 1.5 ], polygon);
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for point-in-polygon
// Project: https://github.com/substack/point-in-polygon
// Definitions by: kogai <https://github.com/kogai>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'point-in-polygon' {
export default function inside(point: number[], polygon: number[][]): boolean;
}
+5 -7
View File
@@ -1,10 +1,8 @@
/// <reference path="./polylabel.d.ts" />
/// <reference path="../node/node.d.ts" />
import polylabel = require('polylabel');
import * as polylabel from 'polylabel';
const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]
let p: number[]
p = polylabel(polygon)
p = polylabel(polygon, 1.0)
p = polylabel(polygon, 1.0, true)
p = polylabel(polygon, 1.0, false)
polylabel(polygon)
polylabel(polygon, 1.0)
polylabel(polygon, 1.0, true)
polylabel(polygon, 1.0, false)
+3 -2
View File
@@ -15,7 +15,7 @@
* - guarantees finding global optimum within the given precision
* - is many times faster (10-40x)
*/
declare module 'polylabel' {
declare module "polylabel" {
/**
* Polylabel returns the pole of inaccessibility coordinate in [x, y] format.
*
@@ -28,6 +28,7 @@ declare module 'polylabel' {
* @example
* var p = polylabel(polygon, 1.0);
*/
function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[];
function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[];
namespace polylabel {}
export = polylabel;
}
+50
View File
@@ -0,0 +1,50 @@
/// <reference path="proj4.d.ts"/>
import * as proj4 from 'proj4'
///////////////////////////////////////////
// Tests data initialisation
///////////////////////////////////////////
const name = 'WGS84'
const epsg = {
4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees',
4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees',
}
const point1 = [-71, 41]
const point2 = {x: 2, y: 5}
const mgrs = "24XWT783908"
///////////////////////////////////////////
// Tests Measurement
///////////////////////////////////////////
proj4(epsg['4269'], epsg['4326'], point1)
proj4(epsg['4269'], point1)
proj4(epsg['4269'], epsg['4326']).forward(point2)
proj4(epsg['4269'], epsg['4326']).inverse(point2)
///////////////////////////////////
// Named Projections
///////////////////////////////////
proj4.defs('WGS84', epsg['4326'])
proj4.defs([
['EPSG:4326', epsg['4326']],
['EPSG:4269', epsg['4269']]
])
proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326'))
///////////////////////////////////
// Utils
///////////////////////////////////
// WGS84
proj4.WGS84
// Proj
proj4.Proj('WGS84')
// toPoint
proj4.toPoint([1, 2])
proj4.toPoint([1, 2, 3])
proj4.toPoint([1, 2, 3, 4])
// Point
// WARNING: Deprecated in v3
proj4.Point([1, 2, 3, 4])
+116
View File
@@ -0,0 +1,116 @@
// Type definitions for proj4 2.3.15
// Project: https://github.com/proj4js/proj4js
// Definitions by: Denis Carriere <https://github.com/DenisCarriere>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "proj4" {
const TemplateCoordinates: Array<number> | InterfaceCoordinates;
interface InterfaceCoordinates {
x: number,
y: number,
z?: number,
m?: number
}
interface InterfaceDatum {
datum_type: number
a: number
b: number
es: number
ep2: number
}
interface Proj4Static {
forward(coordinates: typeof TemplateCoordinates): Array<number>
inverse(coordinates: typeof TemplateCoordinates): Array<number>
}
interface InterfaceProjection {
title: string
projName: string
ellps: string
datumCode: string
units: string
a: number
rf: number
ellipseName: string
b: number
a2: number
b2: number
es: number
e: number
ep2: number
k0: number
axis: string
datum: InterfaceDatum
init: typeof proj4.Proj,
forward(coordinates: typeof TemplateCoordinates): Array<number>
inverse(coordinates: typeof TemplateCoordinates): Array<number>
names: Array<string>
to_meter(value: number): any
from_greenwich(value: number): any
}
namespace proj4 {
/**
* @name defaultDatum
*/
export const defaultDatum: string;
/**
* @name Proj
*/
export function Proj(srsCode:any, callback?: any): InterfaceProjection;
/**
* @name WGS84
*/
export const WGS84: any;
/**
* Depecrated v3
* @name Point
*/
export function Point(x: number, y: number, z?: number): InterfaceCoordinates;
export function Point(coordinates: Array<number>): InterfaceCoordinates;
export function Point(coordinates: InterfaceCoordinates): InterfaceCoordinates;
export function Point(coordinates: string): InterfaceCoordinates;
/**
* @name toPoint
*/
export function toPoint(array: Array<number>): InterfaceCoordinates;
/**
* @name defs
*/
export function defs(name: string): any;
export function defs(name: string, projection: string): any;
export function defs(name: Array<Array<string>>): any;
/**
* @name transform
*/
export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: typeof TemplateCoordinates): any;
/**
* @name mgrs
*/
export function mgrs(coordinates: Array<number>, accuracy: number): string;
/**
* @name version
*/
export const version: string;
}
/**
* @name proj4
*/
function proj4(fromProjection: string): Proj4Static;
function proj4(fromProjection: string, toProjection: string): Proj4Static;
function proj4(fromProjection: string, coordinates: typeof TemplateCoordinates): Array<number>;
function proj4(fromProjection: string, toProjection: string, coordinates: typeof TemplateCoordinates): Array<number>;
export = proj4
}
-1
View File
@@ -108,4 +108,3 @@ declare module "protractor-helpers" {
function getFilteredConsoleErrors() : webdriver.promise.IThenable<string[]>; // TODO - discuss handling in IE
}
+103
View File
@@ -0,0 +1,103 @@
/// <reference path="pug.d.ts"/>
import * as pug from 'pug';
////////////////////////////////////////////////////////////
/// Options https://pugjs.org/api/reference.html#options ///
////////////////////////////////////////////////////////////
namespace options_tests {
let opts: pug.Options;
let str = 'string'
let bool = false;
let strArray = ['string'];
opts.filename = str;
opts.basedir = str;
opts.doctype = str;
opts.pretty = str;
opts.pretty = bool;
opts.filters = {};
opts.self = bool;
opts.debug = bool;
opts.compileDebug = bool;
opts.globals = strArray;
opts.cache = bool;
opts.inlineRuntimeFunctions = bool;
opts.name = str;
}
////////////////////////////////////////////////////////////
/// Methods https://pugjs.org/api/reference.html#methods ///
////////////////////////////////////////////////////////////
namespace methods_tests {
let source = `p #{ name } 's Pug source code!`;
let path = "foo.pug";
let compileTemplate: pug.compileTemplate;
let template: string;
let clientFunctionString: pug.ClientFunctionString;
let str: string;
{
/// pug.compile(source, ?options) https://pugjs.org/api/reference.html#pugcompilesource-options
compileTemplate = pug.compile(source);
template = compileTemplate();
}
{
/// pug.compileFile(path, ?options) https://pugjs.org/api/reference.html#pugcompilefilepath-options
compileTemplate = pug.compileFile(path);
template = compileTemplate();
}
{
/// pug.compileClient(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientsource-options
clientFunctionString = pug.compileClient(path);
str = pug.compileClient(path);
}
{
/// pug.compileClientWithDependenciesTracked(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientwithdependenciestrackedsource-options
let obj = pug.compileClientWithDependenciesTracked(source);
clientFunctionString = obj.body;
str = obj.body;
let strArray: string[] = obj.dependencies;
}
{
/// pug.compileFileClient(path, ?options) https://pugjs.org/api/reference.html#pugcompilefileclientpath-options
clientFunctionString = pug.compileFileClient(path);
str = pug.compileFileClient(path);
}
{
/// pug.render(source, ?options, ?callback) https://pugjs.org/api/reference.html#pugrendersource-options-callback
str = pug.render(source);
// test type for callback paraments
pug.render(source, {}, (err, html) => {
let e: Error = err;
str = html;
});
}
{
/// pug.renderFile(path, ?options, ?callback) https://pugjs.org/api/reference.html#pugrenderfilepath-options-callback
str = pug.renderFile(path);
// test type for callback paraments
pug.renderFile(path, {}, (err, html) => {
let e: Error = err;
str = html;
});
}
}
+50
View File
@@ -0,0 +1,50 @@
// Type definitions for pug 2.0.0-beta6
// Project: https://github.com/pugjs/pug
// Definitions by: TonyYang <https://github.com/TonyPythoneer>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Table of Contents
*
* - Options https://pugjs.org/api/reference.html#options
* - Methods https://pugjs.org/api/reference.html#methods
*
* The order of contents is according to pugjs API document.
*/
declare module 'pug' {
////////////////////////////////////////////////////////////
/// Options https://pugjs.org/api/reference.html#options ///
////////////////////////////////////////////////////////////
export interface Options {
filename?: string;
basedir?: string;
doctype?: string;
pretty?: boolean | string;
filters?: any;
self?: boolean;
debug?: boolean;
compileDebug?: boolean;
globals?: string[];
cache?: boolean;
inlineRuntimeFunctions?: boolean;
name?: string;
}
////////////////////////////////////////////////////////////
/// Methods https://pugjs.org/api/reference.html#methods ///
////////////////////////////////////////////////////////////
export function compile(source: string, options?: Options): (locals?: any) => string;
export function compileFile(path: string, options?: Options): (locals?: any) => string;
export function compileClient(source: string, options?: Options): ClientFunctionString;
export function compileClientWithDependenciesTracked(source: string, options?: Options): {
body: ClientFunctionString;
dependencies: string[];
};
export function compileFileClient(path: string, options?: Options): ClientFunctionString;
export function render(source: string, options?: Options, callback?: (err: Error, html: string) => void): string;
export function renderFile(path: string, options?: Options, callback?: (err: Error, html: string) => void): string;
// else
export type ClientFunctionString = string; // ex: 'function (locals) {...}'
export type compileTemplate = (locals?: any) => string;
}
+3 -3
View File
@@ -39,10 +39,10 @@ declare namespace ReactRouter {
type RouteComponent = Component
// use the following interface in an app code to get access to route param values, history, location...
// interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: number }> {}
// interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: string }> {}
// somewhere in MyComponent
// ...
// let id = this.props.routeParams.id
// let id = parseInt(this.props.routeParams.id, 10);
// ...
// this.props.history. ...
// ...
@@ -247,7 +247,7 @@ declare namespace ReactRouter {
isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean
}
function withRouter<C extends React.ComponentClass<any>>(component: C): C
function withRouter<C extends React.ComponentClass<any> | React.StatelessComponent<any> | React.PureComponent<any, any>>(component: C): C
/* utils */
@@ -0,0 +1,309 @@
/// <reference path="react-virtualized.d.ts"/>
/// <reference path="../react/react.d.ts"/>
/// <reference path="../react/react-dom.d.ts"/>
import * as React from "react";
import * as ReactDOM from "react-dom";
import {
Collection,
FlexTable,
FlexColumn,
SortDirection,
Grid,
VirtualScroll,
ArrowKeyStepper,
AutoSizer,
CellMeasurer,
ColumnSizer,
InfiniteLoader,
ScrollSync,
WindowScroller,
} from "react-virtualized";
/*
* Collection
*/
function CollectionTest() {
const list = [
{ name: "Brian Vaughn", x: 13, y: 34, width: 123, size: 234, height: 123 }
];
// Render your grid
ReactDOM.render(
<Collection
cellCount={list.length}
cellRenderer={({ index }) => list[index].name}
cellSizeAndPositionGetter={({ index }) => {
const datum = list[index];
return {
height: datum.height,
width: datum.width,
x: datum.x,
y: datum.y
};
} }
height={300}
width={300}
/>,
document.getElementById("example")
);
}
function FlexTableTest() {
const list = [
{ name: 'Brian Vaughn', description: 'Software engineer' }
// And so on...
];
// Render your table
ReactDOM.render(
<FlexTable
width={300}
height={300}
headerHeight={20}
rowHeight={30}
rowCount={list.length}
rowGetter={
({ index }) => list[index]
}
>
<FlexColumn
label="Name"
dataKey="name"
width={100}
/>
<FlexColumn
width={200}
label="Description"
dataKey="description"
/>
</FlexTable>,
document.getElementById("example")
);
}
function GridTest() {
// Grid data as an array of arrays
const list = [
['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */]
// And so on...
];
// Render your grid
ReactDOM.render(
<Grid
width={300}
height={300}
columnWidth={100}
rowHeight={30}
columnCount={list[0].length}
rowCount={list.length}
cellRenderer={({ columnIndex, isScrolling, rowIndex }) => list[rowIndex][columnIndex]}
/>,
document.getElementById('example')
);
}
function VirtualScrollTest() {
// List data as an array of strings
const list = [
'Brian Vaughn'
// And so on...
];
// Render your list
ReactDOM.render(
<VirtualScroll
width={300}
height={300}
rowCount={list.length}
rowHeight={20}
rowRenderer={({ index, isScrolling }) => list[index]}
/>,
document.getElementById('example')
);
}
function ArrowKeyStepperTest() {
const columnCount = 12;
const rowCount = 3;
ReactDOM.render(
<ArrowKeyStepper columnCount={columnCount} rowCount={rowCount}>
{({ onSectionRendered, scrollToColumn, scrollToRow }) => (
<Grid
columnCount={columnCount}
onSectionRendered={onSectionRendered}
rowCount={rowCount}
scrollToColumn={scrollToColumn}
scrollToRow={scrollToRow}
/>
) }
</ArrowKeyStepper>,
document.getElementById('example')
);
}
function AutoSizerTest() {
// List data as an array of strings
const list = [
'Brian Vaughn'
// And so on...
];
// Render your list
ReactDOM.render(
<AutoSizer>
{({ height, width }) => (
<VirtualScroll
width={width}
height={height}
rowCount={list.length}
rowHeight={20}
rowRenderer={
({ index }) => list[index] // Could also be a DOM element
}
/>
) }
</AutoSizer>,
document.getElementById('example')
);
}
function CellMeasurerTest() {
const columnCount = 12;
const rowCount = 3;
const cellRenderer = ({ columnIndex, rowIndex }) => `${rowIndex}, ${columnIndex}`;
const fixedRowHeight = 42;
const height = 12;
const width = 12;
ReactDOM.render(
<CellMeasurer
cellRenderer={cellRenderer}
columnCount={columnCount}
height={fixedRowHeight}
rowCount={rowCount}
>
{({ getColumnWidth }) => (
<Grid
columnCount={columnCount}
columnWidth={getColumnWidth}
height={height}
cellRenderer={cellRenderer}
rowCount={rowCount}
rowHeight={fixedRowHeight}
width={width}
/>
) }
</CellMeasurer>,
document.getElementById('example')
);
}
function ColumnSizerTest() {
ReactDOM.render(
<ColumnSizer
columnMaxWidth={100}
columnMinWidth={50}
columnCount={12}
width={120}
>
{({ adjustedWidth, getColumnWidth, registerChild }) => (
<Grid
ref={registerChild}
columnWidth={getColumnWidth}
columnCount={12}
height={12}
cellRenderer={() => "test"}
rowHeight={50}
rowCount={12}
width={adjustedWidth}
/>
) }
</ColumnSizer>,
document.getElementById('example')
);
}
function InfiniteLoaderTest() {
const list: string[] = [];
function isRowLoaded({ index }) {
return !!list[index];
}
function loadMoreRows({ startIndex, stopIndex }) {
return list.push('test');
}
// Render your list
ReactDOM.render(
<InfiniteLoader
isRowLoaded={isRowLoaded}
loadMoreRows={loadMoreRows}
rowCount={12}
>
{({ onRowsRendered, registerChild }) => (
<VirtualScroll
ref={registerChild}
width={300}
height={200}
onRowsRendered={onRowsRendered}
rowCount={list.length}
rowHeight={20}
rowRenderer={
({ index }) => list[index] // Could also be a DOM element
}
/>
) }
</InfiniteLoader>,
document.getElementById('example')
);
}
function ScrollSyncTest() {
return (
<ScrollSync>
{({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => (
<div className='Table'>
<div className='LeftColumn'>
<VirtualScroll
rowRenderer={() => "test"}
rowCount={42}
height={12}
width={12}
rowHeight={120}
scrollTop={scrollTop}/>
/>
</div>
<div className='RightColumn'>
<Grid
onScroll={onScroll}/>
</div>
</div>
) }
</ScrollSync>
);
}
function WindowScrollerTest() {
ReactDOM.render(
<WindowScroller>
{({ height, isScrolling, scrollTop }) => (
<VirtualScroll
autoHeight
height={height}
rowCount={12}
rowHeight={12}
rowRenderer={() => 'test'}
scrollTop={scrollTop}
width={120}/>
) }
</WindowScroller>,
document.getElementById('example')
);
}
+123
View File
@@ -0,0 +1,123 @@
// Type definitions for react-virtualized
// Project: https://github.com/bvaughn/react-virtualized
// Definitions by: Ian Ker-Seymer <https://github.com/ianks>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="./../react/react.d.ts" />
declare module "react-virtualized" {
import * as React from "react";
/*
* Components
*/
interface VirtualScrollProps {
className?: string;
autoHeight?: boolean;
estimatedRowSize?: number;
height: number;
noRowsRenderer?: Function;
onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void;
onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void;
overscanRowCount?: number;
rowHeight: number | ((info: { index: number }) => number);
rowRenderer: (info: { index: number, isScrolling: boolean }) => React.ReactNode;
rowClassName?: string | ((info: { index: number }) => string);
rowCount: number;
rowStyle?: React.CSSProperties | ((info: { index: number }) => React.CSSProperties);
scrollToAlignment?: string;
scrollToIndex?: number;
scrollTop?: number;
style?: React.CSSProperties;
tabIndex?: number;
width: number;
}
export class VirtualScroll extends React.Component<VirtualScrollProps, {}> { }
type CollectionProps = any;
export class Collection extends React.Component<CollectionProps, {}> { }
type FlexTableProps = any;
export class FlexTable extends React.Component<FlexTableProps, {}> { }
type FlexColumnProps = any;
export class FlexColumn extends React.Component<FlexColumnProps, {}> { }
type SortDirectionProps = any;
export class SortDirection extends React.Component<SortDirectionProps, {}> { }
type GridProps = any;
export class Grid extends React.Component<GridProps, {}> { }
/*
* Higher-Order Components
*/
interface AutoSizerProps {
disableHeight?: boolean;
disableWidth?: boolean;
onResize?: (info: { height: number, width: number }) => any;
}
export class AutoSizer extends React.Component<AutoSizerProps, {}> { }
interface ArrowKeyStepperProps {
children?: React.StatelessComponent<{
onSectionRendered: Function,
scrollToColumn: number,
scrollToRow: number
}>;
className?: string;
columnCount: number;
rowCount: number;
}
export class ArrowKeyStepper extends React.Component<ArrowKeyStepperProps, {}> { }
interface CellMeasurerProps {
cellRenderer: (info: { columnIndex: number, rowIndex: number }) => React.ReactNode;
cellSizeCache?: {
clearAllColumnWidths(): void;
clearAllRowHeights(): void;
clearColumnWidth(index: number): void;
clearRowHeight(index: number): void;
getColumnWidth(index: number): number;
getRowHeight(index: number): number;
hasColumnWidth(index: number): boolean;
hasRowHeight(index: number): boolean;
setColumnWidth(index: number, width: number): void;
setRowHeight(index: number, height: number): void;
};
children?: React.StatelessComponent<{
getColumnWidth: () => number,
getRowHeight: () => number,
resetMeasurements: () => any,
resetMeasurementsForColumn: (index: number) => any,
resetMeasurementsForRow: (index: number) => any,
}>;
columnCount: number;
container?: React.ReactType;
height?: number;
rowCount: number;
width?: number;
}
export class CellMeasurer extends React.Component<CellMeasurerProps, {}> { }
interface ColumnSizerProps {
children?: React.StatelessComponent<{ adjustedWidth: number, getColumnWidth: () => number, registerChild: any }>;
columnMaxWidth?: number;
columnMinWidth?: number;
columnCount?: number;
width: number;
}
export class ColumnSizer extends React.Component<ColumnSizerProps, {}> { }
type InfiniteLoaderProps = any;
export class InfiniteLoader extends React.Component<InfiniteLoaderProps, {}> { }
type ScrollSyncProps = any;
export class ScrollSync extends React.Component<ScrollSyncProps, {}> { }
type WindowScrollerProps = any;
export class WindowScroller extends React.Component<WindowScrollerProps, {}> { }
}
+1 -1
View File
@@ -4,7 +4,7 @@
import {createAction} from 'redux-actions';
import { createStore, applyMiddleware, PromiseAction } from 'redux';
import promise from 'redux-promise';
import promise = require('redux-promise');
declare var userReducer: any;
+2 -2
View File
@@ -19,5 +19,5 @@ declare namespace ReduxPromise {
declare module "redux-promise" {
var promise: ReduxPromise.Promise;
export default promise;
}
export = promise;
}
+1 -1
View File
@@ -206,7 +206,7 @@ interface RequireConfig {
* }
* });
**/
urlArgs?: string | { (id: string, url: string): string; };
urlArgs?: string | ((id: string, url: string) => string);
/**
* Specify the value for the type="" attribute used for script
+2 -4
View File
@@ -84,8 +84,8 @@ declare namespace restangular {
one(route: string, id?: number): IElement;
one(route: string, id?: string): IElement;
oneUrl(route: string, url: string): IElement;
all(route: string): IElement;
allUrl(route: string, url: string): IElement;
all(route: string): ICollection;
allUrl(route: string, url: string): ICollection;
copy(fromElement: any): IElement;
withConfig(configurer: (RestangularProvider: IProvider) => any): IService;
restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement;
@@ -104,8 +104,6 @@ declare namespace restangular {
put(queryParams?: any, headers?: any): IPromise<any>;
post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): IPromise<any>;
post<T>(subElement: any, elementToPost: T, queryParams?: any, headers?: any): IPromise<T>;
post(elementToPost: any, queryParams?: any, headers?: any): IPromise<any>;
post<T>(elementToPost: T, queryParams?: any, headers?: any): IPromise<T>;
remove(queryParams?: any, headers?: any): IPromise<any>;
head(queryParams?: any, headers?: any): IPromise<any>;
trace(queryParams?: any, headers?: any): IPromise<any>;
+1
View File
@@ -452,6 +452,7 @@ declare module "restify" {
responseTimeFormatter ?: (durationInMilliseconds: number) => any;
handleUpgrades ?: boolean;
router ?: Router;
httpsServerOptions?: any;
}
interface ClientOptions {
+105
View File
@@ -0,0 +1,105 @@
/// <reference path="rpio.d.ts"/>
rpio.init({gpiomem: false}); /* Use /dev/mem for i²c/PWM/SPI */
rpio.init({mapping: 'gpio'}); /* Use the GPIOxx numbering */
/* Configure P11 as input with the internal pulldown resistor enabled */
rpio.open(11, rpio.INPUT, rpio.PULL_DOWN);
/* Configure P12 as output with the initiate state set high */
rpio.open(12, rpio.OUTPUT, rpio.HIGH);
/* Configure P13 as output, but leave it in its initial undefined state */
rpio.open(13, rpio.OUTPUT);
rpio.mode(12, rpio.INPUT); /* Switch P12 back to input mode */
console.log('Pin 12 = %d', rpio.read(12));
var buf = new Buffer(10000);
/* Read the value of Pin 12 10,000 times in a row, storing the values in buf */
rpio.readbuf(12, buf);
rpio.write(13, rpio.HIGH);
/* Write 1 0 1 0 1 0 1 0 to Pin 13 */
var buf = new Buffer(8).fill(rpio.LOW);
buf[0] = buf[2] = buf[4] = buf[6] = rpio.HIGH;
rpio.writebuf(13, buf);
var curpad = rpio.readpad(rpio.PAD_GROUP_0_27);
var slew = ((curpad & rpio.PAD_SLEW_UNLIMITED) == rpio.PAD_SLEW_UNLIMITED);
var hysteresis = ((curpad & rpio.PAD_HYSTERESIS) == rpio.PAD_HYSTERESIS);
var drive = (curpad & 0x7);
/* Disable input hysteresis but retain other current settings. */
var control = rpio.readpad(rpio.PAD_GROUP_0_27);
control &= ~rpio.PAD_HYSTERESIS;
rpio.writepad(rpio.PAD_GROUP_0_27, control);
rpio.pud(11, rpio.PULL_UP);
rpio.pud(12, rpio.PULL_DOWN);
function nuke_button(pin: number)
{
console.log('Nuke button on pin %d pressed', pin);
/* No need to nuke more than once. */
rpio.poll(pin, null);
}
function regular_button(pin: number)
{
/* Watch pin 11 forever. */
console.log('Button event on pin %d, is now %d', pin, rpio.read(pin));
}
/*
* Pin 11 watches for both high and low transitions. Pin 12 only watches for
* high transitions (e.g. the nuke button is pushed).
*/
rpio.poll(11, regular_button);
rpio.poll(12, nuke_button, rpio.POLL_HIGH);
rpio.close(11);
rpio.i2cBegin();
rpio.i2cSetSlaveAddress(0x20);
rpio.i2cSetBaudRate(100000); /* 100kHz */
rpio.i2cSetClockDivider(2500); /* 250MHz / 2500 = 100kHz */
var txbuf = new Buffer([0x0b, 0x0e, 0x0e, 0x0f]);
var rxbuf = new Buffer(32);
rpio.i2cWrite(txbuf); /* Sends 4 bytes */
rpio.i2cRead(rxbuf, 16); /* Reads 16 bytes */
rpio.i2cEnd();
rpio.open(12, rpio.PWM); /* Use pin 12 */
rpio.pwmSetClockDivider(64); /* Set PWM refresh rate to 300kHz */
rpio.pwmSetRange(12, 1024);
rpio.pwmSetData(12, 512);
rpio.spiBegin(); /* Switch GPIO7-GPIO11 to SPI mode */
rpio.spiSetCSPolarity(0, rpio.HIGH); /* Set CE0 high to activate */
rpio.spiSetClockDivider(128); /* Set SPI speed to 1.95MHz */
rpio.spiTransfer(txbuf, rxbuf, txbuf.length);
rpio.spiWrite(txbuf, txbuf.length);
rpio.spiEnd();
rpio.sleep(1); /* Sleep for n seconds */
rpio.msleep(1); /* Sleep for n milliseconds */
rpio.usleep(1); /* Sleep for n microseconds */
+372
View File
@@ -0,0 +1,372 @@
// Type definitions for node-rpio
// Project: https://github.com/jperkin/node-rpio
// Definitions by: Dominik Palo <https://github.com/DominikPalo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare var rpio: Rpio;
declare module 'rpio' {
export = rpio;
}
interface Rpio {
/**
* Initialise the bcm2835 library. This will be called automatically by .open() using the default option values if not called explicitly.
* @param options
*/
init(options: RPIO.Options): void;
/**
* Open a pin for input or output. Valid modes are:
* INPUT: pin is input (read-only).
* OUTPUT: pin is output (read-write).
* PWM: configure pin for hardware PWM.
*
* For input pins, option can be used to configure the internal pullup or pulldown resistors using options as described in the .pud() documentation below.
*
* For output pins, option defines the initial isMotionDetected of the pin, rather than having to issue a separate .write() call. This can be critical for devices which must have a stable value, rather than relying on the initial floating value when a pin is enabled for output but hasn't yet been configured with a value.
* @param pin
* @param mode
* @param options
*/
open(pin: number, mode: number, options?: number): void;
/**
* Switch a pin that has already been opened in one mode to a different mode.
* This is provided primarily for performance reasons, as it avoids some of the setup work done by .open().
* @param pin
* @param mode
*/
mode(pin: number, mode: number): void;
/**
* Read the current value of pin, returning either 1 (high) or 0 (low).
* @param pin
*/
read(pin: number): number;
/**
* Read length bits from pin into buffer as fast as possible. If length isn't specified it defaults to buffer.length.
* @param pin
* @param buffer
* @param length
*/
readbuf(pin: number, buffer: Buffer, length?: number): void;
/**
* Set the specified pin either high or low, using either the HIGH/LOW constants, or simply 1 or 0.
* @param pin
* @param value
*/
write(pin: number, value: number): void;
/**
* Write length bits to pin from buffer as fast as possible. If length isn't specified it defaults to buffer.length.
* @param pin
* @param buffer
* @param length
*/
writebuf(pin: number, buffer: Buffer, length?: number): void;
/**
* Read the current isMotionDetected of the GPIO pad control for the specified GPIO group. On current models of Raspberry Pi there are three groups with corresponding defines:
* PAD_GROUP_0_27: GPIO0 - GPIO27. Use this for the main GPIO header.
* PAD_GROUP_28_45: GPIO28 - GPIO45. Use this to configure the P5 header.
* PAD_GROUP_46_53: GPIO46 - GPIO53. Internal, you probably won't need this.
*
* The value returned will be a bit mask of the following defines:
* PAD_SLEW_UNLIMITED: 0x10. Slew rate unlimited if set.
* PAD_HYSTERESIS: 0x08. Hysteresis is enabled if set.
*
* The bottom three bits determine the drive current:
* PAD_DRIVE_2mA: 0b000
* PAD_DRIVE_4mA: 0b001
* PAD_DRIVE_6mA: 0b010
* PAD_DRIVE_8mA: 0b011
* PAD_DRIVE_10mA: 0b100
* PAD_DRIVE_12mA: 0b101
* PAD_DRIVE_14mA: 0b110
* PAD_DRIVE_16mA: 0b111
*
* @note Note that the pad control registers are not available via /dev/gpiomem, so you will need to use .init({gpiomem: false}) and run as root.
* @param group
*/
readpad(group: number): number;
/**
* Write control settings to the pad control for group. Uses the same defines as above for .readpad().
* @param group
* @param control
*/
writepad(group: number, control: number): void;
/**
* Configure the pin's internal pullup or pulldown resistors, using the following isMotionDetected constants:
* PULL_OFF: disable configured resistors.
* PULL_DOWN: enable the pulldown resistor.
* PULL_UP: enable the pullup resistor.
*
* @param pin
* @param state
*/
pud(pin: number, state: number): void;
/**
* Watch pin for changes and execute the callback cb() on events. cb() takes a single argument, the pin which triggered the callback.
*
* The optional direction argument can be used to watch for specific events:
* POLL_LOW: poll for falling edge transitions to low.
* POLL_HIGH: poll for rising edge transitions to high.
* POLL_BOTH: poll for both transitions (the default).
*
* Due to hardware/kernel limitations we can only poll for changes, and the event detection only says that an event occurred, not which one. The poll interval is a 1ms setInterval() and transitions could come in between detecting the event and reading the value. Therefore this interface is only useful for events which transition slower than approximately 1kHz.
*
* To stop watching for pin changes, call .poll() again, setting the callback to null.
* @param pin
* @param cb
* @param direction
*/
poll(pin: number, cb: RPIO.CallbackFunction, direction?: number): void;
/**
* Reset pin to INPUT and clear any pullup/pulldown resistors and poll events.
* @param pin
*/
close(pin: number): void;
// I²C
/**
* Assign pins 3 and 5 to i²c use. Until .i2cEnd() is called they won't be available for GPIO use.
*
* The pin assignments are:
* Pin 3: SDA (Serial Data)
* Pin 5: SCL (Serial Clock)
*/
i2cBegin(): void;
/**
* Configure the slave address. This is between 0 - 0x7f, and it can be helpful to
* run the i2cdetect program to figure out where your devices are if you are unsure.
* @param address
*/
i2cSetSlaveAddress(address: number): void;
/**
* Set the baud rate - directly set the speed in hertz.
* @param baudRate
*/
i2cSetBaudRate(baudRate: number): void;
/**
* Read from the i²c slave.
* Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified.
* @param buffer
* @param length
*/
i2cRead(buffer: Buffer, length?: number): void;
/**
* Write to the i²c slave.
* Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified.
* @param biffer
* @param length
*/
i2cWrite(biffer: Buffer, length?: number): void;
/**
* Set the baud rate - based on a divisor of the base 250MHz rate.
* @param clockDivider
*/
i2cSetClockDivider(clockDivider: number): void;
/**
* Turn off the i²c interface and return the pins to GPIO.
*/
i2cEnd(): void;
// PWM
/**
* Set the PWM refresh rate.
* @param clockDivider: power-of-two divisor of the base 19.2MHz rate, with a maximum value of 4096 (4.6875kHz).
*/
pwmSetClockDivider(clockDivider: number): void;
/**
* Set the PWM range for a pin. This determines the maximum pulse width.
* @param pin
* @param range
*/
pwmSetRange(pin: number, range: number): void;
/**
* Set the PWM width for a pin.
* @param pin
* @param data
*/
pwmSetData(pin: number, data: number): void;
// SPI
/**
* Switch pins 119, 21, 23, 24 and 25 (GPIO7-GPIO11) to SPI mode
*
* Pin | Function
* -----|----------
* 19 | MOSI
* 21 | MISO
* 23 | SCLK
* 24 | CE0
* 25 | CE1
*/
spiBegin(): void;
/**
* Choose which of the chip select / chip enable pins to control.
*
* Value | Pin
* ------|---------------------
* 0 | SPI_CE0 (24 / GPIO8)
* 1 | SPI_CE1 (25 / GPIO7)
* 2 | Both
*
* @param chip
*/
spiChipSelect(cePin: number): void;
/**
* Commonly chip enable (CE) pins are active low, and this is the default.
* If your device's CE pin is active high, use spiSetCSPolarity() to change the polarity.
* @param cePin
* @param polarity
*/
spiSetCSPolarity(cePin: number, polarity: number): void;
/**
* Set the SPI clock speed with.
* @param clockDivider: an even divisor of the base 250MHz rate ranging between 0 and 65536.
*/
spiSetClockDivider(clockDivider: number): void;
/**
* Transfer data. Data is sent and received in 8-bit chunks via buffers which should be the same size.
* @param txBuffer
* @param rxBuffer
* @param txLength
*/
spiTransfer(txBuffer: Buffer, rxBuffer: Buffer, txLength: number): void;
/**
* Send data and do not care about the data coming back.
* @param txBuffer
* @param txLength
*/
spiWrite(txBuffer: Buffer, txLength: number): void;
/**
* Release the pins back to general purpose use.
*/
spiEnd(): void;
// Misc
/**
* Sleep for n seconds.
* @param n: number of seconds to sleep
*/
sleep(n: number): void;
/**
* Sleep for n milliseconds.
* @param n: number of milliseconds to sleep
*/
msleep(n: number): void;
/**
* Sleep for n microseconds.
* @param n: number of microseconds to sleep
*/
usleep(n: number): void;
// Constants:
HIGH: number;
LOW: number;
INPUT: number;
OUTPUT: number;
PWM: number;
PULL_OFF: number;
PULL_DOWN: number;
PULL_UP: number;
PAD_GROUP_0_27: number;
PAD_GROUP_28_45: number;
PAD_GROUP_46_53: number;
PAD_SLEW_UNLIMITED: number;
PAD_HYSTERESIS: number;
PAD_DRIVE_2mA: number;
PAD_DRIVE_4mA: number;
PAD_DRIVE_6mA: number;
PAD_DRIVE_8mA: number;
PAD_DRIVE_10mA: number;
PAD_DRIVE_12mA: number;
PAD_DRIVE_14mA: number;
PAD_DRIVE_16mA: number;
POLL_LOW: number;
POLL_HIGH: number;
POLL_BOTH: number;
}
declare namespace RPIO {
interface Options {
/**
* There are two device nodes for GPIO access. The default is /dev/gpiomem which, when configured with gpio group access, allows users in that group to read/write directly to that device. This removes the need to run as root, but is limited to GPIO functions.
* For non-GPIO functions (i²c, PWM, SPI) the /dev/mem device is required for full access to the Broadcom peripheral address range and the program needs to be executed as the root user (e.g. via sudo). If you do not explicitly call .init() when using those functions, the library will do it for you with gpiomem: false.
* You may also need to use gpiomem: false if you are running on an older Linux kernel which does not support the gpiomem module.
* rpio will throw an exception if you try to use one of the non-GPIO functions after already opening with /dev/gpiomem, as well as checking to see if you have the necessary permissions.
*
* Valid options:
* true: use /dev/gpiomem for non-root but GPIO-only access
* false: use /dev/mem for full access but requires root
*/
gpiomem?: boolean;
/**
* There are two naming schemes when referring to GPIO pins:
* By their physical header location: Pins 1 to 26 (A/B) or Pins 1 to 40 (A+/B+)
* Using the Broadcom hardware map: GPIO 0-25 (B rev1), GPIO 2-27 (A/B rev2, A+/B+)
*
* Confusingly however, the Broadcom GPIO map changes between revisions, so for example P3 maps to GPIO0 on Model B Revision 1 models, but maps to GPIO2 on all later models.
* This means the only sane default mapping is the physical layout, so that the same code will work on all models regardless of the underlying GPIO mapping.
* If you prefer to use the Broadcom GPIO scheme for whatever reason (e.g. to use the P5 header pins on the Raspberry Pi 1 revision 2.0 model which aren't currently mapped to the physical layout), you can set mapping to gpio to switch to the GPIOxx naming.
*
* Valid options:
* gpio: use the Broadcom GPIOxx naming
* physical: use the physical P01-P40 header layou
*/
mapping?: "gpio" | "physical";
}
interface CallbackFunction {
/**
* @param pin: The pin which triggered the callback.
*/
(pin: number): void;
}
}
+890 -576
View File
File diff suppressed because it is too large Load Diff
+74
View File
@@ -0,0 +1,74 @@
/// <reference path="scrollreveal.d.ts" />
//Tests from https://github.com/jlmakes/scrollreveal.js
//1.2
var sr = ScrollReveal();
sr.reveal('.foo');
sr.reveal('.bar');
//1.3
sr = ScrollReveal().reveal('.foo, .bar');
//2.1
sr = ScrollReveal({ reset: true });
sr.reveal('.foo', { duration: 200 });
//3.1
sr = ScrollReveal({ duration: 2000 });
sr.reveal('.box', 50);
sr = ScrollReveal();
sr.reveal('.box', { duration: 2000 }, 50);
//3.2
var fooReveal = {
delay : 200,
distance : '90px',
easing : 'ease-in-out',
rotate : { z: 10 },
scale : 1.1
};
sr = ScrollReveal();
sr.reveal('.foo', fooReveal);
sr.reveal('#chocolate', { delay: 500, scale: 0.9 });
//3.3
sr.reveal(document.getElementById('foo'));
sr.reveal(document.querySelectorAll('.bar'));
//3.4
sr = ScrollReveal();
var fooContainer = document.getElementById('fooContainer');
sr.reveal('.foo', { container: fooContainer });
sr.reveal('.bar', { container: '#barContainer' });
//3.5
fooContainer = document.getElementById('fooContainer');
sr = ScrollReveal();
sr.reveal('.foo', { container: fooContainer });
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
// Turn our response into HTML...
var content = document.createElement('div');
content.innerHTML = xmlhttp.responseText;
// Add each element to the DOM...
for (var i = 0; i < content.childNodes.length; i++) {
fooContainer.appendChild(content.childNodes[ i ]);
};
// Finally!
sr.sync();
}
}
}
xmlhttp.open('GET', 'ajax.html', true);
xmlhttp.send();
+68
View File
@@ -0,0 +1,68 @@
// Type definitions for ScrollReveal
// Project: https://github.com/jlmakes/scrollreveal.js
// Definitions by: David Pires <https://github.com/Davidblkx>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace scrollReveal {
interface ScrollRevealRotateObject {
x?: number;
y?: number;
z?: number;
}
interface ScrollRevealPositionObject {
top?: number;
right?: number;
bottom?: number;
left?: number;
}
interface ScrollRevealObjectOptions {
origin ? : string;
distance ? : string;
duration ? : number;
delay ? : number;
rotate ? : ScrollRevealRotateObject;
opacity ? : number;
scale ? : number;
easing ? : string;
container ? : any;
mobile ? : boolean;
reset ? : boolean;
useDelay ? : string;
viewFactor ? : number;
viewOffset ? : ScrollRevealPositionObject;
beforeReveal ? (domEl: HTMLElement): void;
afterReveal ? (domEl: HTMLElement): void;
beforeReset ? (domEl: HTMLElement): void;
afterReset ? (domEl: HTMLElement): void;
beforeReveal ? (domEl: NodeListOf<Element>): void;
afterReveal ? (domEl: NodeListOf<Element>): void;
beforeReset ? (domEl: NodeListOf<Element>): void;
afterReset ? (domEl: NodeListOf<Element>): void;
}
interface ScrollRevealObject {
(): ScrollRevealObject;
(options: ScrollRevealObjectOptions): ScrollRevealObject;
reveal(selector: string): ScrollRevealObject;
reveal(selector: string, interval: number): ScrollRevealObject;
reveal(selector: string, options: ScrollRevealObjectOptions): ScrollRevealObject;
reveal(selector: string, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject;
reveal(selector: HTMLElement): ScrollRevealObject;
reveal(selector: HTMLElement, interval: number): ScrollRevealObject;
reveal(selector: HTMLElement, options: ScrollRevealObjectOptions): ScrollRevealObject;
reveal(selector: HTMLElement, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject;
reveal(selector: NodeListOf<Element>): ScrollRevealObject;
reveal(selector: NodeListOf<Element>, interval: number): ScrollRevealObject;
reveal(selector: NodeListOf<Element>, options: ScrollRevealObjectOptions): ScrollRevealObject;
reveal(selector: NodeListOf<Element>, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject;
sync(): void;
}
}
declare var ScrollReveal: scrollReveal.ScrollRevealObject;

Some files were not shown because too many files have changed in this diff Show More