Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Terry Mun
2018-09-17 11:01:26 +02:00
83 changed files with 3507 additions and 376 deletions
@@ -132,9 +132,8 @@ myApp.controller('sortableController', function ($scope: MySortableControllerSco
$scope.sortableOptions.tolerance = 'pointer';
$scope.sortableOptions.zIndex = 9999;
$scope.sortableOptions['ui-floating'] = undefined;
$scope.sortableOptions['ui-floating'] = null;
$scope.sortableOptions['ui-floating'] = false;
$scope.sortableOptions['ui-floating'] = true;
$scope.sortableOptions['ui-floating'] = "auto";
const sortableFloatingOption0: ng.ui.UISortableOptions<SortableModelInfo> = { 'ui-floating': undefined };
const sortableFloatingOption1: ng.ui.UISortableOptions<SortableModelInfo> = { 'ui-floating': false };
const sortableFloatingOption2: ng.ui.UISortableOptions<SortableModelInfo> = { 'ui-floating': true };
const sortableFloatingOption3: ng.ui.UISortableOptions<SortableModelInfo> = { 'ui-floating': 'auto' };
});
+1 -1
View File
@@ -12,7 +12,7 @@ declare module 'angular' {
export namespace ui {
interface UISortableOptions<T> extends SortableOptions<T> {
'ui-floating'?: string | boolean;
'ui-floating'?: 'auto' | boolean;
}
interface UISortableProperties<T> {
+2 -2
View File
@@ -124,7 +124,7 @@ declare namespace chroma {
* Computes the eucledian distance between two colors in a given color space (default is 'lab').
* {@link https://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions}
*/
distance(color1: string | Color, color2: string | Color, colorSpace?: keyof ColorSpaces): Color;
distance(color1: string | Color, color2: string | Color, colorSpace?: keyof ColorSpaces): number;
/**
* Computes color difference {@link https://en.wikipedia.org/wiki/Color_difference#CMC_l:c_.281984.29} as
@@ -133,7 +133,7 @@ declare namespace chroma {
* {@link https://web.archive.org/web/20160306044036/http://www.brucelindbloom.com/javascript/ColorDiff.js}
* The parameters L (default 1) and C (default 1) are weighting factors for lightness and chromacity.
*/
deltaE(color1: string | Color, color2: string | Color, L?: number, C?: number): Color;
deltaE(color1: string | Color, color2: string | Color, L?: number, C?: number): number;
/**
* chroma.brewer is an map of ColorBrewer scales that are included in chroma.js for convenience.
+1
View File
@@ -16,4 +16,5 @@ graph.transition = (selection: d3.Selection<any>) => {
const render = new dagreD3.render();
const svg = d3.select("svg");
render.arrows()["arrowType"] = (parent: d3.Selection<any>, id: string, edge: dagre.Edge, type: string) => {};
render.shapes()["shapeName"] = (parent: d3.Selection<any>, bbox: any, node: dagre.Node) => {};
render(svg, graph);
+2
View File
@@ -11,6 +11,7 @@ export as namespace dagreD3;
export * from "dagre";
export const render: { new(): Render };
export const intersect: { [shapeName: string]: (node: dagre.Node, points: Array<{}>, point: any) => void };
declare module "dagre" {
namespace graphlib {
@@ -32,4 +33,5 @@ export interface Render {
// see http://cpettitt.github.io/project/dagre-d3/latest/demo/user-defined.html for example usage
arrows(): { [arrowStyleName: string]: (parent: d3.Selection<any>, id: string, edge: dagre.Edge, type: string) => void };
(selection: d3.Selection<any>, g: dagre.graphlib.Graph): void;
shapes(): { [shapeStyleName: string]: (parent: d3.Selection<any>, bbox: any, node: dagre.Node) => void };
}
+44 -97
View File
@@ -13,7 +13,6 @@
// TypeScript Version: 2.8
/// <reference types="jquery" />
/// <reference types="handlebars" />
declare module 'ember' {
import {
@@ -25,7 +24,7 @@ declare module 'ember' {
} from 'ember/-private-types/object/computed';
import { Objectify, Fix, KeysOfType, TypeLookup } from 'ember/-private-types/utils';
import { EmberClassArguments, EmberClassConstructor, EmberInstanceArguments } from 'ember/-private-types/object';
import * as HandlebarsNamespace from 'handlebars';
// Capitalization is intentional: this makes it much easier to re-export RSVP on
// the Ember namespace.
import Rsvp from 'rsvp';
@@ -34,6 +33,8 @@ declare module 'ember' {
import { Registry as ServiceRegistry } from '@ember/service';
import { Registry as ControllerRegistry } from '@ember/controller';
import ModuleComputed from '@ember/object/computed';
import * as EmberString from '@ember/string';
import * as EmberPolyfills from '@ember/polyfills';
// Get an alias to the global Array type to use in inner scope below.
type GlobalArray<T> = T[];
@@ -1733,11 +1734,11 @@ declare module 'ember' {
key: keyof this,
target: Target,
method: ObserverMethod<Target, this>
): void;
): this;
addObserver(
key: keyof this,
method: ObserverMethod<this, this>
): void;
): this;
/**
* Remove an observer you have previously registered on this object. Pass
* the same key, target, and method you passed to `addObserver()` and your
@@ -1747,11 +1748,11 @@ declare module 'ember' {
key: keyof this,
target: Target,
method: ObserverMethod<Target, this>
): any;
): this;
removeObserver(
key: keyof this,
method: ObserverMethod<this, this>
): any;
): this;
/**
* Retrieves the value of a property, or a default value in the case that the
* property returns `undefined`.
@@ -2421,27 +2422,24 @@ declare module 'ember' {
function K(): any;
function createFrame(objec: any): any;
function Exception(message: string): void;
class SafeString {
constructor(str: string);
toString(): string;
}
const SafeString: typeof HandlebarsNamespace.SafeString;
function parse(string: string): any;
function print(ast: any): void;
const logger: typeof Ember.Logger;
function log(level: string, str: string): void;
}
namespace String {
function camelize(str: string): string;
function capitalize(str: string): string;
function classify(str: string): string;
function dasherize(str: string): string;
function decamelize(str: string): string;
const camelize: typeof EmberString.camelize;
const capitalize: typeof EmberString.capitalize;
const classify: typeof EmberString.classify;
const dasherize: typeof EmberString.dasherize;
const decamelize: typeof EmberString.decamelize;
function fmt(...args: string[]): string;
function htmlSafe(str: string): Handlebars.SafeString;
function isHTMLSafe(str: string): boolean;
function loc(template: string, args?: string[]): string;
function underscore(str: string): string;
function w(str: string): string[];
const htmlSafe: typeof EmberString.htmlSafe;
const isHTMLSafe: typeof EmberString.isHTMLSafe;
const loc: typeof EmberString.loc;
const underscore: typeof EmberString.underscore;
const w: typeof EmberString.w;
}
const computed: {
<T>(cb: ComputedPropertyCallback<T>): ComputedProperty<T>;
@@ -3138,11 +3136,7 @@ declare module 'ember' {
* A value is present if it not `isBlank`.
*/
function isPresent(obj?: any): boolean;
/**
* Merge the contents of two objects together into the first object.
* @deprecated Use Object.assign
*/
function merge<T extends object, U extends object>(original: T, updates: U): Mix<T, U>;
const merge: typeof EmberPolyfills.merge;
/**
* Makes a method available via an additional name.
*/
@@ -3150,33 +3144,33 @@ declare module 'ember' {
/**
* Specify a method that observes property changes.
*/
function observer(key1: string, func: (target: any, key: string) => void): void;
function observer(
function observer<Fn extends (target: any, key: string) => void>(key1: string, func: Fn): Fn;
function observer<Fn extends (target: any, key: string) => void>(
key1: string,
key2: string,
func: (target: any, key: string) => void
): void;
function observer(
func: Fn
): Fn;
function observer<Fn extends (target: any, key: string) => void>(
key1: string,
key2: string,
key3: string,
func: (target: any, key: string) => void
): void;
function observer(
func: Fn
): Fn;
function observer<Fn extends (target: any, key: string) => void>(
key1: string,
key2: string,
key3: string,
key4: string,
func: (target: any, key: string) => void
): void;
function observer(
func: Fn
): Fn;
function observer<Fn extends (target: any, key: string) => void>(
key1: string,
key2: string,
key3: string,
key4: string,
key5: string,
func: (target: any, key: string) => void
): void;
func: Fn
): Fn;
/**
* Adds an observer on a property.
*/
@@ -3233,6 +3227,11 @@ declare module 'ember' {
key: K,
value: UnwrapComputedPropertySetter<T[K]>
): UnwrapComputedPropertyGetter<T[K]>;
function set<T, K extends keyof T>(
obj: T,
key: K,
value: T[K]
): T[K];
/**
* Error-tolerant form of `Ember.set`. Will not blow up if any part of the
* chain is `undefined`, `null`, or destroyed.
@@ -3247,6 +3246,11 @@ declare module 'ember' {
obj: T,
hash: Pick<UnwrapComputedPropertySetters<T>, K>
): Pick<UnwrapComputedPropertyGetters<T>, K>;
// TODO: in TS2.9 - Pick<UnwrapComputedPropertySetters<T> | T, K>
function setProperties<T, K extends keyof T>(
obj: T,
hash: Pick<T, K>
): Pick<T, K>;
/**
* Detects when a specific package of Ember (e.g. 'Ember.Application')
* has fully loaded and is available for extension.
@@ -3289,14 +3293,12 @@ declare module 'ember' {
function typeOf<T>(value: T): KeysOfType<TypeLookup, T>;
function typeOf(): 'undefined';
function typeOf(item: any): string;
// TODO: replace with an es6 reexport when declare module 'ember' is removed
/**
* Copy properties from a source object to a target object.
* @deprecated Use Object.assign
*/
function assign<T extends object, U extends object>(target: T, source: U): Mix<T, U>;
function assign<T extends object, U extends object, V extends object>(target: T, source1: U, source2: V): Mix3<T, U, V>;
function assign<T extends object, U extends object, V extends object, W extends object>(target: T, source1: U, source2: V, source3: W): Mix4<T, U, V, W>;
const assign: typeof EmberPolyfills.assign;
/**
* Polyfill for Object.create
* @deprecated Use Object.create
@@ -3331,12 +3333,6 @@ declare module 'ember' {
: undefined;
function tryInvoke<FNAME extends keyof T, T extends object>(obj: T, methodName: FNAME): T[FNAME] extends (() => any) ? ReturnType<T[FNAME]> : undefined;
function tryInvoke(obj: object, methodName: string, args?: any[]): undefined;
/**
* Forces the passed object to be part of an array. If the object is already
* an array, it will return the object. Otherwise, it will add the object to
* an array. If obj is `null` or `undefined`, it will return an empty array.
*/
function makeArray<T>(obj?: T[] | T | null): T[];
/**
* Framework objects in an Ember application (components, services, routes, etc.)
* are created via a factory and dependency injection system. Each of these
@@ -3551,7 +3547,6 @@ declare module '@ember/array' {
export default EmberArray;
export const A: typeof Ember.A;
export const isArray: typeof Ember.isArray;
export const makeArray: typeof Ember.makeArray;
}
declare module '@ember/array/mutable' {
@@ -3647,37 +3642,12 @@ declare module '@ember/engine/instance' {
export default class EngineInstance extends Ember.EngineInstance { }
}
declare module '@ember/enumerable' {
import Ember from 'ember';
type Enumerable<T> = Ember.Enumerable<T>;
const Enumerable: typeof Ember.Enumerable;
export default Enumerable;
}
declare module '@ember/error' {
import Ember from 'ember';
const Error: typeof Ember.Error;
export default Error;
}
declare module '@ember/instrumentation' {
import Ember from 'ember';
export const instrument: typeof Ember.instrument;
export const reset: typeof Ember.reset;
export const subscribe: typeof Ember.subscribe;
export const unsubscribe: typeof Ember.unsubscribe;
}
declare module '@ember/map' {
import Ember from 'ember';
export default class EmberMap extends Ember.Map { }
}
declare module '@ember/map/with-default' {
import Ember from 'ember';
export default class MapWithDefault extends Ember.MapWithDefault { }
}
declare module '@ember/object' {
import Ember from 'ember';
export default class EmberObject extends Ember.Object { }
@@ -3790,15 +3760,6 @@ declare module '@ember/object/proxy' {
export default class ObjectProxy extends Ember.ObjectProxy { }
}
declare module '@ember/polyfills' {
import Ember from 'ember';
export const assign: typeof Ember.assign;
export const create: typeof Ember.create;
export const hasPropertyAccessors: typeof Ember.platform.hasPropertyAccessors;
export const keys: typeof Ember.keys;
export const merge: typeof Ember.merge;
}
declare module '@ember/routing/auto-location' {
import Ember from 'ember';
export default class AutoLocation extends Ember.AutoLocation { }
@@ -3872,20 +3833,6 @@ declare module '@ember/service' {
interface Registry {}
}
declare module '@ember/string' {
import Ember from 'ember';
export const camelize: typeof Ember.String.camelize;
export const capitalize: typeof Ember.String.capitalize;
export const classify: typeof Ember.String.classify;
export const dasherize: typeof Ember.String.dasherize;
export const decamelize: typeof Ember.String.decamelize;
export const htmlSafe: typeof Ember.String.htmlSafe;
export const isHTMLSafe: typeof Ember.String.isHTMLSafe;
export const loc: typeof Ember.String.loc;
export const underscore: typeof Ember.String.underscore;
export const w: typeof Ember.String.w;
}
declare module '@ember/test' {
import Ember from 'ember';
export const registerAsyncHelper: typeof Ember.Test.registerAsyncHelper;
+17
View File
@@ -49,3 +49,20 @@ class Foo extends Ember.Object.extend({
});
}
}
export class Foo2 extends Ember.Object {
name!: string;
changeName(name: string) {
let a: string = this.set('name', name);
let b: number = this.set('name', name); // $ExpectError
let x: string = Ember.set(this, 'name', name);
let y: number = Ember.set(this, 'name', name); // $ExpectError
this.setProperties({
name
});
Ember.setProperties(this, {
name
});
}
}
+4 -4
View File
@@ -69,13 +69,13 @@ class DemoObservable implements Observable {
notifyPropertyChange(keyName: string): this {
throw new Error("Method not implemented.");
}
addObserver<Target>(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): void;
addObserver<K extends keyof this>(key: K, method: keyof this | ((this: this, sender: this, key: K, value: this[K], rev: number) => void)): void;
addObserver<Target>(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): any;
addObserver<K extends keyof this>(key: K, method: keyof this | ((this: this, sender: this, key: K, value: this[K], rev: number) => void)): any;
addObserver(key: any, target: any, method?: any) {
throw new Error("Method not implemented.");
}
removeObserver<Target>(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): void;
removeObserver(key: keyof this, method: keyof this | ((this: this, sender: this, key: string, value: any, rev: number) => void)): void;
removeObserver<Target>(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): any;
removeObserver(key: keyof this, method: keyof this | ((this: this, sender: this, key: string, value: any, rev: number) => void)): any;
removeObserver(key: any, target: any, method?: any): void {
throw new Error("Method not implemented.");
}
+5
View File
@@ -1,4 +1,5 @@
import Ember from 'ember';
import { SafeString } from 'handlebars';
const { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w } = Ember.String;
@@ -34,3 +35,7 @@ loc(); // $ExpectError
loc("_Hello World"); // $ExpectType string
// TODO - fix this case upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/281
loc("_Hello %@ %@", ["John", "Smith"]); // $ExpectType string
const handlebarsSafeString: SafeString = Ember.String.htmlSafe('lorem ipsum...');
Ember.String.htmlSafe('lorem ipsum...'); // $ExpectType SafeString
const regularString: string = Ember.String.htmlSafe('lorem ipsum...'); // $ExpectError
-8
View File
@@ -62,14 +62,6 @@ function testOnError() {
};
}
function testMakeArray() {
assertType<any[]>(Ember.makeArray());
assertType<any[]>(Ember.makeArray(null));
assertType<any[]>(Ember.makeArray(undefined));
assertType<string[]>(Ember.makeArray('lindsay'));
assertType<number[]>(Ember.makeArray([1, 2, 42]));
}
function testDeprecateFunc() {
function newMethod(first: string, second: number): string {
return '';
+4
View File
@@ -14,6 +14,10 @@
"typeRoots": [
"../"
],
"paths": {
"@ember/string": ["ember__string"],
"@ember/polyfills": ["ember__polyfills"]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
+38
View File
@@ -0,0 +1,38 @@
import Ember from 'ember';
type ComputedProperty<Get, Set = Get> = Ember.ComputedProperty<Get, Set>;
declare const ComputedProperty: typeof Ember.ComputedProperty;
export default ComputedProperty;
export const alias: typeof Ember.computed.alias;
export const and: typeof Ember.computed.and;
export const bool: typeof Ember.computed.bool;
export const collect: typeof Ember.computed.collect;
export const deprecatingAlias: typeof Ember.computed.deprecatingAlias;
export const empty: typeof Ember.computed.empty;
export const equal: typeof Ember.computed.equal;
export const expandProperties: typeof Ember.expandProperties;
export const filter: typeof Ember.computed.filter;
export const filterBy: typeof Ember.computed.filterBy;
export const gt: typeof Ember.computed.gt;
export const gte: typeof Ember.computed.gte;
export const intersect: typeof Ember.computed.intersect;
export const lt: typeof Ember.computed.lt;
export const lte: typeof Ember.computed.lte;
export const map: typeof Ember.computed.map;
export const mapBy: typeof Ember.computed.mapBy;
export const match: typeof Ember.computed.match;
export const max: typeof Ember.computed.max;
export const min: typeof Ember.computed.min;
export const none: typeof Ember.computed.none;
export const not: typeof Ember.computed.not;
export const notEmpty: typeof Ember.computed.notEmpty;
export const oneWay: typeof Ember.computed.oneWay;
export const or: typeof Ember.computed.or;
export const readOnly: typeof Ember.computed.readOnly;
export const reads: typeof Ember.computed.reads;
export const setDiff: typeof Ember.computed.setDiff;
export const sort: typeof Ember.computed.sort;
export const sum: typeof Ember.computed.sum;
export const union: typeof Ember.computed.union;
export const uniq: typeof Ember.computed.uniq;
export const uniqBy: typeof Ember.computed.uniqBy;
+3
View File
@@ -0,0 +1,3 @@
import Ember from 'ember';
export default class CoreObject extends Ember.CoreObject { }
+6
View File
@@ -0,0 +1,6 @@
import Ember from 'ember';
type Evented = Ember.Evented;
declare const Evented: typeof Ember.Evented;
export default Evented;
export const on: typeof Ember.on;
+5
View File
@@ -0,0 +1,5 @@
import Ember from 'ember';
export const addListener: typeof Ember.addListener;
export const removeListener: typeof Ember.removeListener;
export const sendEvent: typeof Ember.sendEvent;
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for @ember/object 3.0
// Project: http://emberjs.com/
// Definitions by: Mike North <https://github.com/mike-north>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import Ember from 'ember';
declare class EmberObject extends Ember.Object { }
export default EmberObject;
export const aliasMethod: typeof Ember.aliasMethod;
export const computed: typeof Ember.computed;
export const defineProperty: typeof Ember.defineProperty;
export const get: typeof Ember.get;
export const getProperties: typeof Ember.getProperties;
export const getWithDefault: typeof Ember.getWithDefault;
export const observer: typeof Ember.observer;
export const set: typeof Ember.set;
export const setProperties: typeof Ember.setProperties;
export const trySet: typeof Ember.trySet;
+5
View File
@@ -0,0 +1,5 @@
import Ember from 'ember';
export const cacheFor: typeof Ember.cacheFor;
export const copy: typeof Ember.copy;
export const guidFor: typeof Ember.guidFor;
+3
View File
@@ -0,0 +1,3 @@
import Ember from 'ember';
export default class Mixin<T, Base = Ember.Object> extends Ember.Mixin<T, Base> {}
+5
View File
@@ -0,0 +1,5 @@
import Ember from 'ember';
type Observable = Ember.Observable;
declare const Observable: typeof Ember.Observable;
export default Observable;
+4
View File
@@ -0,0 +1,4 @@
import Ember from 'ember';
export const addObserver: typeof Ember.addObserver;
export const removeObserver: typeof Ember.removeObserver;
+5
View File
@@ -0,0 +1,5 @@
import Ember from 'ember';
type PromiseProxyMixin<T> = Ember.PromiseProxyMixin<T>;
declare const PromiseProxyMixin: typeof Ember.PromiseProxyMixin;
export default PromiseProxyMixin;
+3
View File
@@ -0,0 +1,3 @@
import Ember from 'ember';
export default class ObjectProxy extends Ember.ObjectProxy { }
@@ -0,0 +1,21 @@
import { assertType } from './lib/assert';
import EmberObject from '@ember/object';
class Foo extends EmberObject {
hello() { return 'world'; }
protected bar() { return 'bar'; }
private baz() { return 'baz'; }
}
const f = new Foo();
assertType<string>(f.hello());
assertType<string>(f.bar()); // $ExpectError
assertType<string>(f.baz()); // $ExpectError
// TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291
// class Foo2 extends EmberObject.extend({
// bar: ''
// }) {
// hello() { return 'world'; }
// protected bar() { return 'bar'; } // $ExpectError
// private baz() { return 'baz'; }
// }
+198
View File
@@ -0,0 +1,198 @@
import EmberObject, { computed } from '@ember/object';
import ComputedProperty, {
alias,
or,
and,
filter,
equal,
empty,
filterBy,
notEmpty,
none,
not,
min,
max,
gt,
gte,
lt,
lte,
readOnly,
reads,
setDiff,
sort,
intersect,
mapBy,
match,
map,
oneWay,
sum,
union,
uniqBy,
uniq,
deprecatingAlias,
bool,
collect
} from '@ember/object/computed';
import { assertType } from './lib/assert';
const Person = EmberObject.extend({
firstName: '',
lastName: '',
age: 0,
noArgs: computed<string>(() => 'test'),
fullName: computed<string>('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
}),
fullNameReadonly: computed<string>('fullName', function() {
return this.get('fullName');
}).readOnly(),
fullNameWritable: computed<string>('firstName', 'lastName', {
get() {
return this.get('fullName');
},
set(key, value) {
const [first, last] = value.split(' ');
this.set('firstName', first);
this.set('lastName', last);
return value;
}
}),
fullNameGetOnly: computed<string>('fullName', {
get() {
return this.get('fullName');
}
}),
fullNameSetOnly: computed<string>('firstName', 'lastName', {
set(key, value) {
const [first, last] = value.split(' ');
this.set('firstName', first);
this.set('lastName', last);
return value;
}
}),
combinators: computed<string>(function() {
return this.get('firstName');
}).property('firstName')
.meta({ foo: 'bar' })
.volatile()
.readOnly(),
explicitlyDeclared: alias('fullName') as ComputedProperty<string>,
});
const person = Person.create({
firstName: 'Fred',
lastName: 'Smith',
age: 29,
});
assertType<string>(person.firstName);
assertType<number>(person.age);
assertType<ComputedProperty<string>>(person.noArgs);
assertType<ComputedProperty<string>>(person.fullName);
assertType<ComputedProperty<string>>(person.fullNameReadonly);
assertType<ComputedProperty<string>>(person.fullNameWritable);
assertType<ComputedProperty<string>>(person.fullNameGetOnly);
assertType<ComputedProperty<string>>(person.fullNameSetOnly);
assertType<ComputedProperty<string>>(person.combinators);
assertType<ComputedProperty<string>>(person.explicitlyDeclared);
assertType<string>(person.get('firstName'));
assertType<number>(person.get('age'));
assertType<string>(person.get('noArgs'));
assertType<string>(person.get('fullName'));
assertType<string>(person.get('fullNameReadonly'));
assertType<string>(person.get('fullNameWritable'));
assertType<string>(person.get('fullNameGetOnly'));
assertType<string>(person.get('fullNameSetOnly'));
assertType<string>(person.get('combinators'));
assertType<string>(person.get('explicitlyDeclared'));
assertType<{ firstName: string, fullName: string, age: number }>(person.getProperties('firstName', 'fullName', 'age'));
const person2 = Person.create({
fullName: 'Fred Smith'
});
assertType<string>(person2.get('firstName'));
assertType<string>(person2.get('fullName'));
const person3 = Person.extend({
firstName: 'Fred',
fullName: 'Fred Smith'
}).create();
assertType<string>(person3.get('firstName'));
assertType<string>(person3.get('fullName'));
const person4 = Person.extend({
firstName: computed(() => 'Fred'),
fullName: computed(() => 'Fred Smith')
}).create();
assertType<string>(person4.get('firstName'));
assertType<string>(person4.get('fullName'));
// computed property macros
const objectWithComputedProperties = EmberObject.extend({
alias: alias('foo'),
and: and('foo', 'bar', 'baz', 'qux'),
bool: bool('foo'),
collect: collect('foo', 'bar', 'baz', 'qux'),
deprecatingAlias: deprecatingAlias('foo', {
id: 'hamster.deprecate-banana',
until: '3.0.0'
}),
empty: empty('foo'),
equalNumber: equal('foo', 1),
equalString: equal('foo', 'bar'),
equalObject: equal('foo', {}),
filter: filter('foo', (item) => item === 'bar'),
filterBy1: filterBy('foo', 'bar'),
filterBy2: filterBy('foo', 'bar', false),
gt: gt('foo', 3),
gte: gte('foo', 3),
intersect: intersect('foo', 'bar', 'baz', 'qux'),
lt: lt('foo', 3),
lte: lte('foo', 3),
map: map('foo', (item, index) => item.bar),
mapBy: mapBy('foo', 'bar'),
match: match('foo', /^tom.ter$/),
max: max('foo'),
min: min('foo'),
none: none('foo'),
not: not('foo'),
notEmpty: notEmpty('foo'),
oneWay: oneWay('foo'),
or: or('foo', 'bar', 'baz', 'qux'),
readOnly: readOnly('foo'),
reads: reads('foo'),
setDiff: setDiff('foo', 'bar'),
sort1: sort('foo', 'bar'),
sort2: sort('foo', (itemA, itemB) => {
if (itemA < itemB) {
return -1;
} else if (itemA > itemB) {
return 1;
} else {
return 0;
}
}),
sum: sum('foo'),
union: union('foo', 'bar', 'baz', 'qux'),
uniq: uniq('foo'),
uniqBy: uniqBy('foo', 'bar')
});
const component2 = EmberObject.extend({
isAnimal: or('isDog', 'isCat')
}).create();
assertType<boolean>(component2.get('isAnimal'));
+198
View File
@@ -0,0 +1,198 @@
import Ember from 'ember';
import { assertType } from './lib/assert';
/** Newable tests */
const co1 = new Ember.CoreObject();
// TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
// co1.concatenatedProperties; // $ExpectType string[]
co1.isDestroyed; // $ExpectType boolean
co1.isDestroying; // $ExpectType boolean
co1.destroy(); // $ExpectType CoreObject
co1.toString(); // $ExpectType string
/** .create tests */
const co2 = Ember.CoreObject.create();
// TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
// co2.concatenatedProperties; // $ExpectType string[]
co2.isDestroyed; // $ExpectType boolean
co2.isDestroying; // $ExpectType boolean
co2.destroy(); // $ExpectType CoreObject
co2.toString(); // $ExpectType string
/** .create tests w/ initial instance data passed in */
const co3 = Ember.CoreObject.create({ foo: '123', bar: 456 });
co3.foo; // $ExpectType string
co3.bar; // $ExpectType number
/** .extend with a zero-argument .create() */
const co4 = Ember.CoreObject.extend({
foo: '123',
bar: 456,
baz(): [string, number] {
return [this.foo, this.bar];
}
}).create();
co4.foo; // $ExpectType string
co4.bar; // $ExpectType number
co4.baz; // $ExpectType () => [string, number]
/** .extend with inconsistent arguments passed into .create() */
const class05 = Ember.CoreObject.extend({
foo: '123' as (string | boolean),
bar: 456,
baz() {
return [this.foo, this.bar];
}
});
const c05 = class05.create({ foo: 99 }); // $ExpectError
const c05b = class05.create({ foo: true });
const c05c = class05.create({ foo: 'abc' });
assertType<string>(c05b.foo); // $ExpectError
assertType<boolean>(c05c.foo); // $ExpectError
/** two .extend arguments with a zero-argument .create() */
const co6 = Ember.CoreObject.extend({
foo: '123',
bar: 456,
baz() {
return [this.foo, this.bar];
},
func1() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
this.foo; // $ExpectType string
// this does not include stuff from later extend args
this.bee; // $ExpectError
}
}, {
foo: 99,
bee: 'honey',
func2() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
// TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
this.foo; // $ExpectType string & number
// this includes stuff from earlier extend-args
this.bar; // $ExpectType number
}
}).create();
// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
// assertType<string>(co6.foo); // $ExpectError
assertType<number>(co6.bar); // $ExpectType number
assertType<() => Array<string | number>>(co6.baz); // $ExpectType () => (string | number)[]
/** three .extend arguments with a zero-argument .create() */
const co7 = Ember.CoreObject.extend({
foo: '123',
bar: 456,
baz() {
return [this.foo, this.bar];
},
func1() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
this.foo; // $ExpectType string
// this does not include stuff from later extend args
this.bee; // $ExpectError
}
}, {
foo: 99,
bee: 'honey',
func2() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
// TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
this.foo; // $ExpectType string & number
// this includes stuff from earlier extend-args
this.bar; // $ExpectType number
}
}, {
foo: '99',
money: 'in the banana stand',
func3() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
this.money; // $ExpectType string
// this includes stuff from earlier extend-args
this.bee; // $ExpectType string
this.bar; // $ExpectType number
}
}).create();
// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
// assertType<number>(co7.foo); // $ExpectError
assertType<number>(co7.bar); // $ExpectType number
assertType<string>(co7.money); // $ExpectType string
assertType<() => Array<string | number>>(co7.baz); // $ExpectType () => (string | number)[]
/** four .extend arguments with a zero-argument .create() */
const co8 = Ember.CoreObject.extend({
foo: '123',
bar: 456,
baz() {
return [this.foo, this.bar];
},
func1() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
this.foo; // $ExpectType string
// this does not include stuff from later extend args
this.bee; // $ExpectError
}
}, {
foo: 99,
bee: 'honey',
func2() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
// TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
this.foo; // $ExpectType string & number
// this includes stuff from earlier extend-args
this.bar; // $ExpectType number
// this does not include stuff from later extend args
this.money; // $ExpectError
}
}, {
foo: '99',
money: 'in the banana stand',
func3() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
this.money; // $ExpectType string
// this includes stuff from earlier extend-args
this.bee; // $ExpectType string
this.bar; // $ExpectType number
// this does not include stuff from later extend args
this.neighborhood; // $ExpectError
}
}, {
foo: '99',
neighborhood: 'sudden valley',
func4() {
// this includes stuff from CoreObject
this.init; // $ExpectType () => void
// this includes stuff from this extend-arg
this.neighborhood; // $ExpectType string
// this includes stuff from earlier extend-args
this.bee; // $ExpectType string
this.bar; // $ExpectType number
this.money; // $ExpectType string
}
}).create();
// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291
// assertType<number>(co8.foo); // $ExpectError
assertType<number>(co8.bar); // $ExpectType number
assertType<string>(co8.money); // $ExpectType string
assertType<() => Array<string | number>>(co8.baz); // $ExpectType () => (string | number)[]
@@ -0,0 +1,9 @@
import { assertType } from './lib/assert';
import Ember from 'ember';
import { PersonWithNumberName, Person } from './create';
Person.create({ firstName: 99 }); // $ExpectError
Person.create({}, { firstName: 99 }); // $ExpectError
Person.create({}, {}, { firstName: 99 }); // $ExpectError
const p4 = new PersonWithNumberName();
+54
View File
@@ -0,0 +1,54 @@
import { assertType } from './lib/assert';
import EmberObject, { computed } from '@ember/object';
import ComputedProperty from '@ember/object/computed';
/**
* Zero-argument case
*/
const o = EmberObject.create();
// create returns an object
assertType<object>(o);
// object returned by create type-checks as an instance of Ember.Object
assertType<boolean>(o.isDestroyed); // from instance
assertType<boolean>(o.isDestroying); // from instance
assertType<(key: keyof EmberObject) => any>(o.get); // from prototype
/**
* One-argument case
*/
const o1 = EmberObject.create({x: 9, y: 'hello', z: false});
assertType<number>(o1.x);
assertType<string>(o1.y);
o1.y; // $ExpectType string
o1.z; // $ExpectType boolean
const obj = EmberObject.create({ a: 1 }, { b: 2 }, { c: 3 });
assertType<number>(obj.b);
assertType<number>(obj.a);
assertType<number>(obj.c);
export class Person extends EmberObject {
fullName = computed('firstName', 'lastName', function() {
return [this.firstName + this.lastName].join(' ');
});
firstName: string;
lastName: string;
age: number;
}
const p = new Person();
assertType<string>(p.firstName);
assertType<ComputedProperty<string>>(p.fullName);
assertType<string>(p.get('fullName'));
const p2 = Person.create({ firstName: 'string' });
const p2b = Person.create({}, { firstName: 'string' });
const p2c = Person.create({}, {}, { firstName: 'string' });
export class PersonWithNumberName extends Person.extend({
fullName: 6
}) {}
const p4 = new PersonWithNumberName();
assertType<string>(p4.firstName);
assertType<number>(p4.fullName);
+20
View File
@@ -0,0 +1,20 @@
import { assertType } from './lib/assert';
import EmberObject from '@ember/object';
const ExtendClass = EmberObject.extend({
foo: 'hello'
});
class ES6Class extends EmberObject {
bar: string;
}
const testObject = null;
if (ExtendClass.detectInstance(testObject)) {
assertType<string>(testObject.foo);
}
if (ES6Class.detectInstance(testObject)) {
assertType<string>(testObject.bar);
}
+20
View File
@@ -0,0 +1,20 @@
import { assertType } from './lib/assert';
import EmberObject from '@ember/object';
const ExtendClass = EmberObject.extend({
foo: 'hello'
});
class ES6Class extends EmberObject {
bar: string;
}
const TestClass = EmberObject;
if (ExtendClass.detect(TestClass)) {
assertType<string>(TestClass.create().foo);
}
if (ES6Class.detect(TestClass)) {
assertType<string>(TestClass.create().bar);
}
+61
View File
@@ -0,0 +1,61 @@
import EmberObject, { observer } from '@ember/object';
import { sendEvent, addListener, removeListener } from '@ember/object/events';
import Evented, { on } from '@ember/object/evented';
function testOn() {
const Job = EmberObject.extend({
logCompleted: on('completed', () => {
console.log('Job completed!');
})
});
const job = Job.create();
sendEvent(job, 'completed'); // Logs 'Job completed!'
}
function testEvented() {
const Person = EmberObject.extend(Evented, {
greet() {
this.trigger('greet');
}
});
const person = Person.create();
person.on('greet', () => {
console.log('Our person has greeted');
});
person.on('greet', () => {
console.log('Our person has greeted');
}).one('greet', () => {
console.log('Offer one-time special');
}).off('event', {}, () => {});
person.greet();
}
function testObserver() {
EmberObject.extend({
// TODO: enable after https://github.com/typed-ember/ember-cli-typescript/issues/290
// valueObserver: observer('value', () => {
// // Executes whenever the "value" property changes
// })
});
}
function testListener() {
EmberObject.extend({
init() {
addListener(this, 'willDestroy', this, 'willDestroyListener');
addListener(this, 'willDestroy', this, 'willDestroyListener', true);
addListener(this, 'willDestroy', this, this.willDestroyListener);
addListener(this, 'willDestroy', this, this.willDestroyListener, true);
removeListener(this, 'willDestroy', this, 'willDestroyListener');
removeListener(this, 'willDestroy', this, this.willDestroyListener);
},
willDestroyListener() {
}
});
}
+61
View File
@@ -0,0 +1,61 @@
import EmberObject from '@ember/object';
import { assertType } from './lib/assert';
const Person = EmberObject.extend({
firstName: '',
lastName: '',
getFullName() {
return `${this.firstName} ${this.lastName}`;
},
getFullName2(): string {
return `${this.get('firstName')} ${this.get('lastName')}`;
}
});
assertType<string>(Person.prototype.firstName);
assertType<() => string>(Person.prototype.getFullName);
const person = Person.create({
firstName: 'Joe',
lastName: 'Blow',
extra: 42
});
assertType<string>(person.getFullName());
assertType<number>(person.extra);
class ES6Person extends EmberObject {
firstName: string;
lastName: string;
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
get fullName2(): string {
return `${this.get('firstName')} ${this.get('lastName')}`;
}
}
assertType<string>(ES6Person.prototype.firstName);
assertType<string>(ES6Person.prototype.fullName);
const es6Person = ES6Person.create({
firstName: 'Joe',
lastName: 'Blow',
extra: 42
});
assertType<string>(es6Person.fullName);
assertType<number>(es6Person.extra);
class PersonWithStatics extends EmberObject {
static isPerson = true;
}
const PersonWithStatics2 = PersonWithStatics.extend({});
class PersonWithStatics3 extends PersonWithStatics {}
class PersonWithStatics4 extends PersonWithStatics2 {}
assertType<boolean>(PersonWithStatics.isPerson);
assertType<boolean>(PersonWithStatics2.isPerson);
assertType<boolean>(PersonWithStatics3.isPerson);
assertType<boolean>(PersonWithStatics4.isPerson);
+5
View File
@@ -0,0 +1,5 @@
/** Static assertion that `value` has type `T` */
// Disable tslint here b/c the generic is used to let us do a type coercion and
// validate that coercion works for the type value "passed into" the function.
// tslint:disable-next-line:no-unnecessary-generics
export declare function assertType<T>(value: T): T;
+75
View File
@@ -0,0 +1,75 @@
import EmberObject, { computed } from "@ember/object";
const LifetimeHooks = EmberObject.extend({
resource: null as {} | null,
init() {
this._super();
this.resource = {};
},
willDestroy() {
delete this.resource;
this._super();
}
});
class MyObject30 extends EmberObject {
constructor() {
super();
}
}
class MyObject31 extends EmberObject {
constructor(properties: object) {
super(properties);
}
}
class Foo extends EmberObject {
a = computed({
get() { return ''; },
set(key: string, newVal: string) { return ''; }
});
b = 5;
baz() {
const y = this.b; // $ExpectType number
const z = this.a; // $ExpectType ComputedProperty<string, string>
this.b = 10;
this.get('b').toFixed(4); // $ExpectType string
this.set('a', 'abc').split(','); // $ExpectType string[]
this.set('b', 10).toFixed(4); // $ExpectType string
this.setProperties({ b: 11 });
// this.setProperties({ b: '11' }); // $ExpectError
this.setProperties({
a: 'def',
b: 11
});
}
}
// TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291
// class Foo extends EmberObject.extend({
// a: computed({
// get() { return ''; },
// set(key: string, newVal: string) { return ''; }
// })
// }) {
// b = 5;
// baz() {
// const y = this.b; // $ExpectType number
// const z = this.a; // $ExpectType ComputedProperty<string, string>
// this.b = 10;
// this.get('b').toFixed(4); // $ExpectType string
// this.set('a', 'abc').split(','); // $ExpectType string[]
// this.set('b', 10).toFixed(4); // $ExpectType string
// this.setProperties({ b: 11 });
// // this.setProperties({ b: '11' }); // $ExpectError
// this.setProperties({
// a: 'def',
// b: 11
// });
// }
// }
+114
View File
@@ -0,0 +1,114 @@
import { assertType } from './lib/assert';
import EmberObject, { computed, getWithDefault, getProperties, get, setProperties, set } from '@ember/object';
import { removeObserver, addObserver } from '@ember/object/observers';
class MyComponent extends EmberObject {
foo = 'bar';
init() {
this._super.apply(this, arguments);
this.addObserver('foo', this, 'fooDidChange');
this.addObserver('foo', this, this.fooDidChange);
addObserver(this, 'foo', this, 'fooDidChange');
addObserver(this, 'foo', this, this.fooDidChange);
this.removeObserver('foo', this, 'fooDidChange');
this.removeObserver('foo', this, this.fooDidChange);
removeObserver(this, 'foo', this, 'fooDidChange');
removeObserver(this, 'foo', this, this.fooDidChange);
const lambda = () => {
this.fooDidChange(this, 'foo');
};
this.addObserver('foo', lambda);
this.removeObserver('foo', lambda);
addObserver(this, 'foo', lambda);
removeObserver(this, 'foo', lambda);
}
fooDidChange(sender: this, key: keyof this) {
// your code
}
}
const myComponent = MyComponent.create();
myComponent.addObserver('foo', null, () => {});
myComponent.set('foo', 'baz');
const person = EmberObject.create({
name: 'Fred',
age: 29,
capitalized: computed<string>(function() {
return this.get('name').toUpperCase();
})
});
const pojo = { name: 'Fred', age: 29 };
function testGet() {
assertType<string>(get(person, 'name'));
assertType<number>(get(person, 'age'));
assertType<string>(get(person, 'capitalized'));
assertType<string>(person.get('name'));
assertType<number>(person.get('age'));
assertType<string>(person.get('capitalized'));
assertType<string>(get(pojo, 'name'));
}
function testGetProperties() {
assertType<{ name: string }>(getProperties(person, 'name'));
assertType<{ name: string, age: number }>(getProperties(person, 'name', 'age'));
assertType<{ name: string, age: number }>(getProperties(person, [ 'name', 'age' ]));
assertType<{ name: string, age: number, capitalized: string }>(getProperties(person, 'name', 'age', 'capitalized'));
assertType<{ name: string }>(person.getProperties('name'));
assertType<{ name: string, age: number }>(person.getProperties('name', 'age'));
assertType<{ name: string, age: number }>(person.getProperties([ 'name', 'age' ]));
assertType<{ name: string, age: number, capitalized: string }>(person.getProperties('name', 'age', 'capitalized'));
assertType<{ name: string, age: number }>(getProperties(pojo, 'name', 'age'));
}
function testGetWithDefault() {
assertType<string>(getWithDefault(person, 'name', 'Joe'));
assertType<number>(getWithDefault(person, 'age', 20));
assertType<string>(getWithDefault(person, 'capitalized', 'JOE'));
assertType<string>(person.getWithDefault('name', 'Joe'));
assertType<number>(person.getWithDefault('age', 20));
assertType<string>(person.getWithDefault('capitalized', 'JOE'));
assertType<string>(getWithDefault(pojo, 'name', 'JOE'));
}
function testSet() {
assertType<string>(set(person, 'name', 'Joe'));
assertType<number>(set(person, 'age', 35));
assertType<string>(set(person, 'capitalized', 'JOE'));
assertType<string>(person.set('name', 'Joe'));
assertType<number>(person.set('age', 35));
assertType<string>(person.set('capitalized', 'JOE'));
assertType<string>(set(pojo, 'name', 'Joe'));
}
function testSetProperties() {
assertType<{ name: string }>(setProperties(person, { name: 'Joe' }));
assertType<{ name: string, age: number }>(setProperties(person, { name: 'Joe', age: 35 }));
assertType<{ name: string, capitalized: string }>(setProperties(person, { name: 'Joe', capitalized: 'JOE' }));
assertType<{ name: string }>(person.setProperties({ name: 'Joe' }));
assertType<{ name: string, age: number }>(person.setProperties({ name: 'Joe', age: 35 }));
assertType<{ name: string, capitalized: string }>(person.setProperties({ name: 'Joe', capitalized: 'JOE' }));
assertType<{ name: string, age: number }>(setProperties(pojo, { name: 'Joe', age: 35 }));
}
function testDynamic() {
const obj: any = {};
const dynamicKey: string = 'dummy'; // tslint:disable-line:no-inferrable-types
assertType<any>(get(obj, 'dummy'));
assertType<any>(get(obj, dynamicKey));
assertType<string>(getWithDefault(obj, 'dummy', 'default'));
assertType<string>(getWithDefault(obj, dynamicKey, 'default'));
assertType<{ dummy: any }>(getProperties(obj, 'dummy'));
assertType<{ dummy: any }>(getProperties(obj, [ 'dummy' ]));
assertType<object>(getProperties(obj, dynamicKey));
assertType<object>(getProperties(obj, [ dynamicKey ]));
assertType<string>(set(obj, 'dummy', 'value'));
assertType<string>(set(obj, dynamicKey, 'value'));
assertType<{ dummy: string }>(setProperties(obj, { dummy: 'value '}));
assertType<object>(setProperties(obj, { [dynamicKey]: 'value' }));
}
+72
View File
@@ -0,0 +1,72 @@
import { assertType } from "./lib/assert";
import EmberObject from "@ember/object";
import Mixin from "@ember/object/mixin";
type Person = typeof Person.prototype;
const Person = EmberObject.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
}
});
assertType<Person>(Person.reopen());
assertType<string>(Person.create().name);
// tslint:disable-next-line no-void-expression
assertType<void>(Person.create().sayHello());
const Person2 = Person.reopenClass({
species: 'Homo sapiens',
createPerson(name: string): Person {
return Person.create({ name });
}
});
assertType<string>(Person2.create().name);
// tslint:disable-next-line no-void-expression
assertType<void>(Person2.create().sayHello());
assertType<string>(Person2.species);
const tom = Person2.create({
name: 'Tom Dale'
});
const badTom = Person2.create({ name: 99 }); // $ExpectError
const yehuda = Person2.createPerson('Yehuda Katz');
tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(Person2.species); // "Homo sapiens"
const Person3 = Person2.reopen({
goodbyeMessage: 'goodbye',
sayGoodbye() {
alert(`${this.get('goodbyeMessage')}, ${this.get('name')}`);
}
});
const person3 = Person3.create();
person3.get('name');
person3.get('goodbyeMessage');
person3.sayHello();
person3.sayGoodbye();
interface AutoResizeMixin { resizable: true; }
declare const AutoResizeMixin: Mixin<AutoResizeMixin>;
const ResizableTextArea = EmberObject.reopen(AutoResizeMixin, {
scaling: 1.0
});
const text = ResizableTextArea.create();
// TODO fix upstream
// assertType<boolean>(text.resizable);
assertType<number>(text.scaling);
const Reopened = EmberObject.reopenClass({ a: 1 }, { b: 2 }, { c: 3 });
assertType<number>(Reopened.a);
assertType<number>(Reopened.b);
assertType<number>(Reopened.c);
+51
View File
@@ -0,0 +1,51 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@ember/object": ["ember__object"],
"@ember/object/*": ["ember__object/*"]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"computed.d.ts",
"core.d.ts",
"evented.d.ts",
"events.d.ts",
"index.d.ts",
"internals.d.ts",
"mixin.d.ts",
"observable.d.ts",
"observers.d.ts",
"promise-proxy-mixin.d.ts",
"proxy.d.ts",
"test/lib/assert.ts",
"test/access-modifier.ts",
"test/core.ts",
"test/computed.ts",
"test/create.ts",
"test/create-negative.ts",
"test/detect.ts",
"test/detect-instance.ts",
"test/event.ts",
"test/extend.ts",
"test/object.ts",
"test/observable.ts",
"test/reopen.ts"
]
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "dtslint/dt.json",
"rules": { }
}
@@ -6,13 +6,10 @@ import { assign, merge } from '@ember/polyfills';
assign({ a: 6 }, { a: 'b'}).a; // $ExpectType string
assign({ a: 6 }, {}).a; // $ExpectType number
assign({ b: 6 }, {}).a; // $ExpectError
// TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291
// assign({}, { b: 6 }, {}).b; // $ExpectType number
assign({}, { b: 6 }, {}).b; // $ExpectType number
assign({ a: 'hello' }, { b: 6 }, {}).a; // $ExpectType string
// TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291
// assign({ a: 'hello' }, { b: 6 }, { a: true }).a; // $ExpectType boolean
// TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291
// assign({ a: 'hello' }, '', { a: true }).a; // $ExpectError
assign({ a: 'hello' }, { b: 6 }, { a: true }).a; // $ExpectType boolean
assign({ a: 'hello' }, '', { a: true }).a; // $ExpectError
assign({ d: ['gobias industries'] }, { a: 'hello' }, { b: 6 }, { a: true }).d; // $ExpectType string[]
})();
+14 -3
View File
@@ -4,7 +4,18 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import Ember from 'ember';
import { Mix, Mix3, Mix4 } from './types';
export const assign: typeof Ember.assign;
export const merge: typeof Ember.merge;
/**
* Copy properties from a source object to a target object.
* @deprecated Use Object.assign
*/
export function assign<T extends object, U extends object>(target: T, source: U): Mix<T, U>;
export function assign<T extends object, U extends object, V extends object>(target: T, source1: U, source2: V): Mix3<T, U, V>;
export function assign<T extends object, U extends object, V extends object, W extends object>(target: T, source1: U, source2: V, source3: W): Mix4<T, U, V, W>;
/**
* Merge the contents of two objects together into the first object.
* @deprecated Use Object.assign
*/
export function merge<T extends object, U extends object>(original: T, updates: U): Mix<T, U>;
+3 -1
View File
@@ -15,7 +15,8 @@
"../"
],
"paths": {
"@ember/polyfills": ["ember__polyfills"]
"@ember/polyfills": ["ember__polyfills"],
"@ember/polyfills/*": ["ember__polyfills/*"]
},
"types": [],
"noEmit": true,
@@ -23,6 +24,7 @@
},
"files": [
"index.d.ts",
"types.d.ts",
"ember__polyfills-tests.ts"
]
}
+4
View File
@@ -0,0 +1,4 @@
export type Mix<A, B> = B & Pick<A, Exclude<keyof A, keyof B>>;
export type Mix3<A, B, C> = Mix<Mix<A, B>, C>;
export type Mix4<A, B, C, D> = Mix3<Mix<A, B>, C, D>;
export default Mix;
+11 -11
View File
@@ -4,15 +4,15 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import Ember from 'ember';
import { SafeString } from 'handlebars';
export const camelize: typeof Ember.String.camelize;
export const capitalize: typeof Ember.String.capitalize;
export const classify: typeof Ember.String.classify;
export const dasherize: typeof Ember.String.dasherize;
export const decamelize: typeof Ember.String.decamelize;
export const htmlSafe: typeof Ember.String.htmlSafe;
export const isHTMLSafe: typeof Ember.String.isHTMLSafe;
export const loc: typeof Ember.String.loc;
export const underscore: typeof Ember.String.underscore;
export const w: typeof Ember.String.w;
export function camelize(str: string): string;
export function capitalize(str: string): string;
export function classify(str: string): string;
export function dasherize(str: string): string;
export function decamelize(str: string): string;
export function htmlSafe(str: string): Handlebars.SafeString;
export function isHTMLSafe(str: string): boolean;
export function loc(template: string, args?: string[]): string;
export function underscore(str: string): string;
export function w(str: string): string[];
+27 -34
View File
@@ -17,8 +17,7 @@ import EmberObject from '@ember/object';
return;
}
const anotherString = maybeUndefined + 'another string';
// TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/256
// isNone(); // $ExpectType boolean
isNone(); // $ExpectType boolean
isNone(null); // $ExpectType boolean
isNone(undefined); // $ExpectType boolean
isNone(''); // $ExpectType boolean
@@ -30,10 +29,9 @@ import EmberObject from '@ember/object';
/** tryInvoke */
let d = new Date('03/15/2013');
// TODO fix enhance in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/257
// tryInvoke(d, 'getTime'); // $ExpectType number
// tryInvoke(d, 'setFullYear', [2014]); // $ExpectType number
// tryInvoke(d, 'noSuchMethod', [2014]); // $ExpectType undefined
tryInvoke(d, 'getTime'); // $ExpectType number
tryInvoke(d, 'setFullYear', [2014]); // $ExpectType number
tryInvoke(d, 'noSuchMethod', [2014]); // $ExpectType undefined
tryInvoke(d, 'getTime');
tryInvoke(d, 'setFullYear', [2014]);
tryInvoke(d, 'noSuchMethod', [2014]);
@@ -41,8 +39,7 @@ import EmberObject from '@ember/object';
(function() {
/** isPresent */
// TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/258
// isPresent(); // $ExpectType boolean
isPresent(); // $ExpectType boolean
isPresent(null); // $ExpectType boolean
isPresent(undefined); // $ExpectType boolean
isPresent(''); // $ExpectType boolean
@@ -63,29 +60,27 @@ import EmberObject from '@ember/object';
(function() {
/** typeOf */
// TODO: more specific return type in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/259
// typeOf(null); // $ExpectType 'null'
// typeOf(undefined); // $ExpectType 'undefined'
// typeOf('michael'); // $ExpectType 'string'
// // tslint:disable-next-line:no-construct
// typeOf(new String('michael')); // $ExpectType 'string'
// typeOf(101); // $ExpectType 'number'
// // tslint:disable-next-line:no-construct
// typeOf(new Number(101)); // $ExpectType 'number'
// typeOf(true); // $ExpectType 'boolean'
// // tslint:disable-next-line:no-construct
// typeOf(new Boolean(true)); // $ExpectType 'boolean'
// typeOf(() => 4); // $ExpectType 'function'
// typeOf([1, 2, 90]); // $ExpectType 'array'
// typeOf(/abc/); // $ExpectType 'regexp'
// typeOf(new Date()); // $ExpectType 'date'
// typeOf(FileList); // $ExpectType 'filelist'
// // typeOf(EmberObject.extend()); // $ExpectType 'class'
// // typeOf(EmberObject.create()); // $ExpectType 'instance'
// typeOf(new Error('teamocil')); // $ExpectType 'error'
typeOf(null); // $ExpectType "null"
typeOf(undefined); // $ExpectType "undefined"
typeOf('michael'); // $ExpectType "string"
// tslint:disable-next-line:no-construct
typeOf(new String('michael')); // $ExpectType "string"
typeOf(101); // $ExpectType "number"
// tslint:disable-next-line:no-construct
typeOf(new Number(101)); // $ExpectType "number"
typeOf(true); // $ExpectType "boolean"
// tslint:disable-next-line:no-construct
typeOf(new Boolean(true)); // $ExpectType "boolean"
typeOf(() => 4); // $ExpectType "function"
typeOf([1, 2, 90]); // $ExpectType "array"
typeOf(/abc/); // $ExpectType "regexp"
typeOf(new Date()); // $ExpectType "date"
typeOf(new FileList()); // $ExpectType "filelist"
typeOf(EmberObject.extend()); // $ExpectType "class"
typeOf(EmberObject.create()); // $ExpectType "instance"
typeOf(new Error('teamocil')); // $ExpectType "error"
// TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/260
// typeOf();
typeOf();
typeOf(null);
typeOf(undefined);
typeOf('michael');
@@ -130,8 +125,7 @@ import EmberObject from '@ember/object';
(function() {
/** isBlank */
// TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/254
// isBlank(); // $ExpectType boolean
isBlank(); // $ExpectType boolean
isBlank(null); // $ExpectType boolean
isBlank(undefined); // $ExpectType boolean
isBlank(''); // $ExpectType boolean
@@ -147,8 +141,7 @@ import EmberObject from '@ember/object';
(function() {
/** isEmpty */
// TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/255
// isEmpty(); // $ExpectType boolean
isEmpty(); // $ExpectType boolean
isEmpty(null); // $ExpectType boolean
isEmpty(undefined); // $ExpectType boolean
isEmpty(''); // $ExpectType boolean
+18
View File
@@ -2048,6 +2048,11 @@ interface IObjectOptions {
*/
borderColor?: string;
/**
* Array specifying dash pattern of an object's border (hasBorder must be true)
*/
borderDashArray?: number[];
/**
* Color of controlling corners of an object (when it's active)
*/
@@ -3114,6 +3119,10 @@ interface ITextOptions extends IObjectOptions {
* Line height
*/
lineHeight?: number;
/**
* Character spacing
*/
charSpacing?: number;
/**
* When defined, an object is rendered via stroke and this property specifies its color.
* <b>Backwards incompatibility note?:</b> This property was named "strokeStyle" until v1.1.6
@@ -3254,6 +3263,15 @@ export class Text extends Object {
* @param lineHeight Line height
*/
setLineHeight(lineHeight: number): Text;
/**
* Retrieves object's charSpacing
*/
getCharSpacing(): number;
/**
* Sets object's charSpacing
* @param charSpacing Character spacing
*/
setCharSpacing(charSpacing: number): Text;
/**
* Retrieves object's textAlign
*/
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="node" />
import find = require('find-process');
find('pid', 12345).then((processList) => {
processList.forEach((ps) => {
console.log('Full command with args: ' + ps.cmd);
console.log('User group ID (for *nix): ' + ps.gid);
console.log('command/process name: ' + ps.name);
console.log('Process ID: ' + ps.pid);
console.log('Parent process ID: ' + ps.ppid);
console.log('User ID (for *nix): ' + ps.uid);
});
}, (err) => {
console.log(err.stack || err);
});
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for find-process 1.1
// Project: https://github.com/yibn2008/find-process
// Definitions by: Buaban Buataitom <https://github.com/buaban>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare function find(by: string, value: string | number): Promise<Array<{ pid: string, ppid: string, uid: string, gid: string, name: string, cmd: string }>>;
declare namespace find {}
export = find;
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "find-process-tests.ts"]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+4 -2
View File
@@ -1,6 +1,8 @@
// Type definitions for node-fluent-ffmpeg 2.1
// Project: https://github.com/fluent-ffmpeg/node-fluent-ffmpeg
// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk <https://github.com/tcaesvk>, DingWeizhe <https://github.com/DingWeizhe>
// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk <https://github.com/tcaesvk>
// DingWeizhe <https://github.com/DingWeizhe>
// Mounir Abid <https://github.com/mabidina>
// Definitions: https://github.com/DefinitelyType/DefinitelyTyped
/// <reference types="node" />
@@ -11,7 +13,7 @@ import * as stream from "stream";
declare namespace Ffmpeg {
interface FfmpegCommandLogger {
error(...data: any[]): void;
warning(...data: any[]): void;
warn(...data: any[]): void;
info(...data: any[]): void;
debug(...data: any[]): void;
}
@@ -13,6 +13,17 @@ const options: MapOptions = {
featureType: "administrative",
elementType: "all",
stylers: [ {saturation: "-100"} ]
},
{
featureType: "administrative.neighborhood",
stylers: [ {visibility: "off" } ]
},
{
elementType: "labels.text.stroke",
stylers: [ {color: "#242f3e"} ]
},
{
stylers: [ {color: "#fcfffd"} ]
}
],
};
+2 -2
View File
@@ -9,8 +9,8 @@ import * as React from 'react';
export type BootstrapURLKeys = ({ key: string; } | { client: string; v: string; }) & { language?: string };
export interface MapTypeStyle {
elementType: string;
featureType: string;
elementType?: string;
featureType?: string;
stylers: any[];
}
+63
View File
@@ -0,0 +1,63 @@
// Type definitions for jwt-then 1.0
// Project: https://github.com/fl0w/jwt-then#readme
// Definitions by: Definitions by: Max Uetrecht <https://github.com/phenomax>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
export type Secret = string | Buffer | { key: string; passphrase: string };
export interface SignOptions {
/**
* Signature algorithm. Could be one of these values :
* - HS256: HMAC using SHA-256 hash algorithm (default)
* - HS384: HMAC using SHA-384 hash algorithm
* - HS512: HMAC using SHA-512 hash algorithm
* - RS256: RSASSA using SHA-256 hash algorithm
* - RS384: RSASSA using SHA-384 hash algorithm
* - RS512: RSASSA using SHA-512 hash algorithm
* - ES256: ECDSA using P-256 curve and SHA-256 hash algorithm
* - ES384: ECDSA using P-384 curve and SHA-384 hash algorithm
* - ES512: ECDSA using P-521 curve and SHA-512 hash algorithm
* - none: No digital signature or MAC value included
*/
algorithm?: string;
keyid?: string;
/** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */
expiresIn?: string | number;
/** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */
notBefore?: string | number;
audience?: string | string[];
subject?: string;
issuer?: string;
jwtid?: string;
noTimestamp?: boolean;
header?: object;
encoding?: string;
}
/**
* Sign the given payload into a JSON Web Token string
* @param payload - Payload to sign, could be an literal, buffer or string
* @param secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA.
* @param [options] - Options for the signature
* @returns A proiose containing the JSON Web Token string
*/
export function sign(
payload: string | Buffer | object,
secretOrPrivateKey: Secret,
options?: SignOptions,
): Promise<string>;
/**
* Verify given token using a secret or a public key to get a decoded token
* @param token - JWT string to verify
* @param secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.
* @param [options] - Options for the verification
* @returns A promise containing either an error or the decoded JSON Web Token string
*/
export function verify(
token: string,
secretOrPublicKey: string | Buffer,
): Promise<object | string>;
+11
View File
@@ -0,0 +1,11 @@
import jwt = require("jwt-then");
import fs = require("fs");
const testObject = { foo: "bar" };
(async () => {
const token = await jwt.sign(testObject, "foobar");
const verified = await jwt.verify(token, "foobar");
console.log(token, verified);
})();
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jwt-then-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+10 -8
View File
@@ -1,7 +1,9 @@
// Type definitions for Lovefield 2.1
// Project: http://google.github.io/lovefield/
// Definitions by: freshp86 <https://github.com/freshp86>
// zackzeno <https://github.com/zackzeno>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare namespace lf {
enum Order { ASC, DESC }
@@ -59,10 +61,10 @@ declare namespace lf {
}
interface Transaction {
attach(query: query.Builder): Promise<Object[]>;
attach(query: query.Builder): Promise<object[]>;
begin(scope: schema.Table[]): Promise<void>;
commit(): Promise<void>;
exec(queries: query.Builder[]): Promise<Object[][]>;
exec(queries: query.Builder[]): Promise<object[][]>;
rollback(): Promise<void>;
stats(): TransactionStats;
}
@@ -73,9 +75,9 @@ declare namespace lf {
close(): void;
createTransaction(type?: TransactionType): Transaction;
delete(): query.Delete;
export(): Promise<Object>;
export(): Promise<object>;
getSchema(): schema.Database;
import(data: Object): Promise<void>;
import(data: object): Promise<void>;
insertOrReplace(): query.Insert;
insert(): query.Insert;
observe(query: query.Select, callback: Function): void;
@@ -87,7 +89,7 @@ declare namespace lf {
namespace query {
interface Builder {
bind(...values: any[]): Builder;
exec(): Promise<Object[]>;
exec(): Promise<object[]>;
explain(): string;
toSql(): string;
}
@@ -131,9 +133,9 @@ declare namespace lf {
renameTableColumn(
tableName: string, oldColumnName: string,
newColumnName: string): Promise<void>;
createRow(payload: Object): Row;
createRow(payload: object): Row;
getVersion(): number;
dump(): Object[];
dump(): object[];
}
} // module raw
@@ -166,7 +168,7 @@ declare namespace lf {
interface ITable {
as(name: string): Table;
createRow(value: Object): Row;
createRow(value: object): Row;
getName(): string;
}
+9 -3
View File
@@ -1,4 +1,10 @@
import lf = require("lovefield");
export interface IRow {
id: number;
description: string;
deadline: Date;
done: boolean;
}
function main(): void {
const schemaBuilder: lf.schema.Builder = lf.schema.create('todo', 1);
@@ -28,11 +34,11 @@ function main(): void {
});
return db.insertOrReplace().into(itemSchema).values([row]).exec();
}).then(() => {
const column = itemSchema['done'];
return todoDb.select().from(itemSchema).where(column.eq(false)).exec();
const column = itemSchema.done;
return todoDb.select().from(itemSchema).where(column.eq(false)).exec() as Promise<IRow[]>;
}).then((results) => {
results.forEach((row) => {
document.body.textContent = `${(row as any).description} before ${(row as any).deadline}`;
document.body.textContent = `${row.description} before ${row.deadline}`;
});
return todoDb.delete().from(itemSchema);
+1 -1
View File
@@ -11,7 +11,7 @@
* @param {(string | Buffer)} message - a string or buffer to hash
* @returns {string} the resultant MD5 hash of the given message
*/
declare function md5(message: string | Buffer): string;
declare function md5(message: string | Buffer | Array<number>): string;
declare namespace md5 {}
+8 -5
View File
@@ -1,4 +1,3 @@
import fs = require("fs");
import md5 = require("md5");
/**
* API
@@ -24,8 +23,12 @@ import md5 = require("md5");
* }); *
* **************************************************
*/
console.log(md5('message')); // should print 78e731027d8fd50ed642340b7c9a63b3
const message = 'message';
fs.readFile('md5.d.ts', function(err: Error, buf: Buffer) {
console.log(md5(buf));
});
console.log(md5(message)); // should print 78e731027d8fd50ed642340b7c9a63b3
const array = new Array<number>(message.length);
for (let i = 0; i < message.length; ++i)
array[i] = message.charCodeAt(i);
const buffer = new Buffer(array);
console.log(md5(buffer)); // Should be same result as above.
+9 -3
View File
@@ -697,7 +697,9 @@ declare module "mongoose" {
| "findOne"
| "findOneAndRemove"
| "findOneAndUpdate"
| "update",
| "update"
| "updateOne"
| "updateMany",
fn: HookSyncCallback<T>,
errorCb?: HookErrorCallback
): this;
@@ -730,7 +732,9 @@ declare module "mongoose" {
| "findOne"
| "findOneAndRemove"
| "findOneAndUpdate"
| "update",
| "update"
| "updateOne"
| "updateMany",
parallel: boolean,
fn: HookAsyncCallback<T>,
errorCb?: HookErrorCallback
@@ -2701,6 +2705,7 @@ declare module "mongoose" {
* Triggers the save() hook.
*/
create(docs: any[], callback?: (err: any, res: T[]) => void): Promise<T[]>;
create(docs: any[], options?: SaveOptions, callback?: (err: any, res: T[]) => void): Promise<T[]>;
create(...docs: any[]): Promise<T>;
create(...docsWithCallback: any[]): Promise<T>;
@@ -2988,6 +2993,7 @@ declare module "mongoose" {
interface SaveOptions {
safe?: boolean | WriteConcern;
validateBeforeSave?: boolean;
session?: ClientSession;
}
interface WriteConcern {
@@ -3030,7 +3036,7 @@ declare module "mongoose" {
interface ModelOptions {
session?: ClientSession | null;
}
interface ModelFindByIdAndUpdateOptions extends ModelOptions {
/** true to return the modified document rather than the original. defaults to false */
new?: boolean;
+27 -1
View File
@@ -1960,4 +1960,30 @@ db.createCollection('users').
]).session(session).exec()).
then((res: any) => {
session.commitTransaction();
});
});
/** https://mongoosejs.com/docs/transactions.html */
const Customer = db.model('Customer', new mongoose.Schema({ name: String }));
db.createCollection('customers').
then(() => db.startSession()).
then(_session => {
session = _session;
// Start a transaction
session.startTransaction();
// This `create()` is part of the transaction because of the `session`
// option.
return Customer.create([{ name: 'Test' }], { session: session });
}).
// Transactions execute in isolation, so unless you pass a `session`
// to `findOne()` you won't see the document until the transaction
// is committed.
then((customer: mongoose.Document[]) => Customer.findOne({ name: 'Test' }).exec()).
// This `findOne()` will return the doc, because passing the `session`
// means this `findOne()` will run as part of the transaction.
then(() => Customer.findOne({ name: 'Test' }).session(session).exec()).
// Once the transaction is committed, the write operation becomes
// visible outside of the transaction.
then(() => session.commitTransaction()).
then(() => Customer.findOne({ name: 'Test' }).exec())
+135 -36
View File
@@ -1,4 +1,4 @@
// Type definitions for Node.js 10.9.x
// Type definitions for Node.js 10.10.x
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <http://typescriptlang.org>
// DefinitelyTyped <https://github.com/DefinitelyTyped/DefinitelyTyped>
@@ -795,6 +795,14 @@ declare namespace NodeJS {
disconnect(): void;
connected: boolean;
/**
* The `process.allowedNodeEnvironmentFlags` property is a special,
* read-only `Set` of flags allowable within the [`NODE_OPTIONS`][]
* environment variable.
*/
// TODO: This Set is readonly
allowedNodeEnvironmentFlags: Set<string>;
/**
* EventEmitter
* 1. beforeExit
@@ -1088,6 +1096,7 @@ declare module "http" {
'pragma'?: string;
'proxy-authenticate'?: string;
'public-key-pins'?: string;
'referer'?: string;
'retry-after'?: string;
'set-cookie'?: string[];
'strict-transport-security'?: string;
@@ -1737,8 +1746,8 @@ declare module "os" {
export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] };
export function homedir(): string;
export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string };
export var constants: {
UV_UDP_REUSEADDR: number,
export const constants: {
UV_UDP_REUSEADDR: number;
signals: {
SIGHUP: number;
SIGINT: number;
@@ -1774,7 +1783,7 @@ declare module "os" {
SIGPWR: number;
SIGSYS: number;
SIGUNUSED: number;
},
};
errno: {
E2BIG: number;
EACCES: number;
@@ -1855,13 +1864,36 @@ declare module "os" {
ETXTBSY: number;
EWOULDBLOCK: number;
EXDEV: number;
},
};
priority: {
PRIORITY_LOW: number;
PRIORITY_BELOW_NORMAL: number;
PRIORITY_NORMAL: number;
PRIORITY_ABOVE_NORMAL: number;
PRIORITY_HIGH: number;
PRIORITY_HIGHEST: number;
}
};
export function arch(): string;
export function platform(): NodeJS.Platform;
export function tmpdir(): string;
export const EOL: string;
export function endianness(): "BE" | "LE";
/**
* Gets the priority of a process.
* Defaults to current process.
*/
export function getPriority(pid?: number): number;
/**
* Sets the priority of the current process.
* @param priority Must be in range of -20 to 19
*/
export function setPriority(priority: number): void;
/**
* Sets the priority of the process specified process.
* @param priority Must be in range of -20 to 19
*/
export function setPriority(pid: number, priority: number): void;
}
declare module "https" {
@@ -2097,22 +2129,53 @@ declare module "readline" {
declare module "vm" {
export interface Context { }
export interface ScriptOptions {
export interface BaseOptions {
/**
* Specifies the filename used in stack traces produced by this script.
* Default: `''`.
*/
filename?: string;
/**
* Specifies the line number offset that is displayed in stack traces produced by this script.
* Default: `0`.
*/
lineOffset?: number;
/**
* Specifies the column number offset that is displayed in stack traces produced by this script.
* Default: `0`
*/
columnOffset?: number;
}
export interface ScriptOptions extends BaseOptions {
displayErrors?: boolean;
timeout?: number;
cachedData?: Buffer;
produceCachedData?: boolean;
}
export interface RunningScriptOptions {
filename?: string;
lineOffset?: number;
columnOffset?: number;
export interface RunningScriptOptions extends BaseOptions {
displayErrors?: boolean;
timeout?: number;
}
export interface CompileFunctionOptions extends BaseOptions {
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: Buffer;
/**
* Specifies whether to produce new cache data.
* Default: `false`,
*/
produceCachedData?: boolean;
/**
* The sandbox/context in which the said function should be compiled in.
*/
parsingContext?: Context;
/**
* An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling
*/
contextExtensions?: Object[];
}
export class Script {
constructor(code: string, options?: ScriptOptions);
runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any;
@@ -2126,6 +2189,7 @@ declare module "vm" {
export function runInDebugContext(code: string): any;
export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any;
export function runInThisContext(code: string, options?: RunningScriptOptions | string): any;
export function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function;
}
declare module "child_process" {
@@ -2360,7 +2424,7 @@ declare module "child_process" {
export interface SpawnSyncOptions {
argv0?: string; // Not specified in the docs
cwd?: string;
input?: string | Buffer | Uint8Array;
input?: string | Buffer | NodeJS.TypedArray | DataView;
stdio?: StdioOptions;
env?: NodeJS.ProcessEnv;
uid?: number;
@@ -2423,7 +2487,7 @@ declare module "child_process" {
export interface ExecFileSyncOptions {
cwd?: string;
input?: string | Buffer | Uint8Array;
input?: string | Buffer | NodeJS.TypedArray | DataView;
stdio?: StdioOptions;
env?: NodeJS.ProcessEnv;
uid?: number;
@@ -3189,6 +3253,7 @@ declare module "fs" {
*/
export type PathLike = string | Buffer | URL;
export type BinaryData = Buffer | DataView | NodeJS.TypedArray;
export class Stats {
isFile(): boolean;
isDirectory(): boolean;
@@ -3217,6 +3282,17 @@ declare module "fs" {
birthtime: Date;
}
export class Dirent {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
name: string;
}
export interface FSWatcher extends events.EventEmitter {
close(): void;
@@ -3964,21 +4040,21 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: PathLike, options: { encoding: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void;
export function readdir(path: PathLike, options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void;
export function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void;
export function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
@@ -3986,6 +4062,13 @@ declare module "fs" {
*/
export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
*/
export function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void;
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
export namespace readdir {
/**
@@ -3993,21 +4076,28 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): Promise<string[]>;
export function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise<string[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer" }): Promise<Buffer[]>;
export function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise<Buffer[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string[] | Buffer[]>;
export function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise<string[] | Buffer[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options If called with `withFileTypes: true` the result data will be an array of Dirent
*/
export function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise<Dirent[]>;
}
/**
@@ -4015,21 +4105,28 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): string[];
export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer[];
export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): string[] | Buffer[];
export function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[];
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
*/
export function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[];
/**
* Asynchronous close(2) - close a file descriptor.
@@ -4164,7 +4261,7 @@ declare module "fs" {
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
*/
export function write<TBuffer extends Buffer | Uint8Array>(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
export function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
@@ -4172,20 +4269,20 @@ declare module "fs" {
* @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
*/
export function write<TBuffer extends Buffer | Uint8Array>(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
export function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
*/
export function write<TBuffer extends Buffer | Uint8Array>(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
export function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
*/
export function write<TBuffer extends Buffer | Uint8Array>(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
export function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
@@ -4220,7 +4317,7 @@ declare module "fs" {
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
*/
export function __promisify__<TBuffer extends Buffer | Uint8Array>(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>;
export function __promisify__<TBuffer extends BinaryData>(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
@@ -4239,7 +4336,7 @@ declare module "fs" {
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
*/
export function writeSync(fd: number, buffer: Buffer | Uint8Array, offset?: number | null, length?: number | null, position?: number | null): number;
export function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number;
/**
* Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written.
@@ -4258,7 +4355,7 @@ declare module "fs" {
* @param length The number of bytes to read.
* @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position.
*/
export function read<TBuffer extends Buffer | Uint8Array>(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;
export function read<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
export namespace read {
@@ -4269,7 +4366,7 @@ declare module "fs" {
* @param length The number of bytes to read.
* @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position.
*/
export function __promisify__<TBuffer extends Buffer | Uint8Array>(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>;
export function __promisify__<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>;
}
/**
@@ -4280,7 +4377,7 @@ declare module "fs" {
* @param length The number of bytes to read.
* @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position.
*/
export function readSync(fd: number, buffer: Buffer | Uint8Array, offset: number, length: number, position: number | null): number;
export function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number;
/**
* Asynchronously reads the entire contents of a file.
@@ -4379,6 +4476,8 @@ declare module "fs" {
*/
export function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer;
export type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null;
/**
* Asynchronously writes data to a file, replacing the file if it already exists.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@@ -4391,7 +4490,7 @@ declare module "fs" {
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'w'` is used.
*/
export function writeFile(path: PathLike | number, data: any, options: { encoding?: string | null; mode?: number | string; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void;
export function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void;
/**
* Asynchronously writes data to a file, replacing the file if it already exists.
@@ -4416,7 +4515,7 @@ declare module "fs" {
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'w'` is used.
*/
export function __promisify__(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): Promise<void>;
export function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise<void>;
}
/**
@@ -4431,7 +4530,7 @@ declare module "fs" {
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'w'` is used.
*/
export function writeFileSync(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void;
export function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void;
/**
* Asynchronously append data to a file, creating the file if it does not exist.
@@ -4445,7 +4544,7 @@ declare module "fs" {
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'a'` is used.
*/
export function appendFile(file: PathLike | number, data: any, options: { encoding?: string | null, mode?: string | number, flag?: string } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void;
export function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void;
/**
* Asynchronously append data to a file, creating the file if it does not exist.
@@ -4470,7 +4569,7 @@ declare module "fs" {
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'a'` is used.
*/
export function __promisify__(file: PathLike | number, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string } | string | null): Promise<void>;
export function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise<void>;
}
/**
@@ -4485,7 +4584,7 @@ declare module "fs" {
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'a'` is used.
*/
export function appendFileSync(file: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void;
export function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void;
/**
* Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed.
+45 -2
View File
@@ -186,6 +186,7 @@ namespace fs_tests {
fs.writeFileSync("testfile", "content", "utf8");
fs.writeFileSync("testfile", "content", { encoding: "utf8" });
fs.writeFileSync("testfile", new DataView(new ArrayBuffer(1)), { encoding: "utf8" });
}
{
@@ -229,6 +230,14 @@ namespace fs_tests {
fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data);
}
{
fs.read(1, new DataView(new ArrayBuffer(1)), 0, 1, 0, (err: NodeJS.ErrnoException, bytesRead: number, buffer: DataView) => {});
}
{
fs.readSync(1, new DataView(new ArrayBuffer(1)), 0, 1, 0);
}
{
var errno: number;
fs.readFile('testfile', (err, data) => {
@@ -247,6 +256,8 @@ namespace fs_tests {
listS = fs.readdirSync('path', 'utf8');
listS = fs.readdirSync('path', null);
listS = fs.readdirSync('path', undefined);
const listDir: fs.Dirent[] = fs.readdirSync('path', { withFileTypes: true });
const listDir2: Buffer[] = fs.readdirSync('path', { withFileTypes: false, encoding: 'buffer' });
let listB: Buffer[];
listB = fs.readdirSync('path', { encoding: 'buffer' });
@@ -255,8 +266,9 @@ namespace fs_tests {
let enc = 'buffer';
fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[]
fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[]
}
fs.readdir('path', { withFileTypes: true }, (err: NodeJS.ErrnoException, files: fs.Dirent[]) => {});
}
{
fs.mkdtemp('/tmp/foo-', (err, folder) => {
console.log(folder);
@@ -864,7 +876,7 @@ namespace util_tests {
var arg0NoResult: () => Promise<any> = util.promisify((cb: (err: Error) => void): void => { });
var arg1: (arg: string) => Promise<number> = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { });
var arg1NoResult: (arg: string) => Promise<any> = util.promisify((arg: string, cb: (err: Error) => void): void => { });
var cbOptionalError: () => Promise<void> = util.promisify((cb: (err?: Error | null) => void): void => { cb(); });
var cbOptionalError: () => Promise<void | {}> = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); // tslint:disable-line void-return
assert(typeof util.promisify.custom === 'symbol');
// util.deprecate
const foo = () => {};
@@ -2421,6 +2433,8 @@ namespace child_process_tests {
childProcess.spawnSync("echo test");
childProcess.spawnSync("echo test", {windowsVerbatimArguments: false});
childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"});
childProcess.spawnSync("echo test", {input: new Uint8Array([])});
childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))});
}
{
@@ -2433,6 +2447,11 @@ namespace child_process_tests {
childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); });
}
{
childProcess.execFileSync("echo test", {input: new Uint8Array([])});
childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))});
}
async function testPromisify() {
const execFile = util.promisify(childProcess.execFile);
let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm");
@@ -2868,6 +2887,16 @@ namespace os_tests {
result = os.constants.errno.EWOULDBLOCK;
result = os.constants.errno.EXDEV;
}
{
const prio = os.getPriority();
os.setPriority(prio + 1);
const prio2 = os.getPriority(1);
os.setPriority(2, prio + 1);
os.setPriority(os.constants.priority.PRIORITY_LOW);
}
}
////////////////////////////////////////////////////
@@ -2921,6 +2950,17 @@ namespace vm_tests {
{
vm.runInThisContext('console.log("hello world"', './my-file.js');
}
{
const fn: Function = vm.compileFunction('console.log("test")', [], {
parsingContext: vm.createContext(),
contextExtensions: [{
a: 1,
}],
produceCachedData: false,
cachedData: Buffer.from('nope'),
});
}
}
/////////////////////////////////////////////////////
@@ -3036,6 +3076,9 @@ namespace process_tests {
process.setUncaughtExceptionCaptureCallback(null);
const b: boolean = process.hasUncaughtExceptionCaptureCallback();
}
{
process.allowedNodeEnvironmentFlags.has('asdf');
}
}
///////////////////////////////////////////////////////////
+2 -1
View File
@@ -50,7 +50,8 @@ export const UNIT_SEP: string;
export const WORKERS_SUPPORTED: boolean;
// The relative path to Papa Parse. This is automatically detected when Papa Parse is loaded synchronously.
export const SCRIPT_PATH: string;
// Assign it a value to override auto-detected path.
export let SCRIPT_PATH: string;
// When passed to Papa Parse a Readable stream is returned.
export const NODE_STREAM_INPUT = 1;
+1 -1
View File
@@ -45,7 +45,7 @@ declare namespace OAuth2Strategy {
tokenURL: string;
clientID: string;
clientSecret: string;
callbackURL: string;
callbackURL?: string;
}
interface StrategyOptions extends _StrategyOptionsBase {
passReqToCallback?: false;
@@ -33,7 +33,6 @@ function verifyFunction4(_req: Request, _accessToken: string, _refreshToken: str
const strategyOptions2: StrategyOptionsWithRequest = {
authorizationURL: 'http://www.example.com/auth',
callbackURL: 'http://www.example.com/callback',
clientID: 'dummy',
clientSecret: 'secret',
tokenURL: 'http://www.example.com/token',
+209 -58
View File
@@ -1,12 +1,10 @@
// Type definitions for postmark 1.4
// Project: http://wildbit.github.io/postmark.js
// Definitions by: Ben Bayard <https://github.com/benbayard>
// Definitions by: Ben Bayard <https://github.com/benbayard>
// Jinesh Shah <https://github.com/jineshshah36>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export = postmark;
declare const postmark: Postmark.Postmark;
declare namespace Postmark {
const defaults: Options;
@@ -87,7 +85,9 @@ declare namespace Postmark {
InlineCssForHtmlTestRender?: boolean;
}
type PostmarkCallback<T extends object = any> = ((e: PostmarkError, ret: T) => undefined) | undefined;
type PostmarkCallback<T extends object = any> =
| ((e: PostmarkError, ret: T) => undefined)
| undefined;
interface SimpleOptions {
ssl: boolean;
@@ -109,36 +109,64 @@ declare namespace Postmark {
constructor(serverKey: string, options?: Partial<Options>);
send(message: PostmarkMessage): Promise<SendStatus>;
send(message: PostmarkMessage, callback: PostmarkCallback<SendStatus>): undefined;
send(
message: PostmarkMessage,
callback: PostmarkCallback<SendStatus>
): undefined;
sendEmailWithTemplate(message: PostmarkMessageWithTemplate): Promise<SendStatus>;
sendEmailWithTemplate(message: PostmarkMessageWithTemplate, callback: PostmarkCallback<SendStatus>): undefined;
sendEmailWithTemplate(
message: PostmarkMessageWithTemplate
): Promise<SendStatus>;
sendEmailWithTemplate(
message: PostmarkMessageWithTemplate,
callback: PostmarkCallback<SendStatus>
): undefined;
batch(message: PostmarkMessage[]): Promise<SendStatus[]>;
batch(message: PostmarkMessage[], callback: PostmarkCallback<SendStatus[]>): undefined;
batch(
message: PostmarkMessage[],
callback: PostmarkCallback<SendStatus[]>
): undefined;
sendEmail(message: PostmarkMessage): Promise<SendStatus>;
sendEmail(message: PostmarkMessage, callback: PostmarkCallback<SendStatus>): undefined;
sendEmail(
message: PostmarkMessage,
callback: PostmarkCallback<SendStatus>
): undefined;
sendEmailBatch(message: PostmarkMessage[]): Promise<SendStatus[]>;
sendEmailBatch(message: PostmarkMessage[], callback: PostmarkCallback<SendStatus[]>): undefined;
sendEmailBatch(
message: PostmarkMessage[],
callback: PostmarkCallback<SendStatus[]>
): undefined;
// stats
getDeliveryStatistics(): Promise<DeliveryStats>;
getDeliveryStatistics(callback: PostmarkCallback<DeliveryStats>): undefined;
getDeliveryStatistics(
callback: PostmarkCallback<DeliveryStats>
): undefined;
// bounces
getBounces(filter: BounceFilter): Promise<BouncesResult>;
getBounces(filter: BounceFilter, callback?: PostmarkCallback<BouncesResult>): undefined;
getBounces(
filter: BounceFilter,
callback?: PostmarkCallback<BouncesResult>
): undefined;
getBounce(id: number): Promise<Bounce>;
getBounce(id: number, callback?: PostmarkCallback<Bounce>): undefined;
getBounceDump(id: number): Promise<BounceDump>;
getBounceDump(id: number, callback?: PostmarkCallback<BounceDump>): undefined;
getBounceDump(
id: number,
callback?: PostmarkCallback<BounceDump>
): undefined;
activateBounce(id: number): Promise<ActivatedBounceResult>;
activateBounce(id: number, callback?: PostmarkCallback<ActivatedBounceResult>): undefined;
activateBounce(
id: number,
callback?: PostmarkCallback<ActivatedBounceResult>
): undefined;
getBounceTags(): Promise<string[]>;
getBounceTags(callback?: PostmarkCallback<string[]>): undefined;
@@ -148,54 +176,112 @@ declare namespace Postmark {
getServer(callback?: PostmarkCallback<Server>): undefined;
editServer(server: Partial<Server>): Promise<Server>;
editServer(server: Partial<Server>, callback?: PostmarkCallback<Server>): undefined;
editServer(
server: Partial<Server>,
callback?: PostmarkCallback<Server>
): undefined;
// message info
getOutboundMessages(filter: OutboundMessageFilter): Promise<OutboundMessagesResult>;
getOutboundMessages(filter: OutboundMessageFilter, callback?: PostmarkCallback<OutboundMessagesResult>): undefined;
getOutboundMessages(
filter: OutboundMessageFilter
): Promise<OutboundMessagesResult>;
getOutboundMessages(
filter: OutboundMessageFilter,
callback?: PostmarkCallback<OutboundMessagesResult>
): undefined;
getOutboundMessageDetails(id: number): Promise<OutboundMessage>;
getOutboundMessageDetails(id: number, callback?: PostmarkCallback<OutboundMessage>): undefined;
getOutboundMessageDetails(
id: number,
callback?: PostmarkCallback<OutboundMessage>
): undefined;
getMessageOpens(filter: OpenMessageFilter): Promise<MessageOpensResult>;
getMessageOpens(filter: OpenMessageFilter, callback?: PostmarkCallback<MessageOpensResult>): undefined;
getMessageOpens(
filter: OpenMessageFilter,
callback?: PostmarkCallback<MessageOpensResult>
): undefined;
getMessageOpensForSingleMessage(id: number, filter: Filter): Promise<MessageOpensResult>;
getMessageOpensForSingleMessage(id: number, filter: Filter, callback?: PostmarkCallback<MessageOpensResult>): undefined;
getMessageOpensForSingleMessage(
id: number,
filter: Filter
): Promise<MessageOpensResult>;
getMessageOpensForSingleMessage(
id: number,
filter: Filter,
callback?: PostmarkCallback<MessageOpensResult>
): undefined;
getInboundMessages(filter: InboundMessageFilter): Promise<InboundMessagesResult>;
getInboundMessages(filter: InboundMessageFilter, callback?: PostmarkCallback<InboundMessagesResult>): undefined;
getInboundMessages(
filter: InboundMessageFilter
): Promise<InboundMessagesResult>;
getInboundMessages(
filter: InboundMessageFilter,
callback?: PostmarkCallback<InboundMessagesResult>
): undefined;
getInboundMessageDetails(id: number): Promise<InboundMessage>;
getInboundMessageDetails(id: number, callback?: PostmarkCallback<InboundMessage>): undefined;
getInboundMessageDetails(
id: number,
callback?: PostmarkCallback<InboundMessage>
): undefined;
bypassBlockedInboundMessage(id: number): Promise<GenericResult>;
bypassBlockedInboundMessage(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
bypassBlockedInboundMessage(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
getOuboundOverview(filter: BaseFilter): Promise<OutboundOverview>;
getOuboundOverview(filter: BaseFilter, callback?: PostmarkCallback<OutboundOverview>): undefined;
getOuboundOverview(
filter: BaseFilter,
callback?: PostmarkCallback<OutboundOverview>
): undefined;
retryInboundHookForMessage(id: number): Promise<GenericResult>;
retryInboundHookForMessage(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
retryInboundHookForMessage(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
// templates
getTemplate(id: number): Promise<Template>;
getTemplate(id: number, callback?: PostmarkCallback<Template>): undefined;
getTemplate(
id: number,
callback?: PostmarkCallback<Template>
): undefined;
createTemplate(template: Partial<Template>): Promise<TemplateBase>;
createTemplate(template: Partial<Template>, callback?: PostmarkCallback<TemplateBase>): undefined;
createTemplate(
template: Partial<Template>,
callback?: PostmarkCallback<TemplateBase>
): undefined;
editTemplate(template: Partial<Template>): Promise<TemplateBase>;
editTemplate(template: Partial<Template>, callback?: PostmarkCallback<TemplateBase>): undefined;
editTemplate(
template: Partial<Template>,
callback?: PostmarkCallback<TemplateBase>
): undefined;
getTemplates(filter: Filter): Promise<TemplatesResult>;
getTemplates(filter: Filter, callback?: PostmarkCallback<TemplatesResult>): undefined;
getTemplates(
filter: Filter,
callback?: PostmarkCallback<TemplatesResult>
): undefined;
deleteTemplate(id: number): Promise<GenericResult>;
deleteTemplate(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
deleteTemplate(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
validateTemplate<T extends object>(templateObject: TemplateValidator<T>): Promise<TemplateValidationResult<T>>;
validateTemplate<T extends object>(templateObject: TemplateValidator<T>, callback?: PostmarkCallback<TemplateValidationResult<T>>): undefined;
validateTemplate<T extends object>(
templateObject: TemplateValidator<T>
): Promise<TemplateValidationResult<T>>;
validateTemplate<T extends object>(
templateObject: TemplateValidator<T>,
callback?: PostmarkCallback<TemplateValidationResult<T>>
): undefined;
}
interface CreateSignature extends UpdateSignature {
@@ -227,71 +313,130 @@ declare namespace Postmark {
class AdminClient {
constructor(apiKey: string, options: Partial<Options>);
listSenderSignatures(query: Filter): Promise<SenderSignaturesResults>;
listSenderSignatures(query: Filter, callback?: PostmarkCallback<SenderSignaturesResults>): undefined;
listSenderSignatures(
query: Filter,
callback?: PostmarkCallback<SenderSignaturesResults>
): undefined;
createSenderSignature(options: CreateSignature): Promise<SenderSignature>;
createSenderSignature(options: CreateSignature, callback?: PostmarkCallback<SenderSignature>): undefined;
createSenderSignature(
options: CreateSignature
): Promise<SenderSignature>;
createSenderSignature(
options: CreateSignature,
callback?: PostmarkCallback<SenderSignature>
): undefined;
editSenderSignature(id: number, options: UpdateSignature): Promise<SenderSignature>;
editSenderSignature(id: number, options: UpdateSignature, callback?: PostmarkCallback<SenderSignature>): undefined;
editSenderSignature(
id: number,
options: UpdateSignature
): Promise<SenderSignature>;
editSenderSignature(
id: number,
options: UpdateSignature,
callback?: PostmarkCallback<SenderSignature>
): undefined;
deleteSenderSignature(id: number): Promise<GenericResult>;
deleteSenderSignature(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
deleteSenderSignature(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
resendSenderSignatureConfirmation(id: number): Promise<GenericResult>;
resendSenderSignatureConfirmation(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
resendSenderSignatureConfirmation(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
verifySenderSignatureSPF(id: number): Promise<SenderSignature>;
verifySenderSignatureSPF(id: number, callback?: PostmarkCallback<SenderSignature>): undefined;
verifySenderSignatureSPF(
id: number,
callback?: PostmarkCallback<SenderSignature>
): undefined;
requestNewDKIMForSenderSignature(id: number): Promise<GenericResult>;
requestNewDKIMForSenderSignature(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
requestNewDKIMForSenderSignature(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
// servers
getServer(id: number): Promise<Server>;
getServer(id: number, callback?: PostmarkCallback<Server>): undefined;
createServer(options: CreateServer): Promise<Server>;
createServer(options: CreateServer, callback?: PostmarkCallback<Server>): undefined;
createServer(
options: CreateServer,
callback?: PostmarkCallback<Server>
): undefined;
editServer(id: number, options: Partial<CreateServer>): Promise<Server>;
editServer(id: number, options: Partial<CreateServer>, callback?: PostmarkCallback<Server>): undefined;
editServer(
id: number,
options: Partial<CreateServer>,
callback?: PostmarkCallback<Server>
): undefined;
deleteServer(id: number): Promise<GenericResult>;
deleteServer(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
deleteServer(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
listServers(query: ServerFilter): Promise<ServersResult>;
listServers(query: ServerFilter, callback?: PostmarkCallback<ServersResult>): undefined;
listServers(
query: ServerFilter,
callback?: PostmarkCallback<ServersResult>
): undefined;
// domains
listDomains(query: Filter): Promise<DomainsResult>;
listDomains(query: Filter, callback?: PostmarkCallback<DomainsResult>): undefined;
listDomains(
query: Filter,
callback?: PostmarkCallback<DomainsResult>
): undefined;
getDomain(id: number): Promise<Domain>;
getDomain(id: number, callback?: PostmarkCallback<Domain>): undefined;
createDomain(options: CreateDomain): Promise<Domain>;
createDomain(options: CreateDomain, callback?: PostmarkCallback<Domain>): undefined;
createDomain(
options: CreateDomain,
callback?: PostmarkCallback<Domain>
): undefined;
editDomain(id: number, options: Partial<CreateDomain>): Promise<Domain>;
editDomain(id: number, options: Partial<CreateDomain>, callback?: PostmarkCallback<Domain>): undefined;
editDomain(
id: number,
options: Partial<CreateDomain>,
callback?: PostmarkCallback<Domain>
): undefined;
deleteDomain(id: number): Promise<GenericResult>;
deleteDomain(id: number, callback?: PostmarkCallback<GenericResult>): undefined;
deleteDomain(
id: number,
callback?: PostmarkCallback<GenericResult>
): undefined;
verifyDomainSPF(id: number): Promise<SenderSignature>;
verifyDomainSPF(id: number, callback?: PostmarkCallback<SenderSignature>): undefined;
verifyDomainSPF(
id: number,
callback?: PostmarkCallback<SenderSignature>
): undefined;
rotateDKIMForDomain(id: number): Promise<RotateDKIMResult>;
rotateDKIMForDomain(id: number, callback?: PostmarkCallback<RotateDKIMResult>): undefined;
rotateDKIMForDomain(
id: number,
callback?: PostmarkCallback<RotateDKIMResult>
): undefined;
}
interface ClientClass {
new(serverKey: string, options: Partial<Options>): Client;
new (serverKey: string, options: Partial<Options>): Client;
}
interface AdminClientClass {
new(apiKey: string, options: Partial<Options>): AdminClient;
new (apiKey: string, options: Partial<Options>): AdminClient;
}
interface Postmark {
@@ -637,8 +782,7 @@ declare namespace Postmark {
ReturnPathDomainVerified: boolean;
}
interface Domain extends DomainBase, VerificationDetails {
}
interface Domain extends DomainBase, VerificationDetails {}
interface RotateDKIMResult extends DKIMKey {
Name: string;
@@ -666,3 +810,10 @@ declare namespace Postmark {
WithReadTimeRecorded: number;
}
}
declare function Postmark(
apiKey: string,
options: Partial<Postmark.Options>
): Postmark.Client;
export = Postmark;
+62 -58
View File
@@ -1,20 +1,22 @@
import postmark = require('postmark');
import * as postmark from "postmark";
declare var options: typeof postmark.defaults;
const message = { To: 'me', From: 'you' };
const templateMessage = {...message, TemplateId: '1'};
declare const options: typeof postmark.defaults;
const message = { To: "me", From: "you" };
const templateMessage = { ...message, TemplateId: "1" };
const filter = { offset: 0 };
const editSender = { Color: 'black' };
const editSender = { Color: "black" };
const templateValidator = {
Subject: '123',
HtmlBody: '123345',
TextBody: '123535',
Subject: "123",
HtmlBody: "123345",
TextBody: "123535"
};
declare const error: postmark.PostmarkError;
declare function callback(err: any, data: any): undefined;
const client = new postmark.Client('124345', options);
const adminClient = new postmark.AdminClient('1123235', options);
const client = new postmark.Client("124345", options);
const adminClient = new postmark.AdminClient("1123235", options);
client.send(message, callback);
client.sendEmailWithTemplate(templateMessage, callback);
@@ -40,66 +42,68 @@ client.retryInboundHookForMessage(1, callback);
client.getOuboundOverview(filter, callback);
client.validateTemplate(templateValidator, callback);
client.send(message).then(() => { });
client.sendEmailWithTemplate(templateMessage).then(() => { });
client.batch([message, message]).then(() => { });
client.sendEmail(message).then(() => { });
client.sendEmailBatch([message, message]).then(() => { });
client.getDeliveryStatistics().then(() => { });
client.getBounces(filter).then(() => { });
client.getBounce(1).then(() => { });
client.getBounceDump(1).then(() => { });
client.activateBounce(1).then(() => { });
client.getBounceTags().then(() => { });
client.getServer().then(() => { });
client.editServer(editSender).then(() => { });
client.getOutboundMessages(filter).then(() => { });
client.getOutboundMessageDetails(1).then(() => { });
client.getMessageOpens(filter).then(() => { });
client.getMessageOpensForSingleMessage(1, filter).then(() => { });
client.getInboundMessages(filter).then(() => { });
client.getInboundMessageDetails(1).then(() => { });
client.bypassBlockedInboundMessage(1).then(() => { });
client.retryInboundHookForMessage(1).then(() => { });
client.getOuboundOverview(filter).then(() => { });
client.validateTemplate(templateValidator).then(() => { });
client.send(message).then(() => {});
client.sendEmailWithTemplate(templateMessage).then(() => {});
client.batch([message, message]).then(() => {});
client.sendEmail(message).then(() => {});
client.sendEmailBatch([message, message]).then(() => {});
client.getDeliveryStatistics().then(() => {});
client.getBounces(filter).then(() => {});
client.getBounce(1).then(() => {});
client.getBounceDump(1).then(() => {});
client.activateBounce(1).then(() => {});
client.getBounceTags().then(() => {});
client.getServer().then(() => {});
client.editServer(editSender).then(() => {});
client.getOutboundMessages(filter).then(() => {});
client.getOutboundMessageDetails(1).then(() => {});
client.getMessageOpens(filter).then(() => {});
client.getMessageOpensForSingleMessage(1, filter).then(() => {});
client.getInboundMessages(filter).then(() => {});
client.getInboundMessageDetails(1).then(() => {});
client.bypassBlockedInboundMessage(1).then(() => {});
client.retryInboundHookForMessage(1).then(() => {});
client.getOuboundOverview(filter).then(() => {});
client.validateTemplate(templateValidator).then(() => {});
adminClient.listSenderSignatures(filter, callback);
adminClient.createSenderSignature({FromEmail: '', Name: ''}, callback);
adminClient.editSenderSignature(0, {Name: '123'}, callback);
adminClient.createSenderSignature({ FromEmail: "", Name: "" }, callback);
adminClient.editSenderSignature(0, { Name: "123" }, callback);
adminClient.deleteSenderSignature(0, callback);
adminClient.resendSenderSignatureConfirmation(0, callback);
adminClient.verifySenderSignatureSPF(0, callback);
adminClient.requestNewDKIMForSenderSignature(0, callback);
adminClient.getServer(0, callback);
adminClient.createServer({Name: '123'}, callback);
adminClient.editServer(0, {Name: 'black'}, callback);
adminClient.createServer({ Name: "123" }, callback);
adminClient.editServer(0, { Name: "black" }, callback);
adminClient.deleteServer(0, callback);
adminClient.listServers(filter, callback);
adminClient.listDomains(filter, callback);
adminClient.getDomain(0, callback);
adminClient.createDomain({Name: '1234'}, callback);
adminClient.editDomain(0, {ReturnPathDomain: '/'}, callback);
adminClient.createDomain({ Name: "1234" }, callback);
adminClient.editDomain(0, { ReturnPathDomain: "/" }, callback);
adminClient.deleteDomain(0, callback);
adminClient.verifyDomainSPF(0, callback);
adminClient.rotateDKIMForDomain(0, callback);
adminClient.listSenderSignatures(filter).then(() => { });
adminClient.createSenderSignature({ FromEmail: '', Name: '' }).then(() => { });
adminClient.editSenderSignature(0, { Name: 'somename', ReplyToEmail: '123' }).then(() => { });
adminClient.deleteSenderSignature(0).then(() => { });
adminClient.resendSenderSignatureConfirmation(0).then(() => { });
adminClient.verifySenderSignatureSPF(0).then(() => { });
adminClient.requestNewDKIMForSenderSignature(0).then(() => { });
adminClient.getServer(0).then(() => { });
adminClient.createServer({ Name: '123' }).then(() => { });
adminClient.editServer(0, { Name: 'black' }).then(() => { });
adminClient.deleteServer(0).then(() => { });
adminClient.listServers(filter).then(() => { });
adminClient.listDomains(filter).then(() => { });
adminClient.getDomain(0).then(() => { });
adminClient.createDomain({ Name: '1234' }).then(() => { });
adminClient.editDomain(0, { ReturnPathDomain: '/' }).then(() => { });
adminClient.deleteDomain(0).then(() => { });
adminClient.verifyDomainSPF(0).then(() => { });
adminClient.rotateDKIMForDomain(0).then(() => { });
adminClient.listSenderSignatures(filter).then(() => {});
adminClient.createSenderSignature({ FromEmail: "", Name: "" }).then(() => {});
adminClient
.editSenderSignature(0, { Name: "somename", ReplyToEmail: "123" })
.then(() => {});
adminClient.deleteSenderSignature(0).then(() => {});
adminClient.resendSenderSignatureConfirmation(0).then(() => {});
adminClient.verifySenderSignatureSPF(0).then(() => {});
adminClient.requestNewDKIMForSenderSignature(0).then(() => {});
adminClient.getServer(0).then(() => {});
adminClient.createServer({ Name: "123" }).then(() => {});
adminClient.editServer(0, { Name: "black" }).then(() => {});
adminClient.deleteServer(0).then(() => {});
adminClient.listServers(filter).then(() => {});
adminClient.listDomains(filter).then(() => {});
adminClient.getDomain(0).then(() => {});
adminClient.createDomain({ Name: "1234" }).then(() => {});
adminClient.editDomain(0, { ReturnPathDomain: "/" }).then(() => {});
adminClient.deleteDomain(0).then(() => {});
adminClient.verifyDomainSPF(0).then(() => {});
adminClient.rotateDKIMForDomain(0).then(() => {});
+6 -13
View File
@@ -1,23 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"strictFunctionTypes": true
},
"files": [
"index.d.ts",
"postmark-tests.ts"
]
}
"files": ["index.d.ts", "postmark-tests.ts"]
}
+1 -6
View File
@@ -1,6 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-unnecessary-generics": false
}
}
{ "extends": "dtslint/dt.json" }
+2 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for react-vertical-timeline-component 2.1
// Type definitions for react-vertical-timeline-component 2.2
// Project: https://github.com/stephane-monnot/react-vertical-timeline
// Definitions by: Stéphane Monnot <https://github.com/stephane-monnot>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -20,6 +20,7 @@ export interface VerticalTimelineElementProps {
icon?: React.ReactNode;
position?: string;
style?: React.CSSProperties;
visibilitySensorProps?: any;
}
export class VerticalTimeline extends React.Component<VerticalTimelineProps> { }
+227
View File
@@ -0,0 +1,227 @@
// Type definitions for web-push 3.3
// Project: https://github.com/web-push-libs/web-push
// Definitions by: Paul Lessing <https://github.com/paullessing>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <reference types="node" />
/**
* To send a push notification call this method with a subscription, optional payload and any options.
*
* Note: you don't need to define a payload, and this method will work without a GCM API Key and / or VAPID keys if the push service supports it.
*
* @param subscription The PushSubscription you wish to send the notification to.
* @param payload The payload you wish to send to the the user.
* @param options Options for the GCM API key and vapid keys can be passed in if they are unique for each notification you wish to send.
*
* @throws WebPushError if the upstream push endpoint returns a non-200 status code.
* @returns This method returns a Promise which resolves if the sending of the notification was successful, otherwise it rejects.
*
* @see SendResult
* @see WebPushError
* @see https://github.com/web-push-libs/web-push#sendnotificationpushsubscription-payload-options
*/
export function sendNotification(subscription: PushSubscription, payload?: string | Buffer | null, options?: RequestOptions): Promise<SendResult>;
/**
* Generate VAPID keys.
*
* @returns Returns an object with publicKey and privateKey values which are URL Safe Base64 encoded strings.
*
* Note: You should create these keys once, store them and use them for all future messages you send.
*/
export function generateVAPIDKeys(): VapidKeys;
/**
* This method expects the GCM API key that is linked to the gcm_sender_id in your web app manifest.
* You can use a GCM API Key from the Google Developer Console or the Cloud Messaging tab under a Firebase Project.
*
* @param apiKey An API key, or null.
*/
export function setGCMAPIKey(apiKey: string | null): void;
/**
* Encrypts the payload according to the Message Encryption for Web Push standard.
*
* (sendNotification will automatically encrypt the payload for you, so if you use sendNotification() you don't need to worry about it).
*
* @param userPublicKey The public key of the receiver (from the browser).
* @param userAuth The auth secret of the receiver (from the browser).
* @param payload The message to attach to the notification.
* @param contentEncoding The type of content encoding to use (e.g. aesgcm or aes128gcm).
*
* @returns This method returns an object with the following fields:
* localPublicKey: The public key matched the private key used during encryption.
* salt: A string representing the salt used to encrypt the payload.
* cipherText: The encrypted payload as a Buffer.
*
* @see ContentEncoding
* @see https://github.com/web-push-libs/web-push#encryptuserpublickey-userauth-payload-contentencoding
*/
export function encrypt(userPublicKey: string, userAuth: string, payload: string | Buffer, contentEncoding: ContentEncoding): EncryptionResult;
/**
* This method takes the required VAPID parameters and returns the required
* header to be added to a Web Push Protocol Request.
* @param audience This must be the origin of the push service.
* @param subject This should be a URL or a 'mailto:' email address.
* @param publicKey The VAPID public key.
* @param privateKey The VAPID private key.
* @param contentEncoding The contentEncoding type.
* @param [expiration] The expiration of the VAPID JWT.
* @returns Returns an Object with the Authorization and 'Crypto-Key' values to be used as headers.
*/
export function getVapidHeaders(
audience: string, subject: string, publicKey: string, privateKey: string, contentEncoding: 'aes128gcm', expiration?: number
): {
Authorization: string;
};
export function getVapidHeaders(
audience: string, subject: string, publicKey: string, privateKey: string, contentEncoding: 'aesgcm', expiration?: number
): {
Authorization: string;
'Crypto-Key': string;
};
export function getVapidHeaders(
audience: string, subject: string, publicKey: string, privateKey: string, contentEncoding: ContentEncoding, expiration?: number
): {
Authorization: string;
'Crypto-Key'?: string;
};
/**
* Note: When calling generateRequestDetails() the payload argument does not need to be defined, passing in null
* will return no body and exclude any unnecessary headers.
* Headers related to the GCM API Key and / or VAPID keys will be included if supplied and required.
*
* @param subscription must be an object containing the details for a push subscription.
* The expected format is the same output as JSON.stringify'ing a PushSubscription in the browser.
* @param payload The payload is optional, but if set, will be encrypted and a Buffer will be returned via the payload parameter.
* This argument must be either a string or a node Buffer.
* Note: In order to encrypt the payload, the pushSubscription must have a keys object with p256dh and auth values.
* @param options Optional argument, none of its parameters are required.
*
* @returns An object containing all the details needed to make a network request.
*
* @see PushSubscription
* @see RequestDetails
* @see https://github.com/web-push-libs/web-push#generaterequestdetailspushsubscription-payload-options
*/
export function generateRequestDetails(subscription: PushSubscription, payload?: null, options?: RequestOptions): RequestDetails & { body: null };
export function generateRequestDetails(subscription: PushSubscription, payload?: string | Buffer, options?: RequestOptions): RequestDetails & { body: Buffer };
export function generateRequestDetails(subscription: PushSubscription, payload?: string | Buffer, options?: RequestOptions): RequestDetails;
/**
* Valid content encodings used by encrypt(), getVapidHeaders(), generateRequestDetails() and sendNotification().
*/
export type ContentEncoding = 'aesgcm' | 'aes128gcm';
/**
* Map of valid content encodings.
*/
export const supportedContentEncodings: {
readonly AES_GCM: 'aesgcm' & ContentEncoding;
readonly AES_128_GCM: 'aws128gcm' & ContentEncoding;
};
/**
* Returned by encrypt() on success.
*/
export interface EncryptionResult {
localPublicKey: string;
salt: string;
cipherText: Buffer;
}
/**
* A private/public key pair for use with VAPID methods.
*/
export interface VapidKeys {
publicKey: string;
privateKey: string;
}
/**
* When making requests where you want to define VAPID details, call this method before sendNotification()
* or pass in the details and options to sendNotification.
*
* @param subject This must be either a URL or a 'mailto:' address.
* For example: 'https://my-site.com/contact' or 'mailto: contact@my-site.com'
* @param publicKey The public VAPID key.
* @param privateKey The private VAPID key.
*/
export function setVapidDetails(subject: string, publicKey: string, privateKey: string): void;
/**
* Configuration for a Push Subscription. This can be obtained on the frontend by calling
* serviceWorkerRegistration.pushManager.subscribe().
* The expected format is the same output as JSON.stringify'ing a PushSubscription in the browser.
*/
export interface PushSubscription {
endpoint: string;
keys: {
p256dh: string;
auth: string;
};
}
export interface Headers {
[header: string]: string;
}
/**
* Options for configuring the outgoing request in generateRequestDetails() or sendNotification().
*/
export interface RequestOptions {
headers?: Headers;
gcmAPIKey?: string; // can be a GCM API key to be used for this request and this request only. This overrides any API key set via setGCMAPIKey().
vapidDetails?: { // should be an object with subject, publicKey and privateKey values defined. These values should follow the VAPID Spec. (https://tools.ietf.org/html/draft-thomson-webpush-vapid)
subject: string;
publicKey: string;
privateKey: string;
};
TTL?: number; // a value in seconds that describes how long a push message is retained by the push service (by default, four weeks).
contentEncoding?: ContentEncoding; // the type of push encoding to use (e.g. 'aesgcm', by default, or 'aes128gcm').
proxy?: string; // proxy hostname/ip and a port to tunnel your requests through (eg. http://< hostname >:< port >).
}
/**
* An object containing all the details needed to make a network request.
* Buffer is null unless a payload was passed into generateRequestDetails().
*/
export interface RequestDetails {
method: 'POST';
headers: Headers;
body: Buffer | null;
endpoint: string;
proxy?: string;
}
/**
* If calling sendNotification() was successful, this result contains the response from the push endpoint.
*/
export interface SendResult {
statusCode: number;
body: string;
headers: Headers;
}
/**
* Error thrown when sendNotification() receives a non-200 status code from the push endpoint.
*/
export class WebPushError extends Error {
readonly message: string;
readonly statusCode: number;
readonly headers: Headers;
readonly body: string;
readonly endpoint: string;
constructor(
message: string,
statusCode: number,
headers: Headers,
body: string,
endpoint: string
);
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"strictFunctionTypes": true,
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"web-push-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+303
View File
@@ -0,0 +1,303 @@
import {
WebPushError,
ContentEncoding,
supportedContentEncodings,
encrypt,
EncryptionResult,
getVapidHeaders,
Headers,
generateVAPIDKeys,
VapidKeys,
setGCMAPIKey,
setVapidDetails,
PushSubscription,
RequestOptions,
RequestDetails,
generateRequestDetails,
SendResult,
sendNotification
} from 'web-push';
declare const anything: any;
// ==============
// WebPushError
// ==============
// $ExpectType WebPushError
const error = new WebPushError('message', 400, {}, 'body', 'endpoint');
// WebPushError extends Error
// $ExpectType string | undefined
error.stack;
// $ExpectType string
error.message;
// $ExpectType string
error.name;
// =================
// ContentEncoding
// =================
// ContentEncoding should only allow named types
// $ExpectError
const notAValidEncoding: ContentEncoding = 'hello world';
// The exported values should match the "enum" type
const aesGcm: ContentEncoding = supportedContentEncodings.AES_GCM;
const aes128Gcm: ContentEncoding = supportedContentEncodings.AES_128_GCM;
// ===========
// encrypt()
// ===========
// $ExpectType EncryptionResult
const encryptionResult = encrypt('publicKey', 'userAuth', 'myPayload', supportedContentEncodings.AES_GCM);
const buffer: Buffer = anything;
// $ExpectType EncryptionResult
encrypt('publicKey', 'userAuth', buffer, supportedContentEncodings.AES_128_GCM);
// Only valid encoding should be allowed
// $ExpectError
encrypt('publicKey', 'userAuth', 'myPayload', 'unknownEncoding');
// $ExpectType string
encryptionResult.localPublicKey;
// $ExpectType string
encryptionResult.salt;
// $ExpectType Buffer
encryptionResult.cipherText;
// ===================
// getVapidHeaders()
// ===================
// $ExpectType { Authorization: string; 'Crypto-Key': string; }
getVapidHeaders('audience', 'subject', 'publicKey', 'privateKey', supportedContentEncodings.AES_GCM, 150);
// $ExpectType { Authorization: string; }
getVapidHeaders('audience', 'subject', 'publicKey', 'privateKey', supportedContentEncodings.AES_128_GCM, 150);
// expiration is optional
// $ExpectType { Authorization: string; 'Crypto-Key': string; }
getVapidHeaders('audience', 'subject', 'publicKey', 'privateKey', supportedContentEncodings.AES_GCM);
// $ExpectType { Authorization: string; }
getVapidHeaders('audience', 'subject', 'publicKey', 'privateKey', supportedContentEncodings.AES_128_GCM);
// Buffers are not supported here
// $ExpectError
getVapidHeaders('audience', buffer, 'publicKey', 'privateKey', supportedContentEncodings.AES_128_GCM);
// $ExpectError
getVapidHeaders('audience', 'subject', buffer, 'privateKey', supportedContentEncodings.AES_128_GCM);
// $ExpectError
getVapidHeaders('audience', 'subject', 'publicKey', buffer, supportedContentEncodings.AES_128_GCM);
// =====================
// generateVAPIDKeys()
// =====================
// $ExpectType VapidKeys
const vapidKeys = generateVAPIDKeys();
// $ExpectType string
vapidKeys.publicKey;
// $ExpectType string
vapidKeys.privateKey;
// ================
// setGCMAPIKey()
// ================
// $ExpectType void
setGCMAPIKey('apiKey');
// $ExpectType void
setGCMAPIKey(null);
// ===================
// setVapidDetails()
// ===================
// $ExpectType void
setVapidDetails('subject', 'privateKey', 'publicKey');
// Buffers are not supported here
// $ExpectError
setVapidDetails(buffer, 'publicKey', 'privateKey');
// $ExpectError
setVapidDetails('subject', buffer, 'privateKey');
// $ExpectError
setVapidDetails('subject', 'publicKey', buffer);
// ==================
// PushSubscription
// ==================
const pushSubscription: PushSubscription = {
endpoint: 'endpointString',
keys: {
p256dh: 'p256dhString',
auth: 'authString',
}
};
// ================
// RequestOptions
// ================
let requestOptions: RequestOptions;
// Can be entirely empty
requestOptions = {};
requestOptions = {
headers: {
someHeader: 'value'
}
};
requestOptions = {
gcmAPIKey: 'key'
};
requestOptions = {
vapidDetails: {
privateKey: 'private',
publicKey: 'public',
subject: 'subject'
}
};
requestOptions = {
TTL: 100
};
requestOptions = {
contentEncoding: supportedContentEncodings.AES_128_GCM
};
requestOptions = {
proxy: 'http://proxy'
};
requestOptions = {
headers: {
someHeader: 'value'
},
gcmAPIKey: 'key',
vapidDetails: {
privateKey: 'private',
publicKey: 'public',
subject: 'subject'
},
TTL: 100,
contentEncoding: supportedContentEncodings.AES_GCM,
proxy: 'http://proxy'
};
// ==========================
// generateRequestDetails()
// ==========================
// $ExpectType RequestDetails & { body: Buffer; }
generateRequestDetails(pushSubscription, 'payload', requestOptions);
// $ExpectType Buffer
generateRequestDetails(pushSubscription, 'payload', requestOptions).body;
// Payload can be a Buffer
// $ExpectType Buffer
generateRequestDetails(pushSubscription, buffer).body;
// $ExpectType Buffer
generateRequestDetails(pushSubscription, buffer, requestOptions).body;
// Payload is optional, then body will be null
// $ExpectType RequestDetails & { body: null; }
generateRequestDetails(pushSubscription);
// $ExpectType null
generateRequestDetails(pushSubscription).body;
// $ExpectType null
generateRequestDetails(pushSubscription, null).body;
// $ExpectType null
generateRequestDetails(pushSubscription, null, requestOptions).body;
// PushSubscription must have all its values
// $ExpectError
generateRequestDetails({});
// $ExpectError
generateRequestDetails({ endpoint: 'endpoint' });
// $ExpectError
generateRequestDetails({ keys: { p256dh: 'p256dh', auth: 'auth' } });
// $ExpectError
generateRequestDetails({ endpoint: null, keys: { p256dh: 'p256dh', auth: 'auth' } });
// $ExpectError
generateRequestDetails({ endpoint: 'endpoint', keys: null });
generateRequestDetails({ endpoint: 'endpoint', keys: { p256dh: 'p256dh', auth: 'auth' } });
// RequestOptions is optional
generateRequestDetails(pushSubscription, 'payload');
generateRequestDetails(pushSubscription, 'payload', {});
// ================
// RequestDetails
// ================
const requestDetails = generateRequestDetails(pushSubscription, 'payload');
// $ExpectType "POST"
requestDetails.method;
// $ExpectType Headers
requestDetails.headers;
// $ExpectType Buffer
requestDetails.body;
// $ExpectType string
requestDetails.endpoint;
// $ExpectType string | undefined
requestDetails.proxy;
// ====================
// sendNotification()
// ====================
// $ExpectType Promise<SendResult>
sendNotification(pushSubscription, 'payload', requestOptions);
// Buffers are also supported
// $ExpectType Promise<SendResult>
sendNotification(pushSubscription, buffer);
// $ExpectType Promise<SendResult>
sendNotification(pushSubscription, buffer, requestOptions);
// Payload can be absent or null
// $ExpectType Promise<SendResult>
sendNotification(pushSubscription);
// $ExpectType Promise<SendResult>
sendNotification(pushSubscription, null, requestOptions);
// PushSubscription must have all its values
// $ExpectError
sendNotification({}, 'payload');
// $ExpectError
sendNotification({ endpoint: 'endpoint' }, 'payload');
// $ExpectError
sendNotification({ keys: { p256dh: 'p256dh', auth: 'auth' } }, 'payload');
// $ExpectError
sendNotification({ endpoint: null, keys: { p256dh: 'p256dh', auth: 'auth' } }, 'payload');
// $ExpectError
sendNotification({ endpoint: 'endpoint', keys: null }, 'payload');
sendNotification({ endpoint: 'endpoint', keys: { p256dh: 'p256dh', auth: 'auth' } }, 'payload');
// =============
// SendResult
// =============
const sendResult = sendNotification(pushSubscription, 'payload');
sendResult.then((result) => {
// ExpectType number
result.statusCode;
// $ExpectType string
result.body;
// $ExpectType Headers
result.headers;
});
sendResult.catch((error: WebPushError) => {
});
+1 -1
View File
@@ -158,7 +158,7 @@ declare namespace WebpackDevServer {
* This option lets you precisely control what bundle information gets displayed.
* This can be a nice middle ground if you want some bundle information, but not all of it.
*/
stats?: string | webpack.Options.Stats;
stats?: webpack.Options.Stats;
/** This option lets the browser open with your local IP. */
useLocalIp?: boolean;
/** Tell the server to watch the files served by the devServer.contentBase option. File changes will trigger a full page reload. */
@@ -58,6 +58,11 @@ const config: WebpackDevServer.Configuration = {
staticOptions: {
},
stats: {
assets: false,
warningsFilter: /1/,
},
// webpack-dev-middleware options
quiet: false,
noInfo: false,
@@ -72,6 +77,13 @@ const config: WebpackDevServer.Configuration = {
headers: { "X-Custom-Header": "yes" }
};
const c2: WebpackDevServer.Configuration = {
stats: false,
};
const c3: WebpackDevServer.Configuration = {
stats: "verbose",
};
// API example
server = new WebpackDevServer(compiler, config);
server.listen(8080, "localhost", () => { });
+4 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for yargs 11.1
// Type definitions for yargs 12.0
// Project: https://github.com/chevex/yargs
// Definitions by: Martin Poelstra <https://github.com/poelstra>
// Mizunashi Mana <https://github.com/mizunashi-mana>
@@ -129,6 +129,8 @@ declare namespace yargs {
locale(): string;
locale(loc: string): Argv;
middleware(callbacks: MiddlewareFunction | MiddlewareFunction[]): Argv;
nargs(key: string, count: number): Argv;
nargs(nargs: { [key: string]: number }): Argv;
@@ -311,6 +313,7 @@ declare namespace yargs {
type CommandBuilder = { [key: string]: Options } | ((args: Argv) => Argv);
type SyncCompletionFunction = (current: string, argv: any) => string[];
type AsyncCompletionFunction = (current: string, argv: any, done: (completion: string[]) => void) => void;
type MiddlewareFunction = (args: Arguments) => void;
type Choices = Array<string | true | undefined>;
type PositionalOptionsType = "boolean" | "number" | "string";
}
+5
View File
@@ -0,0 +1,5 @@
[*.ts]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
+319
View File
@@ -0,0 +1,319 @@
// Type definitions for yargs 11.1
// Project: https://github.com/chevex/yargs
// Definitions by: Martin Poelstra <https://github.com/poelstra>
// Mizunashi Mana <https://github.com/mizunashi-mana>
// Jeffery Grajkowski <https://github.com/pushplay>
// Jeff Kenney <https://github.com/jeffkenney>
// Jimi (Dimitris) Charalampidis <https://github.com/JimiC>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// The following TSLint rules have been disabled:
// unified-signatures: Because there is useful information in the argument names of the overloaded signatures
// Convention:
// Use 'union types' when:
// - parameter types have similar signature type (i.e. 'string | string[]')
// - parameter names have the same semantic meaning (i.e. ['command', 'commands'] , ['key', 'keys'])
// An example for not using 'union types' is the declaration of 'env' where `prefix` and `enable` parameters
// have different semantics. On the other hand, in the declaration of 'usage', a `command: string` parameter
// has the same semantic meaning with declaring an overload method by using `commands: string[]`, thus
// it's prefered to use `command: string | string[]`
// Use parameterless declaration instead of declaring all parameters optional,
// when all parameters are optional and more than one
declare namespace yargs {
interface Argv {
(): Arguments;
(args: string[], cwd?: string): Arguments;
alias(shortName: string | string[], longName: string | string[]): Argv;
alias(aliases: { [shortName: string]: string | string[] }): Argv;
argv: Arguments;
array(key: string | string[]): Argv;
boolean(key: string | string[]): Argv;
check(func: (argv: Arguments, aliases: { [alias: string]: string }) => any, global?: boolean): Argv;
choices(key: string, values: Choices): Argv;
choices(choices: { [argName: string]: Choices }): Argv;
coerce(key: string | string[], func: (arg: any) => any): Argv;
coerce(opts: { [key: string]: (arg: any) => any; }): Argv;
command(command: string | string[], description: string, builder?: (args: Argv) => Argv, handler?: (args: Arguments) => void): Argv;
command(command: string | string[], description: string, builder?: { [key: string]: Options }, handler?: (args: Arguments) => void): Argv;
command(command: string | string[], description: string, module: CommandModule): Argv;
command(command: string | string[], showInHelp: false, builder?: (args: Argv) => Argv, handler?: (args: Arguments) => void): Argv;
command(command: string | string[], showInHelp: false, builder?: { [key: string]: Options }, handler?: (args: Arguments) => void): Argv;
command(command: string | string[], showInHelp: false, module: CommandModule): Argv;
command(module: CommandModule): Argv;
// Advanced API
commandDir(dir: string, opts?: RequireDirectoryOptions): Argv;
completion(): Argv;
completion(cmd: string, func?: AsyncCompletionFunction): Argv;
completion(cmd: string, func?: SyncCompletionFunction): Argv;
completion(cmd: string, description?: string, func?: AsyncCompletionFunction): Argv;
completion(cmd: string, description?: string, func?: SyncCompletionFunction): Argv;
config(): Argv;
config(key: string | string[], description?: string, parseFn?: (configPath: string) => object): Argv;
config(key: string | string[], parseFn: (configPath: string) => object): Argv;
config(explicitConfigurationObject: object): Argv;
conflicts(key: string, value: string | string[]): Argv;
conflicts(conflicts: { [key: string]: string | string[] }): Argv;
count(key: string | string[]): Argv;
default(key: string, value: any, description?: string): Argv;
default(defaults: { [key: string]: any }, description?: string): Argv;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
demand(key: string | string[], msg: string): Argv;
demand(key: string | string[], required?: boolean): Argv;
demand(positionals: number, msg: string): Argv;
demand(positionals: number, required?: boolean): Argv;
demand(positionals: number, max: number, msg?: string): Argv;
demandOption(key: string | string[], msg?: string): Argv;
demandOption(key: string | string[], demand?: boolean): Argv;
demandCommand(): Argv;
demandCommand(min: number, minMsg?: string): Argv;
demandCommand(min: number, max?: number, minMsg?: string, maxMsg?: string): Argv;
describe(key: string | string[], description: string): Argv;
describe(descriptions: { [key: string]: string }): Argv;
detectLocale(detect: boolean): Argv;
env(): Argv;
env(prefix: string): Argv;
env(enable: boolean): Argv;
epilog(msg: string): Argv;
epilogue(msg: string): Argv;
example(command: string, description: string): Argv;
exitProcess(enabled: boolean): Argv;
fail(func: (msg: string, err: Error) => any): Argv;
getCompletion(args: string[], done: (completions: string[]) => void): Argv;
global(key: string | string[]): Argv;
group(key: string | string[], groupName: string): Argv;
hide(key: string): Argv;
help(): Argv;
help(enableExplicit: boolean): Argv;
help(option: string, enableExplicit: boolean): Argv;
help(option: string, description?: string, enableExplicit?: boolean): Argv;
implies(key: string, value: string | string[]): Argv;
implies(implies: { [key: string]: string | string[] }): Argv;
locale(): string;
locale(loc: string): Argv;
nargs(key: string, count: number): Argv;
nargs(nargs: { [key: string]: number }): Argv;
normalize(key: string | string[]): Argv;
number(key: string | string[]): Argv;
option(key: string, options: Options): Argv;
option(options: { [key: string]: Options }): Argv;
options(key: string, options: Options): Argv;
options(options: { [key: string]: Options }): Argv;
parse(): Arguments;
parse(arg: string | string[], context?: object, parseCallback?: ParseCallback): Arguments;
pkgConf(key: string | string[], cwd?: string): Argv;
/**
* 'positional' should be called in a command's builder function, and is not
* available on the top-level yargs instance. If so, it will throw an error.
*/
positional(key: string, opt: PositionalOptions): Argv;
recommendCommands(): Argv;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
require(key: string, msg: string): Argv;
require(key: string, required: boolean): Argv;
require(keys: number[], msg: string): Argv;
require(keys: number[], required: boolean): Argv;
require(positionals: number, required: boolean): Argv;
require(positionals: number, msg: string): Argv;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
required(key: string, msg: string): Argv;
required(key: string, required: boolean): Argv;
required(keys: number[], msg: string): Argv;
required(keys: number[], required: boolean): Argv;
required(positionals: number, required: boolean): Argv;
required(positionals: number, msg: string): Argv;
requiresArg(key: string | string[]): Argv;
/**
* @deprecated since version 6.6.0
* Use '.global()' instead
*/
reset(): Argv;
scriptName($0: string): Argv;
showCompletionScript(): Argv;
showhidden(option?: string | boolean): Argv;
showhidden(option: string, description?: string): Argv;
showHelp(consoleLevel?: string): Argv;
showHelpOnFail(enable: boolean, message?: string): Argv;
skipValidation(key: string | string[]): Argv;
strict(): Argv;
string(key: string | string[]): Argv;
// Intended to be used with '.wrap()'
terminalWidth(): number;
updateLocale(obj: { [key: string]: string }): Argv;
updateStrings(obj: { [key: string]: string }): Argv;
usage(message: string): Argv;
usage(command: string | string[], description: string, builder?: (args: Argv) => Argv, handler?: (args: Arguments) => void): Argv;
usage(command: string | string[], showInHelp: boolean, builder?: (args: Argv) => Argv, handler?: (args: Arguments) => void): Argv;
usage(command: string | string[], description: string, builder?: { [key: string]: Options }, handler?: (args: Arguments) => void): Argv;
usage(commands: string | string[], showInHelp: boolean, builder?: { [key: string]: Options }, handler?: (args: Arguments) => void): Argv;
version(): Argv;
version(version: string): Argv;
version(enable: boolean): Argv;
version(optionKey: string, version: string): Argv;
version(optionKey: string, description: string, version: string): Argv;
wrap(columns: number | null): Argv;
}
interface Arguments {
/** Non-option arguments */
_: string[];
/** The script name or node command */
$0: string;
/** All remaining options */
[argName: string]: any;
}
interface RequireDirectoryOptions {
recurse?: boolean;
extensions?: string[];
visit?: (commandObject: any, pathToFile?: string, filename?: string) => any;
include?: RegExp | ((pathToFile: string) => boolean);
exclude?: RegExp | ((pathToFile: string) => boolean);
}
interface Options {
alias?: string | string[];
array?: boolean;
boolean?: boolean;
choices?: Choices;
coerce?: (arg: any) => any;
config?: boolean;
configParser?: (configPath: string) => object;
conflicts?: string | string[] | { [key: string]: string | string[] };
count?: boolean;
default?: any;
defaultDescription?: string;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
demand?: boolean | string;
demandOption?: boolean | string;
desc?: string;
describe?: string;
description?: string;
global?: boolean;
group?: string;
hidden?: boolean;
implies?: string | string[] | { [key: string]: string | string[] };
nargs?: number;
normalize?: boolean;
number?: boolean;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
require?: boolean | string;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
required?: boolean | string;
requiresArg?: boolean;
skipValidation?: boolean;
string?: boolean;
type?: "array" | "count" | PositionalOptionsType;
}
interface PositionalOptions {
alias?: string | string[];
choices?: Choices;
coerce?: (arg: any) => any;
conflicts?: string | string[] | { [key: string]: string | string[] };
default?: any;
desc?: string;
describe?: string;
description?: string;
implies?: string | string[] | { [key: string]: string | string[] };
normalize?: boolean;
type?: PositionalOptionsType;
}
interface CommandModule {
aliases?: string[] | string;
builder?: CommandBuilder;
command?: string[] | string;
describe?: string | false;
handler: (args: any) => void;
}
type ParseCallback = (err: Error | undefined, argv: Arguments, output: string) => void;
type CommandBuilder = { [key: string]: Options } | ((args: Argv) => Argv);
type SyncCompletionFunction = (current: string, argv: any) => string[];
type AsyncCompletionFunction = (current: string, argv: any, done: (completion: string[]) => void) => void;
type Choices = Array<string | true | undefined>;
type PositionalOptionsType = "boolean" | "number" | "string";
}
declare var yargs: yargs.Argv;
export = yargs;
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../../",
"paths": {
"yargs": [
"yargs/v11"
]
},
"typeRoots": [
"../../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"yargs-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"unified-signatures": false
}
}
+668
View File
@@ -0,0 +1,668 @@
/// <reference types="node" />
import yargs = require('yargs');
import * as fs from 'fs';
import * as path from 'path';
const stringVal = 'string';
// Examples taken from yargs website
// https://github.com/chevex/yargs
// With yargs, the options be just a hash!
function xup() {
const argv = yargs.argv;
if (argv.rif - 5 * argv.xup > 7.138) {
console.log('Plunder more riffiwobbles!');
} else {
console.log('Drop the xupptumblers!');
}
}
// And non-hyphenated options too! Just use argv._!
function nonopt() {
const argv = yargs.argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);
}
// Yargs even counts your booleans!
function count() {
const argv = yargs
.count('verbose')
.alias('v', 'verbose')
.argv;
const VERBOSE_LEVEL: number = argv.verbose;
function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); }
}
// Tell users how to use yer options and make demands.
function divide() {
const argv = yargs
.usage('Usage: $0 -x [num] -y [num]')
.demand(['x', 'y'])
.argv;
console.log(argv.x / argv.y);
}
// After yer demands have been met, demand more! Ask for non-hypenated arguments!
function demand_count() {
const argv = yargs
.demand(2)
.demand(2, false)
.demand(2, 2)
.demand(2, 2, "message")
.argv;
console.dir(argv);
}
// EVEN MORE SHIVER ME TIMBERS!
function default_singles() {
const argv = yargs
.default('x', 10)
.default('y', 10)
.argv
;
console.log(argv.x + argv.y);
}
function default_hash() {
const argv = yargs
.default({ x: 10, y: 10 })
.argv
;
console.log(argv.x + argv.y);
}
// And if you really want to get all descriptive about it...
function boolean_single() {
const argv = yargs
.boolean('v')
.argv
;
console.dir(argv.v);
console.dir(argv._);
}
function boolean_double() {
const argv = yargs
.boolean(['x', 'y', 'z'])
.argv
;
console.dir([argv.x, argv.y, argv.z]);
console.dir(argv._);
}
// Yargs is here to help you...
function line_count() {
const argv = yargs
.usage('Count the lines in a file.\nUsage: $0')
.example('$0 -f', 'count the lines in the given file')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.argv
;
}
// Below are tests for individual methods.
// Not all methods are covered yet, and neither are all possible invocations of methods.
function Argv$argv() {
const argv = yargs.argv;
console.log("command name: " + argv.$0);
console.log("command: " + argv._[1]);
}
function Argv_parsing() {
const argv1 = yargs.parse();
const argv2 = yargs(['-x', '1', '-y', '2']).argv;
const argv3 = yargs.parse(['-x', '1', '-y', '2']);
console.log(argv1.x, argv2.x, argv3.x);
}
function Argv$options() {
const argv1 = yargs
.options('f', {
alias: 'file',
default: '/etc/passwd',
defaultDescription: 'The /etc/passwd file',
group: 'files',
normalize: true,
global: false,
array: true,
nargs: 3,
implies: 'other-arg',
conflicts: 'conflicting-arg',
})
.argv
;
const argv2 = yargs
.alias('f', 'file')
.default('f', '/etc/passwd')
.argv
;
}
function Argv$global() {
const argv = yargs
.global('foo')
.global(['bar', 'baz', 'fizz', 'buzz']);
}
function Argv$group() {
const argv = yargs
.group('foo', 'foogroup')
.group(['bing', 'bang', 'buzz'], 'onomatopoeia');
}
function Argv$env() {
const argv = yargs
.env('YARGS_PREFIX_')
.env()
.env(true);
}
function Argv$array() {
const argv = yargs
.array('foo')
.array(['bar', 'baz']);
}
function Argv$nargs() {
const argv = yargs
.nargs('foo', 12)
.nargs({ bing: 3, bang: 2, buzz: 4 });
}
function Argv$choices() {
// example from documentation
const argv = yargs
.alias('i', 'ingredient')
.describe('i', 'choose your sandwich ingredients')
.choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles'])
.help('help')
.argv;
yargs
.choices('i', [undefined, true, 'asdf', 'test'])
.choices({
test: [undefined, true, 'test-value']
});
}
function Argv$usage_as_default_command() {
const argv = yargs
.usage(
"$0 get",
'make a get HTTP request',
(yargs) => {
return yargs.option('u', {
alias: 'url',
describe: 'the URL to make an HTTP request to'
});
},
(argv) => {
console.dir(argv.url);
}
)
.argv;
}
function Argv$command() {
const argv = yargs
.usage('npm <command>')
.command('install', 'tis a mighty fine package to install')
.command('publish', 'shiver me timbers, should you be sharing all that', yargs =>
yargs.option('f', {
alias: 'force',
description: 'yar, it usually be a bad idea'
})
.help('help')
)
.command("build", "arghh, build it mate", {
tag: {
default: true,
demand: true,
description: "Tag the build, mate!"
},
publish: {
default: false,
description: "Should i publish?"
}
})
.command({
command: "test",
describe: "test package",
builder: {
mateys: {
demand: false
}
},
handler: (args: any) => {
/* handle me mateys! */
}
})
.command("test", "test mateys", {
handler: (args: any) => {
/* handle me mateys! */
}
})
.help('help')
.argv;
yargs
.command('get', 'make a get HTTP request', (yargs) => {
return yargs.option('url', {
alias: 'u',
default: 'http://yargs.js.org/'
});
})
.help()
.argv;
yargs
.command(
'get',
'make a get HTTP request',
(yargs) => {
return yargs.option('u', {
alias: 'url',
describe: 'the URL to make an HTTP request to'
});
},
(argv) => {
console.dir(argv.url);
}
)
.help()
.argv;
}
function Argv$completion_sync() {
const argv = yargs
.completion('completion', (current, argv) => {
// 'current' is the current command being completed.
// 'argv' is the parsed arguments so far.
// simply return an array of completions.
return [
'foo',
'bar'
];
})
.argv;
}
function Argv$completion_async() {
const argv = yargs
.completion('completion', (current: string, argv: any, done: (completion: string[]) => void) => {
setTimeout(() => {
done([
'apple',
'banana'
]);
}, 500);
})
.argv;
}
function Argv$help() {
const argv = yargs
.usage("$0 -operand1 number -operand2 number -operation [add|subtract]")
.help()
.argv;
}
function Argv$showHelpOnFail() {
const argv = yargs
.usage('Count the lines in a file.\nUsage: $0')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.showHelpOnFail(false, "Specify --help for available options")
.argv;
}
function Argv$showHelp() {
const yargs1 = yargs
.usage("$0 -operand1 number -operand2 number -operation [add|subtract]");
yargs1.showHelp();
}
function Argv$version() {
const argv1 = yargs
.version();
const argv2 = yargs
.version('1.0.0');
const argv3 = yargs
.version('--version', '1.0.0');
const argv4 = yargs
.version('--version', 'Show version', '1.0.0');
const argv5 = yargs
.version(false);
}
function Argv$wrap() {
const argv1 = yargs
.wrap(null);
const argv2 = yargs
.wrap(yargs.terminalWidth());
}
function Argv$locale() {
const argv = yargs
.usage('./$0 - follow ye instructions true')
.option('option', {
alias: 'o',
describe: "'tis a mighty fine option",
demand: true
})
.command('run', "Arrr, ya best be knowin' what yer doin'")
.example('$0 run foo', "shiver me timbers, here's an example for ye")
.help('help')
.wrap(70)
.locale('pirate')
.argv;
}
function Argv$epilogue() {
const argv = yargs
.epilogue('for more information, find our manual at http://example.com');
}
function Argv$reset() {
const ya = yargs
.usage('$0 command')
.command('hello', 'hello command')
.command('world', 'world command')
.demand(1, 'must provide a valid command');
const argv = yargs.argv;
const command = argv._[0];
if (command === 'hello') {
ya.reset()
.usage('$0 hello')
.help('h')
.example('$0 hello', 'print the hello message!')
.argv;
console.log('hello!');
} else if (command === 'world') {
ya.reset()
.usage('$0 world')
.help('h')
.example('$0 world', 'print the world message!')
.argv;
console.log('world!');
} else {
ya.showHelp();
}
}
// http://yargs.js.org/docs/#methods-commanddirdirectory-opts
function Argv$commandDir() {
const ya = yargs
.commandDir('.')
.argv;
}
// http://yargs.js.org/docs/#methods-commanddirdirectory-opts
function Argv$commandDirWithOptions() {
const ya = yargs
.commandDir('.', {
recurse: false,
extensions: ['js'],
visit: (commandObject: any, pathToFile: string, filename: string) => void 0,
include: /.*\.js$/,
exclude: /.*\.spec.js$/,
})
.argv;
}
function Argv$normalize() {
const ya = yargs
.normalize('path')
.normalize(['user', 'group'])
.argv;
}
// From http://yargs.js.org/docs/#methods-coercekey-fn
function Argv$coerce() {
const ya = yargs
.coerce('file', (arg: string) => {
return fs.readFileSync(arg, 'utf8');
})
.argv;
}
function Argv$coerces() {
const ya = yargs
.coerce({
date: Date.parse,
json: JSON.parse
})
.argv;
}
function Argv$coerceWithKeys() {
const ya = yargs
.coerce(['src', 'dest'], path.resolve)
.argv;
}
// From http://yargs.js.org/docs/#methods-failfn
function Argv$fail() {
const ya = yargs
.fail((msg, err) => {
if (err) throw err; // preserve stack
console.error('You broke it!');
console.error(msg);
process.exit(1);
})
.argv;
}
function Argv$implies() {
const ya = yargs
.implies('foo', 'snuh')
.implies({
x: 'y'
})
.argv;
}
function Argv$count() {
const ya = yargs
.count('size')
.count(['w', 'h'])
.argv;
}
function Argv$number() {
const ya = yargs
.number('n')
.number(['width', 'height'])
.argv;
}
function Argv$updateStrings() {
const ya = yargs
.command('run', 'the run command')
.help('help')
.updateStrings({
'Commands:': 'My Commands -->\n'
})
.wrap(null)
.argv;
}
function Argv$default() {
const ya = yargs
.default('random', function randomValue() {
return Math.random() * 256;
})
.argv;
}
function Argv$configObject() {
const ya = yargs
.config({ foo: 1, bar: 2 })
.argv;
}
function Argv$configParseFunction() {
const ya = yargs
.config('settings', (configPath) => {
return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
})
.config('settings', 'description', (configPath) => {
return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
})
.argv;
}
function Argv$helpDescriptionExplicit() {
const ya = yargs
.help('help', 'description', true)
.argv;
}
function Argv$showHelpConsoleLevel() {
yargs.showHelp("log"); // prints to stdout using console.log()
}
function Argv$getCompletion() {
const ya = yargs
.option('foobar', {})
.option('foobaz', {})
.completion()
.getCompletion(['./test.js', '--foo'], (completions) => {
console.log(completions);
})
.argv;
}
function Argv$pkgConf() {
const ya = yargs
.pkgConf(['key1', 'key2'], 'configFile.json')
.argv;
}
function Argv$recommendCommands() {
const ya = yargs
.recommendCommands()
.argv;
}
function Argv$showCompletionScript() {
const ya = yargs
.showCompletionScript()
.argv;
}
function Argv$skipValidation() {
const ya = yargs
.skipValidation('arg1')
.skipValidation(['arg2', 'arg3'])
.argv;
}
function Argv$commandObject() {
const options: yargs.Options = {
alias: "string",
array: true,
boolean: true,
choices: [undefined, true, "a", "b", "c"],
coerce: f => JSON.stringify(f),
config: true,
configParser: t => JSON.parse(fs.readFileSync(t, "utf8")),
count: true,
default: "myvalue",
defaultDescription: "description",
demand: true,
demandOption: true,
desc: "desc",
describe: "describe",
description: "description",
global: false,
group: "group",
nargs: 1,
normalize: false,
number: true,
requiresArg: true,
skipValidation: false,
string: true,
type: "string"
};
const ya = yargs.command("commandname", "description", { arg: options });
}
function Argv$demandCommand() {
const ya = yargs
.demandCommand(1)
.demandCommand(1, 'at least 1 command required')
.demandCommand(1, 2)
.demandCommand(1, 2, 'at least 1 command required')
.demandCommand(1, 2, 'at least 1 command required', 'at most 2 commands required')
.argv;
}
function Argv$demandOption() {
const ya = yargs
.demandOption('a')
.demandOption('a', 'a is required')
.demandOption('a', true)
.demandOption(['a', 'b'])
.demandOption(['a', 'b'], 'a and b are required')
.demandOption(['a', 'b'], true)
.argv;
}
function Argv$conflicts() {
const ya = yargs
.conflicts('a', 'b')
.conflicts({
a: 'b'
})
.argv;
}
function Argv$commandArray() {
const ya = yargs
.command(['commandName', 'commandAlias'], 'command description')
.argv;
}
function Argv$check() {
const ya = yargs
.check((argv, aliases) => void 0)
.check((argv, aliases) => void 0, false);
}
function Argv$hide() {
const ya = yargs
.hide('a');
}
function Argv$showhidden() {
const ya = yargs
.showhidden()
.showhidden(true)
.showhidden('show-hidden')
.showhidden('show-hidden', 'Show hidden options');
}
function Argv$scriptName() {
const ya = yargs
.scriptName("my-script");
}