Merge branch 'master' into victory-VictoryGroup-offset

This commit is contained in:
James Lismore
2019-01-10 14:08:41 -05:00
228 changed files with 8936 additions and 3495 deletions
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for node-gettext 2.0
// Project: http://github.com/alexanderwallin/node-gettext
// Definitions by: Sameer K.C. <https://github.com/sameercaresu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = GetText;
declare class GetText {
constructor(options?: { debug: boolean; });
addTranslations(locale: string, domain: string, translations: object): void;
dgettext(domain: string, msgid: string): string;
dngettext(domain: string, msgid: string, msgidPlural: string, count: number): string;
dnpgettext(domain: string, msgctxt: string, msgid: string, msgidPlural: string, count: number): string;
dpgettext(domain: string, msgctxt: string, msgid: string): string;
emit(eventName: string, eventData: any): void;
getComment(domain: string, msgctxt: string, msgid: string): object | boolean;
gettext(msgid: string): string;
ngettext(msgid: string, msgidPlural: string, count: number): string;
npgettext(msgctxt: string, msgid: string, msgidPlural: string, count: number): string;
off(eventName: string, callback: (params: any) => void): string;
on(eventName: string, callback: (params: any) => void): void;
pgettext(msgctxt: string, msgid: string): string;
setLocale(locale: string): void;
setTextDomain(domain: string): void;
static getLanguageCode(locale: string): string;
textdomain(domain: string): void;
warn(message: string): void;
}
+34
View File
@@ -0,0 +1,34 @@
// with tsc v 2.7 & esModuleInterop & allowSyntheticDefaultImports enabled in tsconfig.json
import Gettext from 'node-gettext';
// or without
// import Gettext = require('node-getttext');
const translations = {};
const gt = new Gettext({ debug: true });
const msgid = 'Get translation';
const msgidPlural = 'Get translations';
const domain = 'domain';
const msgctxt = 'context';
const count = 2;
gt.addTranslations('en-US', 'messages', translations);
gt.setTextDomain(domain);
gt.textdomain(domain);
gt.setLocale('en-US');
gt.gettext(msgid);
gt.dgettext('', msgid);
gt.dngettext(domain, msgid, msgidPlural, count);
gt.dnpgettext(domain, msgctxt, msgid, msgidPlural, count);
gt.dpgettext(domain, msgctxt, msgid);
gt.getComment(domain, msgctxt, msgid);
gt.ngettext(msgid, msgidPlural, count);
gt.npgettext(msgctxt, msgid, msgidPlural, count);
gt.pgettext(msgctxt, msgid);
Gettext.getLanguageCode('en-US');
gt.warn('warning');
const errorListener = (error: string) => {
// do something;
};
gt.on('error', errorListener);
gt.emit('error', 'Error occurred');
gt.off('error', errorListener);
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"files": [
"index.d.ts",
"node-gettext-tests.ts"
]
}
+12
View File
@@ -684,6 +684,12 @@
"sourceRepoURL": "https://handsontable.com/",
"asOfVersion": "0.35.0"
},
{
"libraryName": "hibp",
"typingsPackageName": "hibp",
"sourceRepoURL": "https://github.com/wKovacs64/hibp",
"asOfVersion": "7.3.0"
},
{
"libraryName": "homeworks",
"typingsPackageName": "homeworks",
@@ -1482,6 +1488,12 @@
"sourceRepoURL": "https://github.com/zeh/simplesignal",
"asOfVersion": "1.0.0"
},
{
"libraryName": "sip.js",
"typingsPackageName": "sip.js",
"sourceRepoURL": "https://github.com/onsip/SIP.js",
"asOfVersion": "0.12.0"
},
{
"libraryName": "smooth-scrollbar",
"typingsPackageName": "smooth-scrollbar",
+2
View File
@@ -14,6 +14,8 @@ accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB"
const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"]
languages.lastIndexOf('');
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]);
const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"]
mediaTypes.lastIndexOf('');
+1
View File
@@ -10,6 +10,7 @@ export function encoding(encodingHeader?: string, preferences?: string[]): strin
export function encodings(encodingHeader?: string): string[];
export function language(languageHeader?: string, preferences?: string[]): string;
export function languages(languageHeader?: string): string[];
export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string;
export function mediaTypes(mediaTypeHeader?: string): string[];
export function parseAll(
headers: Record<string, string | string[] | undefined>
+10
View File
@@ -549,6 +549,16 @@ declare namespace AceAjax {
getFoldsInRange(range: Range): any;
highlight(text: string): void;
/**
* Highlight lines from `startRow` to `EndRow`.
* @param startRow Define the start line of the highlight
* @param endRow Define the end line of the highlight
* @param clazz Set the CSS class for the marker
* @param inFront Set to `true` to establish a front marker
**/
highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range;
/**
* Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`.
+4 -1
View File
@@ -18,6 +18,7 @@ declare namespace OSS {
internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money.
secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol.
timeout?: string | number; // instance level timeout for all operations, default is 60s
cname?: boolean; // use custom domain name
}
interface Bucket {
@@ -29,7 +30,7 @@ declare namespace OSS {
type StorageType = "Standard" | "IA" | "Archive";
type ACLType = "public-read-write" | "public-read" | "and private";
type ACLType = "public-read-write" | "public-read" | "private";
type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT";
@@ -174,6 +175,7 @@ declare namespace OSS {
mime?: string; // custom mime, will send with Content-Type entity header
meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 }
callback: ObjectCallback;
headers?: object;
}
interface PutObjectResult {
@@ -188,6 +190,7 @@ declare namespace OSS {
mime: string; // custom mime, will send with Content-Type entity header
meta: UserMeta;
callback: ObjectCallback;
headers?: object;
}
interface AppendObjectOptions {
@@ -0,0 +1,6 @@
import { BdApi } from 'bandagedbd__bdapi';
BdApi.React; // $ExpectType typeof React
BdApi.ReactDOM.render; // $ExpectType Renderer
BdApi.alert('foo', 'bar'); // $ExpectType void
BdApi.showToast('hello', { timeout: 2000 }); // $ExpectType void
+176
View File
@@ -0,0 +1,176 @@
// Type definitions for bdapi 0.2
// Project: https://github.com/rauenzi/BetterDiscordApp
// Definitions by: Ari Seyhun <https://github.com/Acidic9>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// Documentation: https://github.com/rauenzi/BetterDiscordApp/wiki/Creating-Plugins#bdapi
import * as ReactInstance from 'react';
import * as ReactDOMInstance from 'react-dom';
export const BdApi: typeof BdApiModule;
/**
* Function with no arguments and no return value that may be called to revert changes made by monkeyPatch method,
* restoring (unpatching) original method.
*/
export type CancelPatch = () => void;
/**
* A callback that modifies method logic.
* This callback is called on each call of the original method and is provided all data about original call.
* Any of the data can be modified if necessary, but do so wisely.
*/
export type PatchFunction = (data: PatchData) => any;
/**
* A callback that modifies method logic.
* This callback is called on each call of the original method and is provided all data about original call.
* Any of the data can be modified if necessary, but do so wisely.
*/
export interface PatchData {
thisObject: object;
methodArguments: any[];
CancelPatch: CancelPatch;
originalMethod: () => void;
callOriginalMethod: () => void;
returnValue: any;
}
export interface MonkeyPatchOptions {
once?: boolean;
silent?: boolean;
displayName?: string;
before?: PatchFunction;
after?: PatchFunction;
instead?: PatchFunction;
}
export interface ToastOptions {
type?: string;
icon?: boolean;
timeout?: number;
}
export namespace BdApiModule {
/**
* The React module being used inside Discord.
*/
const React: typeof ReactInstance;
/**
* The ReactDOM module being used inside Discord.
*/
const ReactDOM: typeof ReactDOMInstance;
/**
* Creates an shows an alert modal to the user. A preview of how it may look can be found [here](https://i.zackrauen.com/7qnnNC.png).
*/
function alert(title: string, content: string): void;
/**
* Removes a style added with [`injectCSS`](#injectcssid-css) below.
*/
function clearCSS(id: string): void;
/**
* Deletes some saved data for plugin `pluginName` with key `key`.
*/
function deleteData(pluginName: string, key: string): void;
/**
* Searches for an internal Discord webpack module based on `filter`.
*/
function findModule(filter: () => void): any;
/**
* Searches for multiple internal Discord webpack module based on `filter`. It's the same as [`findModule`](#findmodulefilter) but will return all matches
*/
function findAllModules(filter: () => void): any[];
/**
* Searches for an internal Discord webpack module that has every property passed.
*/
function findModuleByProps(...props: string[]): any;
/**
* Returns BandagedBD's instance of the core module. Only use this if you know what you are doing.
*/
function getCore(): any; // TODO: This should not return 'any' but instead 'Core'
/**
* Alias for [loadData(pluginName, key)](#loaddatapluginname-key)
*/
function getData(pluginName: string, key: string): any;
/**
* Gets the internal react instance for a particular node.
*/
function getInternalInstance(node: HTMLElement): object|undefined;
/**
* Gets the instance of another plugin with the name `name`.
*/
function getPlugin(name: string): object|null;
/**
* Adds a block of css to the current document's `head`.
*/
function injectCSS(id: string, css: string): object|null;
/**
* Links some remote JavaScript to be added to the page. Useful for libraries like `Sortable.js`.
*/
function linkJS(id: string, url: string): void;
/**
* Gets some saved data for plugin `pluginName` with key `key`. Data can be saved with [`saveData`](#savedatapluginname-key-data).
*/
function loadData(pluginName: string, key: string): any;
/**
* This function monkey-patches a method on an object. The patching callback may be run before, after or instead of target method.
* - Be careful when monkey-patching. Think not only about original functionality of target method and your changes,
* but also about developers of other plugins, who may also patch this method before or after you.
* Try to change target method behaviour as little as possible, and avoid changing method signatures.
* - Display name of patched method is changed, so you can see if a function has been patched (and how many times) while debugging or in the stack trace.
* Also, patched methods have property `__monkeyPatched` set to `true`, in case you want to check something programmatically.
*/
function monkeyPatch(module: object, methodName: string, options: MonkeyPatchOptions): CancelPatch;
/**
* Adds a listener for when the node is removed from the document body.
*/
function onRemoved(node: HTMLElement, callback: () => void): void;
/**
* Saved some `data` for plugin `pluginName` under `key` key. Gets saved in the plugins folder under `pluginName.config.json`. Data can be saved with [`loadData`](#loaddatapluginname-key).
*/
function saveData(pluginName: string, key: string, data: any): void;
/**
* Alias for [saveData(pluginName, key, data)](#savedatapluginname-key-data)
*
*/
function setData(pluginName: string, key: string, data: any): void;
/**
* Shows a simple toast message similar to on Android. An example of the `success` toast can be seen [here](https://i.zackrauen.com/zIagVa.png).
*/
function showToast(content: string, options?: ToastOptions): void;
/**
* Wraps a function in a try catch block.
*/
function suppressErrors(method: () => void, message?: string): () => void;
/**
* Determines if the input is valid and parseable JSON.
*/
function testJSON(data: string): boolean;
/**
* Removes some previously linked JS by [`linkJS`](#linkjsid-url).
*/
function unlinkJS(id: string): void;
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react"
},
"files": [
"index.d.ts",
"bandagedbd__bdapi-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+6 -6
View File
@@ -146,7 +146,7 @@ declare class ByteBuffer
/**
* Concatenates multiple ByteBuffers into one.
*/
static concat( buffers: Array<ByteBuffer | ArrayBuffer | Uint8Array | string>, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer;
static concat( buffers: Array<ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string>, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a base64 encoded string to a ByteBuffer.
@@ -185,7 +185,7 @@ declare class ByteBuffer
* @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN.
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT.
*/
static wrap( buffer: ByteBuffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
static wrap( buffer: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a zigzag encoded signed 32bit integer.
@@ -220,7 +220,7 @@ declare class ByteBuffer
/**
* Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length.
*/
append( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
append( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data.
@@ -291,7 +291,7 @@ declare class ByteBuffer
/**
* Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly.
*/
prepend( source: ByteBuffer | string | ArrayBuffer, encoding?: string | number, offset?: number ): ByteBuffer;
prepend( source: ByteBuffer | string | ArrayBuffer | Buffer, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly.
@@ -480,7 +480,7 @@ declare class ByteBuffer
/**
* Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched.
*/
toBuffer( forceCopy?: boolean ): ArrayBuffer;
toBuffer( forceCopy?: boolean ): Buffer;
/**
*Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
@@ -517,7 +517,7 @@ declare class ByteBuffer
/**
* Writes an array of bytes. This is an alias for append
*/
writeBytes( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
writeBytes( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself.
+12 -6
View File
@@ -1372,12 +1372,12 @@ export interface MediaInformation {
* is playing or ones that receiver will play shortly after; instead of sending
* whole list of clips. This is to avoid overflow of MediaStatus message.
*/
breakClips: BreakClip[];
breakClips?: BreakClip[];
/**
* List of breaks.
*/
breaks: Break[];
breaks?: Break[];
/**
* Typically the url of the media.
@@ -1414,12 +1414,18 @@ export interface MediaInformation {
/**
* The format of the HLS media segment.
*/
hlsSegmentFormat: HlsSegmentFormat;
hlsSegmentFormat?: HlsSegmentFormat;
/**
* The media metadata.
*/
metadata: MediaMetadata;
metadata?:
| MediaMetadata
| GenericMediaMetadata
| MovieMediaMetadata
| MusicTrackMediaMetadata
| PhotoMediaMetadata
| TvShowMediaMetadata;
/**
* The stream type.
@@ -1429,12 +1435,12 @@ export interface MediaInformation {
/**
* The style of text track.
*/
textTrackStyle: TextTrackStyle;
textTrackStyle?: TextTrackStyle;
/**
* The media tracks.
*/
tracks: Track[];
tracks?: Track[];
}
/**
+2 -2
View File
@@ -1,3 +1,3 @@
import * as cn from "./index";
import classNames = require('./index');
export function bind(styles: Record<string, string>): typeof cn;
export function bind(styles: Record<string, string>): typeof classNames;
+1 -1
View File
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
+3 -3
View File
@@ -1,13 +1,13 @@
// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.8
// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.9
// Project: https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin
// Definitions by: Markus Wagner <https://github.com/Ritzlgrmft>, Larry Bahr <https://github.com/larrybahr>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Window {
plugins: Plugins;
plugins: CordovaPlugins;
}
interface Plugins {
interface CordovaPlugins {
socialsharing: SocialSharingPlugin.SocialSharing;
}
+74 -26
View File
@@ -21,6 +21,9 @@ const csvTestStringWithHeader = `Year,Make,Model,Length\n${csvTestString}`;
const tsvTestStringWithHeader = `Year\tMake\tModel\tLength\n${tsvTestString}`;
const pipedTestStringWithHeader = `Year|Make|Model|Length\n${pipedTestString}`;
type Headers = "Year" | "Make" | "Model" | "Length";
type ParsedHeaders = "year" | "make" | "model" | "length";
interface ParsedTestObject {
year: Date | null;
make: string;
@@ -28,17 +31,56 @@ interface ParsedTestObject {
length: number;
}
let parseArray: d3Dsv.DSVParsedArray<d3Dsv.DSVRowString>;
let parseMappedArray: d3Dsv.DSVParsedArray<ParsedTestObject>;
let parseRowsArray: string[][];
let parseRowsMappedArray: ParsedTestObject[];
let parsedTestObject: ParsedTestObject;
let columns: string[];
let num: number;
let str: string;
let strMaybe: string | undefined;
let columns: string[];
let headers: Headers[];
let parsedHeaders: ParsedHeaders[];
// ------------------------------------------------------------------------------------------
// Test Shared Types and Interfaces
// ------------------------------------------------------------------------------------------
declare let row: d3Dsv.DSVRowString;
strMaybe = row.property;
declare let row2: d3Dsv.DSVRowString<Headers>;
strMaybe = row2.Make;
strMaybe = row2.Property; // $ExpectError
declare let raw: d3Dsv.DSVRaw<ParsedTestObject>;
strMaybe = raw.make;
strMaybe = raw.property; // $ExpectError
declare let rowArray: d3Dsv.DSVRowArray;
strMaybe = rowArray[0].property;
columns = rowArray.columns;
num = rowArray.length;
declare let rowArrayHeader: d3Dsv.DSVRowArray<Headers>;
strMaybe = rowArrayHeader[0].Make;
strMaybe = rowArrayHeader[0].Property; // $ExpectError
headers = rowArrayHeader.columns;
num = rowArrayHeader.length;
declare let parseMappedArray: d3Dsv.DSVParsedArray<ParsedTestObject>;
strMaybe = parseMappedArray[0].make;
strMaybe = parseMappedArray[0].property; // $ExpectError
parsedTestObject = parseMappedArray[0];
parsedHeaders = parseMappedArray.columns;
num = parseMappedArray.length;
declare let parseArray: d3Dsv.DSVParsedArray<d3Dsv.DSVRowString>;
strMaybe = parseArray[0].property;
columns = parseArray.columns;
num = parseArray.length;
// ------------------------------------------------------------------------------------------
// Test CSV
// ------------------------------------------------------------------------------------------
@@ -48,8 +90,7 @@ let strMaybe: string | undefined;
// without row mapper -----------------------------------------------------------------------
parseArray = d3Dsv.csvParse(csvTestStringWithHeader);
columns = parseArray.columns;
strMaybe = parseArray[0].Year;
rowArrayHeader = d3Dsv.csvParse<Headers>(csvTestStringWithHeader);
// with row mapper ---------------------------------------------------------------------------
@@ -73,8 +114,12 @@ parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, colum
return pr;
});
columns = parseMappedArray.columns;
parsedTestObject = parseMappedArray[0];
parseMappedArray = d3Dsv.csvParse<ParsedTestObject, Headers>(csvTestStringWithHeader, (rawRow, index, columns) => {
const rr: d3Dsv.DSVRowString<Headers> = rawRow;
const i: number = index;
const c: Headers[] = columns;
return parsedTestObject;
});
// csvParseRows(...) ============================================================================
@@ -108,12 +153,11 @@ parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => {
str = d3Dsv.csvFormat(parseRowsMappedArray);
str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "length"]);
// $ExpectError
str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]);
str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError
// csvFormatRows(...) ========================================================================
str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [
str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d) => [
d.year ? d.year.getFullYear().toString() : '',
d.make,
d.model,
@@ -129,8 +173,7 @@ str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [
// without row mapper -----------------------------------------------------------------------
parseArray = d3Dsv.tsvParse(tsvTestStringWithHeader);
columns = parseArray.columns;
strMaybe = parseArray[0].Year;
rowArrayHeader = d3Dsv.tsvParse<Headers>(csvTestStringWithHeader);
// with row mapper ---------------------------------------------------------------------------
@@ -154,8 +197,12 @@ parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, colum
return pr;
});
columns = parseMappedArray.columns;
parsedTestObject = parseMappedArray[0];
parseMappedArray = d3Dsv.tsvParse<ParsedTestObject, Headers>(tsvTestStringWithHeader, (rawRow, index, columns) => {
const rr: d3Dsv.DSVRowString<Headers> = rawRow;
const i: number = index;
const c: Headers[] = columns;
return parsedTestObject;
});
// tsvParseRows(...) ============================================================================
@@ -189,12 +236,11 @@ parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => {
str = d3Dsv.tsvFormat(parseRowsMappedArray);
str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "length"]);
// $ExpectError
str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]);
str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError
// tsvFormatRows(...) ========================================================================
str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d, i) => [
str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d) => [
d.year ? d.year.getFullYear().toString() : '',
d.make,
d.model,
@@ -215,8 +261,7 @@ dsv = d3Dsv.dsvFormat('|');
// without row mapper -----------------------------------------------------------------------
parseArray = dsv.parse(pipedTestStringWithHeader);
columns = parseArray.columns;
strMaybe = parseArray[0].Year;
rowArrayHeader = dsv.parse<Headers>(csvTestStringWithHeader);
// with row mapper ---------------------------------------------------------------------------
@@ -240,8 +285,12 @@ parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns)
return pr;
});
columns = parseMappedArray.columns;
parsedTestObject = parseMappedArray[0];
parseMappedArray = dsv.parse<ParsedTestObject, Headers>(pipedTestStringWithHeader, (rawRow, index, columns) => {
const rr: d3Dsv.DSVRowString<Headers> = rawRow;
const i: number = index;
const c: Headers[] = columns;
return parsedTestObject;
});
// parseRows(...) ============================================================================
@@ -275,12 +324,11 @@ parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => {
str = dsv.format(parseRowsMappedArray);
str = dsv.format(parseRowsMappedArray, ["year", "length"]);
// $ExpectError
str = dsv.format(parseRowsMappedArray, ["year", "unknown"]);
str = dsv.format(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError
// formatRows(...) ========================================================================
str = dsv.formatRows(parseRowsMappedArray.map((d, i) => [
str = dsv.formatRows(parseRowsMappedArray.map((d) => [
d.year ? d.year.getFullYear().toString() : '',
d.make,
d.model,
+53 -30
View File
@@ -15,21 +15,41 @@
/**
* An object representing a DSV parsed row with values represented as strings.
* When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value.
*/
export interface DSVRowString {
[key: string]: string | undefined;
}
export type DSVRowString<Columns extends string = string> = {
[key in Columns]: string | undefined;
};
/**
* An object in raw format before parsing, that is with only string values.
* When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value.
*/
export type DSVRaw<T extends object> = {
[key in keyof T]: string | undefined;
};
/**
* An object representing a DSV parsed row with values represented as an arbitrary datatype, depending
* on the performed parsed row mapping.
*
* @deprecated
* @deprecated Use `object` instead.
*/
export interface DSVRowAny {
[key: string]: any;
}
/**
* An array object representing all deserialized rows. The array is enhanced with a property listing
* the names of the parsed columns.
*/
export interface DSVRowArray<Columns extends string = string> extends Array<DSVRowString<Columns>> {
/**
* List of column names.
*/
columns: Columns[];
}
/**
* An array object representing all parsed rows. The array is enhanced with a property listing
* the names of the parsed columns.
@@ -38,7 +58,7 @@ export interface DSVParsedArray<T> extends Array<T> {
/**
* List of column names.
*/
columns: string[];
columns: Array<keyof T>;
}
// ------------------------------------------------------------------------------------------
@@ -55,11 +75,12 @@ export interface DSVParsedArray<T> extends Array<T> {
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
* Equivalent to dsvFormat(",").parse.
* Equivalent to `dsvFormat(",").parse`.
*
* @param csvString A string, which must be in the comma-separated values format.
*/
export function csvParse(csvString: string): DSVParsedArray<DSVRowString>;
// tslint:disable-next-line:no-unnecessary-generics
export function csvParse<Columns extends string>(csvString: string): DSVRowArray<Columns>;
/**
* Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows.
*
@@ -68,7 +89,7 @@ export function csvParse(csvString: string): DSVParsedArray<DSVRowString>;
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
* Equivalent to dsvFormat(",").parse.
* Equivalent to `dsvFormat(",").parse`.
*
* @param csvString A string, which must be in the comma-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -76,9 +97,9 @@ export function csvParse(csvString: string): DSVParsedArray<DSVRowString>;
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function csvParse<ParsedRow extends object>(
export function csvParse<ParsedRow extends object, Columns extends string>(
csvString: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): DSVParsedArray<ParsedRow>;
// csvParseRows(...) ========================================================================
@@ -92,7 +113,7 @@ export function csvParse<ParsedRow extends object>(
* If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types.
* In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function.
*
* Equivalent to dsvFormat(",").parseRows.
* Equivalent to `dsvFormat(",").parseRows`.
*
* @param csvString A string, which must be in the comma-separated values format.
*/
@@ -103,7 +124,7 @@ export function csvParseRows(csvString: string): string[][];
* Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header.
* Each row is represented as an array rather than an object. Rows may have variable length.
*
* Equivalent to dsvFormat(",").parseRows.
* Equivalent to `dsvFormat(",").parseRows`.
*
* @param csvString A string, which must be in the comma-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i)
@@ -127,7 +148,7 @@ export function csvParseRows<ParsedRow extends object>(
* If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows;
* the order of columns is nondeterministic.
*
* Equivalent to dsvFormat(",").format.
* Equivalent to `dsvFormat(",").format`.
*
* @param rows Array of object rows.
* @param columns An array of strings representing the column names.
@@ -145,7 +166,7 @@ export function csvFormat<T extends object>(rows: T[], columns?: Array<keyof T>)
* To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map.
* If you like, you can also array.concat this result with an array of column names to generate the first row.
*
* Equivalent to dsvFormat(",").formatRows.
* Equivalent to `dsvFormat(",").formatRows`.
*
* @param rows An array of array of string rows.
*/
@@ -165,11 +186,12 @@ export function csvFormatRows(rows: string[][]): string;
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
* Equivalent to dsvFormat("\t").parse.
* Equivalent to `dsvFormat("\t").parse`.
*
* @param tsvString A string, which must be in the tab-separated values format.
*/
export function tsvParse(tsvString: string): DSVParsedArray<DSVRowString>;
// tslint:disable-next-line:no-unnecessary-generics
export function tsvParse<Columns extends string>(tsvString: string): DSVRowArray<Columns>;
/**
* Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows.
*
@@ -178,7 +200,7 @@ export function tsvParse(tsvString: string): DSVParsedArray<DSVRowString>;
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
* Equivalent to dsvFormat("\t").parse.
* Equivalent to `dsvFormat("\t").parse`.
*
* @param tsvString A string, which must be in the tab-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -186,10 +208,10 @@ export function tsvParse(tsvString: string): DSVParsedArray<DSVRowString>;
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function tsvParse<MappedRow extends object>(
export function tsvParse<ParsedRow extends object, Columns extends string>(
tsvString: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow | undefined | null
): DSVParsedArray<MappedRow>;
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): DSVParsedArray<ParsedRow>;
// tsvParseRows(...) ========================================================================
@@ -202,7 +224,7 @@ export function tsvParse<MappedRow extends object>(
* If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types.
* In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function.
*
* Equivalent to dsvFormat("\t").parseRows.
* Equivalent to `dsvFormat("\t").parseRows`.
*
* @param tsvString A string, which must be in the tab-separated values format.
*/
@@ -213,7 +235,7 @@ export function tsvParseRows(tsvString: string): string[][];
* Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header.
* Each row is represented as an array rather than an object. Rows may have variable length.
*
* Equivalent to dsvFormat("\t").parseRows.
* Equivalent to `dsvFormat("\t").parseRows`.
*
* @param tsvString A string, which must be in the tab-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i)
@@ -221,10 +243,10 @@ export function tsvParseRows(tsvString: string): string[][];
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function tsvParseRows<MappedRow extends object>(
export function tsvParseRows<ParsedRow extends object>(
tsvString: string,
row: (rawRow: string[], index: number) => MappedRow | undefined | null
): MappedRow[];
row: (rawRow: string[], index: number) => ParsedRow | undefined | null
): ParsedRow[];
// tsvFormat(...) ============================================================================
@@ -237,7 +259,7 @@ export function tsvParseRows<MappedRow extends object>(
* If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows;
* the order of columns is nondeterministic.
*
* Equivalent to dsvFormat("\t").format.
* Equivalent to `dsvFormat("\t").format`.
*
* @param rows Array of object rows.
* @param columns An array of strings representing the column names.
@@ -255,7 +277,7 @@ export function tsvFormat<T extends object>(rows: T[], columns?: Array<keyof T>)
* To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map.
* If you like, you can also array.concat this result with an array of column names to generate the first row.
*
* Equivalent to dsvFormat("\t").formatRows.
* Equivalent to `dsvFormat("\t").formatRows`.
*
* @param rows An array of array of string rows.
*/
@@ -279,7 +301,8 @@ export interface DSV {
*
* @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter.
*/
parse(dsvString: string): DSVParsedArray<DSVRowString>;
// tslint:disable-next-line:no-unnecessary-generics
parse<Columns extends string>(dsvString: string): DSVRowArray<Columns>;
/**
* Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows.
*
@@ -294,9 +317,9 @@ export interface DSV {
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
parse<ParsedRow extends object>(
parse<ParsedRow extends object, Columns extends string>(
dsvString: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): DSVParsedArray<ParsedRow>;
/**
+145 -49
View File
@@ -1,62 +1,158 @@
import * as d3Fetch from 'd3-fetch';
import { DSVParsedArray, DSVRowString } from 'd3-dsv';
import { DSVParsedArray, DSVRaw, DSVRowString } from 'd3-dsv';
interface MyType {
foo: string;
// ----------------------------------------------------------------------------
// Preparatory Steps
// ----------------------------------------------------------------------------
type Headers = "Year" | "Make" | "Model" | "Length";
interface Car {
year: Date;
make: string;
model: string;
length: number;
}
const url = 'foo.bar';
const init: RequestInit = {};
let p1: Promise<Blob> = d3Fetch.blob(url);
p1 = d3Fetch.blob(url, init);
let p2: Promise<ArrayBuffer> = d3Fetch.buffer(url);
p2 = d3Fetch.buffer(url, init);
let p3: Promise<HTMLImageElement> = d3Fetch.image(url);
const imageProperties = {
width: '300px',
height: '500px'
};
p3 = d3Fetch.image(url, imageProperties);
let p4: Promise<any> = d3Fetch.json(url);
p4 = d3Fetch.json(url, init);
let p5: Promise<MyType> = d3Fetch.json<MyType>(url);
p5 = d3Fetch.json<MyType>(url, init);
let myString: Promise<string>;
myString = d3Fetch.text(url);
myString = d3Fetch.text(url, init);
const parseRow = (rawRow: DSVRowString, index: number, columns: string[]): (MyType | undefined | null) => {
const myType: MyType | null = rawRow['foo'] ? { foo: rawRow['foo'] + '+ bar' } : null;
return myType;
};
let promise1: Promise<DSVParsedArray<DSVRowString>>;
let promise2: Promise<DSVParsedArray<MyType>>;
promise1 = d3Fetch.csv(url);
promise1 = d3Fetch.csv(url, init);
promise2 = d3Fetch.csv<MyType>(url, parseRow);
promise2 = d3Fetch.csv<MyType>(url, init, parseRow);
promise1 = d3Fetch.dsv(';', url);
promise1 = d3Fetch.dsv(';', url, init);
promise2 = d3Fetch.dsv<MyType>(';', url, parseRow);
promise2 = d3Fetch.dsv<MyType>(';', url, init, parseRow);
promise1 = d3Fetch.tsv(url);
promise1 = d3Fetch.tsv(url, init);
promise2 = d3Fetch.tsv<MyType>(url, parseRow);
promise2 = d3Fetch.tsv<MyType>(url, init, parseRow);
let anyPromise: Promise<any>;
let arrayPromise: Promise<ArrayBuffer>;
let blobPromise: Promise<Blob>;
let docPromise: Promise<Document>;
let imagePromise: Promise<HTMLImageElement>;
let carPromise: Promise<Car>;
let stringPromise: Promise<string>;
let xmlDocPromise: Promise<XMLDocument>;
const url = 'example.org';
const init: RequestInit = {};
const map = new Map<string, number>();
const imageProperties = {
width: 300,
height: 500,
crossOrigin: "anonymous",
};
// ----------------------------------------------------------------------------
// Non DSV file format
// ----------------------------------------------------------------------------
blobPromise = d3Fetch.blob(url);
blobPromise = d3Fetch.blob(url, init);
arrayPromise = d3Fetch.buffer(url);
arrayPromise = d3Fetch.buffer(url, init);
imagePromise = d3Fetch.image(url);
imagePromise = d3Fetch.image(url, imageProperties);
// $ExpectError
imagePromise = d3Fetch.image(url, {width: "500px"}); // fails, string not assignable to number | undefined
anyPromise = d3Fetch.json(url);
anyPromise = d3Fetch.json(url, init);
carPromise = d3Fetch.json<Car>(url);
carPromise = d3Fetch.json<Car>(url, init);
stringPromise = d3Fetch.text(url);
stringPromise = d3Fetch.text(url, init);
docPromise = d3Fetch.html(url);
docPromise = d3Fetch.html(url, init);
docPromise = d3Fetch.svg(url);
docPromise = d3Fetch.svg(url, init);
let xmlDocPromise: Promise<XMLDocument>;
xmlDocPromise = d3Fetch.xml(url);
xmlDocPromise = d3Fetch.xml(url, init);
// ----------------------------------------------------------------------------
// DSV file format
// ----------------------------------------------------------------------------
let rawPromise: Promise<DSVParsedArray<DSVRowString>>;
let rawPromiseHeader: Promise<DSVParsedArray<DSVRowString<Headers>>>;
let parsedPromise: Promise<DSVParsedArray<Car>>;
declare const parseRowString: (rawRow: DSVRowString, index: number, columns: string[]) => Car | undefined | null;
const parseRow = (d: DSVRowString<Headers>, index: number, columns: Headers[]): Car | undefined | null => {
const item: string | undefined = d[columns[0]];
const car = d.Make === 'Ford' ? null :
{
year: new Date(+d.Make!, 0, 1),
make: d.Make!,
model: d.Model!,
length: +d.Length!,
};
return index % 2 === 0 ? undefined : car;
};
const parseRowSimple = (d: DSVRaw<Car>) => {
return {
year: new Date(+d.make!, 0, 1),
make: d.make!,
model: d.model!,
length: +d.length!,
};
};
// CSV
rawPromise = d3Fetch.csv(url);
rawPromise = d3Fetch.csv(url, init);
rawPromiseHeader = d3Fetch.csv<Headers>(url);
rawPromiseHeader = d3Fetch.csv<Headers>(url, init);
parsedPromise = d3Fetch.csv<Car>(url, parseRowString);
parsedPromise = d3Fetch.csv<Car>(url, init, parseRowString);
parsedPromise = d3Fetch.csv<Car, Headers>(url, parseRow);
parsedPromise = d3Fetch.csv<Car, Headers>(url, init, parseRow);
parsedPromise = d3Fetch.csv(url, parseRow);
parsedPromise = d3Fetch.csv(url, init, parseRow);
parsedPromise = d3Fetch.csv(url, parseRowSimple);
anyPromise = d3Fetch.csv(url, (d: DSVRaw<Car>) => map.set(d.model!, +d.year!));
// DSV
rawPromise = d3Fetch.dsv("|", url);
rawPromise = d3Fetch.dsv("|", url, init);
rawPromiseHeader = d3Fetch.dsv<Headers>("|", url);
rawPromiseHeader = d3Fetch.dsv<Headers>("|", url, init);
parsedPromise = d3Fetch.dsv<Car>("|", url, parseRowString);
parsedPromise = d3Fetch.dsv<Car>("|", url, init, parseRowString);
parsedPromise = d3Fetch.dsv<Car, Headers>("|", url, parseRow);
parsedPromise = d3Fetch.dsv<Car, Headers>("|", url, init, parseRow);
parsedPromise = d3Fetch.dsv("|", url, parseRow);
parsedPromise = d3Fetch.dsv("|", url, init, parseRow);
parsedPromise = d3Fetch.dsv("|", url, parseRowSimple);
anyPromise = d3Fetch.dsv("|", url, (d: DSVRaw<Car>) => map.set(d.model!, +d.year!));
// TSV
rawPromise = d3Fetch.tsv(url);
rawPromise = d3Fetch.tsv(url, init);
rawPromiseHeader = d3Fetch.tsv<Headers>(url);
rawPromiseHeader = d3Fetch.tsv<Headers>(url, init);
parsedPromise = d3Fetch.tsv<Car>(url, parseRowString);
parsedPromise = d3Fetch.tsv<Car>(url, init, parseRowString);
parsedPromise = d3Fetch.tsv<Car, Headers>(url, parseRow);
parsedPromise = d3Fetch.tsv<Car, Headers>(url, init, parseRow);
parsedPromise = d3Fetch.tsv(url, parseRow);
parsedPromise = d3Fetch.tsv(url, init, parseRow);
parsedPromise = d3Fetch.tsv(url, parseRowSimple);
anyPromise = d3Fetch.csv(url, (d: DSVRaw<Car>) => map.set(d.model!, +d.year!));
+42 -29
View File
@@ -1,12 +1,13 @@
// Type definitions for d3-fetch 1.1
// Project: https://d3js.org/d3-fetch/
// Definitions by: Hugues Stefanski <https://github.com/ledragon>
// denisname <https://github.com/denisname>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// Last module patch version validated against: 1.1.0
import { DSVParsedArray, DSVRowString } from 'd3-dsv';
import { DSVParsedArray, DSVRowArray, DSVRowString } from "d3-dsv";
/**
* Fetches the binary file at the specified input URL and returns it as a Promise of a Blob.
@@ -33,13 +34,15 @@ export function buffer(url: string, init?: RequestInit): Promise<ArrayBuffer>;
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* The generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function csv(
export function csv<Columns extends string>(
url: string,
init?: RequestInit,
): Promise<DSVParsedArray<DSVRowString>>;
init?: RequestInit
): Promise<DSVRowArray<Columns>>;
/**
* Fetches the CSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
@@ -47,7 +50,8 @@ export function csv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.csvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
* The first generic parameter describes the type of the object representation of a parsed row.
* The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -55,9 +59,9 @@ export function csv(
* the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function csv<ParsedRow extends object>(
export function csv<ParsedRow extends object, Columns extends string = string>(
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
* Fetches the CSV file at the specified input URL and returns
@@ -68,7 +72,8 @@ export function csv<ParsedRow extends object>(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.csvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
* The first generic parameter describes the type of the object representation of a parsed row.
* The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param init An request initialization object.
@@ -77,10 +82,10 @@ export function csv<ParsedRow extends object>(
* the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function csv<ParsedRow extends object>(
export function csv<ParsedRow extends object, Columns extends string = string>(
url: string,
init: RequestInit,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
@@ -90,15 +95,17 @@ export function csv<ParsedRow extends object>(
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* The generic parameter describes the column names as a union of string literal types.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function dsv(
export function dsv<Columns extends string>(
delimiter: string,
url: string,
init?: RequestInit,
): Promise<DSVParsedArray<DSVRowString>>;
init?: RequestInit
): Promise<DSVRowArray<Columns>>;
/**
* Fetches the DSV file with the specified delimiter character at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
@@ -106,7 +113,8 @@ export function dsv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.parse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
* The first generic parameter describes the type of the object representation of a parsed row.
* The second generic parameter describes the column names as a union of string literal types.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
@@ -115,10 +123,10 @@ export function dsv(
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function dsv<ParsedRow extends object>(
export function dsv<ParsedRow extends object, Columns extends string = string>(
delimiter: string,
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
* Fetches the DSV file with the specified delimiter character at the specified input URL and returns
@@ -129,7 +137,8 @@ export function dsv<ParsedRow extends object>(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.parse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
* The first generic parameter describes the type of the object representation of a parsed row.
* The second generic parameter describes the column names as a union of string literal types.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
@@ -139,11 +148,11 @@ export function dsv<ParsedRow extends object>(
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function dsv<ParsedRow extends object>(
export function dsv<ParsedRow extends object, Columns extends string = string>(
delimiter: string,
url: string,
init: RequestInit,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
@@ -164,7 +173,7 @@ export function html(url: string, init?: RequestInit): Promise<Document>;
* @param url A valid URL string.
* @param init An optional object of image properties to set.
*/
export function image(url: string, init?: {[key: string]: any}): Promise<HTMLImageElement>;
export function image(url: string, init?: Partial<HTMLImageElement>): Promise<HTMLImageElement>;
/**
* Fetches the json file at the specified input URL and returns it as a Promise of a parsed JSON object.
@@ -204,13 +213,15 @@ export function text(url: string, init?: RequestInit): Promise<string>;
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* The generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function tsv(
export function tsv<Columns extends string>(
url: string,
init?: RequestInit,
): Promise<DSVParsedArray<DSVRowString>>;
init?: RequestInit
): Promise<DSVRowArray<Columns>>;
/**
* Fetches the TSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row
@@ -219,7 +230,8 @@ export function tsv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.tsvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
* The first generic parameter describes the type of the object representation of a parsed row.
* The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -227,9 +239,9 @@ export function tsv(
* the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function tsv<ParsedRow extends object>(
export function tsv<ParsedRow extends object, Columns extends string = string>(
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
* Fetches the TSV file at the specified input URL and returns
@@ -240,7 +252,8 @@ export function tsv<ParsedRow extends object>(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.tsvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
* The first generic parameter describes the type of the object representation of a parsed row.
* The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param init An request initialization object.
@@ -249,10 +262,10 @@ export function tsv<ParsedRow extends object>(
* the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function tsv<ParsedRow extends object>(
export function tsv<ParsedRow extends object, Columns extends string = string>(
url: string,
init: RequestInit,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
row: (rawRow: DSVRowString<Columns>, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
+25
View File
@@ -47,6 +47,7 @@ import {
Region,
registerRootComponent,
ScreenOrientation,
SecureStore,
Svg,
Updates
} from 'expo';
@@ -484,6 +485,30 @@ async () => {
isString(queryParams2['y'] || '');
};
// #region securestore
async () => {
await SecureStore.setItemAsync('some-key', 'some-val', {
keychainService: "some-service",
keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
});
const result = await SecureStore.getItemAsync('some-key', { keychainService: "some-service" });
if (result != null) {
result.slice() === 'some-val';
}
await SecureStore.deleteItemAsync('some-key', { keychainService: "some-service" });
};
const allSecureStoreKeychainAccessibleValues: number[] = [
SecureStore.WHEN_UNLOCKED,
SecureStore.AFTER_FIRST_UNLOCK,
SecureStore.ALWAYS,
SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
SecureStore.ALWAYS_THIS_DEVICE_ONLY,
];
// #endregion
() => (
<Svg width={100} height={50}>
<Svg.Rect
+13 -1
View File
@@ -14,6 +14,7 @@
// Levan Basharuli <https://github.com/levansuper>
// Pavel Ihm <https://github.com/ihmpavel>
// Bartosz Dotryw <https://github.com/burtek>
// Jason Killian <https://github.com/jkillian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -2301,12 +2302,23 @@ export namespace ScreenOrientation {
export namespace SecureStore {
interface SecureStoreOptions {
keychainService?: string;
}
interface SecureStoreSetOptions extends SecureStoreOptions {
keychainAccessible?: number;
}
function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise<void>;
function setItemAsync(key: string, value: string, options?: SecureStoreSetOptions): Promise<void>;
function getItemAsync(key: string, options?: SecureStoreOptions): Promise<string | null>;
function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise<void>;
const WHEN_UNLOCKED: number;
const AFTER_FIRST_UNLOCK: number;
const ALWAYS: number;
const WHEN_UNLOCKED_THIS_DEVICE_ONLY: number;
const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: number;
const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: number;
const ALWAYS_THIS_DEVICE_ONLY: number;
}
/**
-7
View File
@@ -58,10 +58,3 @@ declare namespace jwt {
constructor(code: ErrorCode, error: { message: string });
}
}
declare global {
namespace Express {
export interface Request {
user?: any
}
}
}
@@ -3,7 +3,19 @@ import RateLimit = require("express-rate-limit");
const apiLimiter = new RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
delayMs: 0 // disabled
headers: false,
skipFailedRequests: false,
skipSuccessfulRequests: true,
});
const apiLimiterWithMaxFn = new RateLimit({
windowMs: 15 * 60 * 1000,
max: () => 5,
});
const apiLimiterWithMaxPromiseFn = new RateLimit({
windowMs: 15 * 60 * 1000,
max: () => Promise.resolve(5),
});
const apiLimiterWithMessageObject = new RateLimit({
@@ -17,8 +29,6 @@ const apiLimiterWithMessageObject = new RateLimit({
const createAccountLimiter = new RateLimit({
windowMs: 60 * 60 * 1000, // 1 hour window
delayAfter: 1, // begin slowing down responses after the first request
delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request
max: 5, // start blocking after 5 requests
message: "Too many accounts created from this IP, please try again after an hour",
handler: (req, _, next) => next(new Error(`TooManyRequests: ${req.ip}`))
+72 -9
View File
@@ -1,6 +1,8 @@
// Type definitions for express-rate-limit 2.9
// Type definitions for express-rate-limit 3.3
// Project: https://github.com/nfriedly/express-rate-limit
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>, makepost <https://github.com/makepost>
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// makepost <https://github.com/makepost>
// Jeremy Forsythe <https://github.com/jdforsythe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -21,19 +23,80 @@ declare namespace RateLimit {
[key: string]: any;
}
type MaxValueFn = () => number | Promise<number>;
interface Options {
delayAfter?: number;
delayMs?: number;
/**
* The funciton to handle requests once `max` is exceeded. It receives the request and response objects.
* The "next" param is available if you need to pass to the next middleware. The `req.rateLimit` object
* has `limit`, `current`, and `remaining` number of requests, and if the store provides it, a `resetTime`
* Date object.
* Default: `(req, res, next) => res.status(options.statusCode).send(options.message)`
*/
handler?(req: express.Request, res: express.Response, next: express.NextFunction): any;
/**
* Enable headers for request limit (`X-RateLimit-Limit`) and current usage (`X-RateLimit-Remaining`) on all
* responses andtime to wait before retrying (`Retry-After`) when `max` is exceeded. Defaults to `true`.
*/
headers?: boolean;
/**
* Function used to generate keys. Defaults to using `req.ip`.
* Default: `(req, res) => req.ip`
*/
keyGenerator?(req: express.Request, res: express.Response): string;
max?: number;
/**
* Max number of connections during `windowMs` before sending a 429 response. May be a `number` or
* a function that returns a `number` or a `Promise<number>`. Defaults to `5`. Set to `0` to disable.
*/
max?: number | MaxValueFn;
/**
* Error message sent to user when `max` is exceeded. May be a `string`, JSON object, or any other value
* that Express's `req.send()` supports. Defaults to `'Too many requests, please try again later.'`.
*/
message?: string | Buffer | Message;
skip?(req: express.Request, res: express.Response): boolean;
skipFailedRequests?: boolean;
statusCode?: number;
store?: Store;
/**
* Function that is called the first time `max` is exceeded. The `req.rateLimit` object has `limit`, `current`,
* and `remaining` number of requests and, if the store provides it, a `resetTime` Date object. Default is
* an empty function.
* Default: `(req, res, opts) => {}`
*/
onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void;
/**
* Function used to skip requests. Returning `true` from the function will skip limiting for that request. Defaults to
* always `false` (count all requests).
* Default: `(req, res) => false`
*/
skip?(req: express.Request, res: express.Response): boolean;
/**
* When set to `true`, failed requests (status >= 400, request canceled or errored) won't be counted. Defaults to `false`.
*/
skipFailedRequests?: boolean;
/**
* When set to `true`, successful requests (status < 400) won't be counted. Defaults to `false`.
*/
skipSuccessfulRequests?: boolean;
/**
* HTTP status code returned when `max` is exceeded. Defaults to `429`.
*/
statusCode?: number;
/**
* The storage to use when persisting rate limit attempts.
*/
store?: Store;
/**
* How long in milliseconds to keep records of requests in memory. Defaults to `60000` (1 minute).
*/
windowMs?: number;
}
}
@@ -0,0 +1,39 @@
import RateLimit = require("express-rate-limit");
const apiLimiter = new RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
delayMs: 0 // disabled
});
const apiLimiterWithMessageObject = new RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
message: {
status: 429,
message: 'To many requests, try again later'
}
});
const createAccountLimiter = new RateLimit({
windowMs: 60 * 60 * 1000, // 1 hour window
delayAfter: 1, // begin slowing down responses after the first request
delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request
max: 5, // start blocking after 5 requests
message: "Too many accounts created from this IP, please try again after an hour",
handler: (req, _, next) => next(new Error(`TooManyRequests: ${req.ip}`))
});
const callbackWithFewerParams = new RateLimit({
handler: (req, res) => res.status(429).json(`TooManyRequests: ${req.ip}`)
});
class SomeStore implements RateLimit.Store {
incr(key: string, cb: RateLimit.StoreIncrementCallback) { }
decrement(key: string) { }
resetKey(key: string) { }
}
const limiterWithStore = new RateLimit({
store: new SomeStore()
});
+42
View File
@@ -0,0 +1,42 @@
// Type definitions for express-rate-limit 2.9
// Project: https://github.com/nfriedly/express-rate-limit
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>, makepost <https://github.com/makepost>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import express = require("express");
declare namespace RateLimit {
type StoreIncrementCallback = (err?: {}, hits?: number) => void;
interface Store {
incr(key: string, cb: StoreIncrementCallback): void;
decrement(key: string): void;
resetKey(key: string): void;
}
interface Message {
status: number;
message: string;
[key: string]: any;
}
interface Options {
delayAfter?: number;
delayMs?: number;
handler?(req: express.Request, res: express.Response, next: express.NextFunction): any;
headers?: boolean;
keyGenerator?(req: express.Request, res: express.Response): string;
max?: number;
message?: string | Buffer | Message;
skip?(req: express.Request, res: express.Response): boolean;
skipFailedRequests?: boolean;
statusCode?: number;
store?: Store;
onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void;
windowMs?: number;
}
}
declare var RateLimit: new (options: RateLimit.Options) => express.RequestHandler;
export = RateLimit;
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"express-rate-limit": ["express-rate-limit/v2"]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"express-rate-limit-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,31 @@
import slowDown = require("express-slow-down");
const slowerAllDefaults = slowDown({});
const slowerWithOptions = slowDown({
windowMs: 15 * 60 * 1000, // 15 minutes,
delayAfter: 1,
delayMs: 0, // disabled
skipFailedRequests: false,
skipSuccessfulRequests: true,
});
const slowerWithCallbacks = slowDown({
keyGenerator: (req, res) => req.ip,
skip: (req, res) => false,
onLimitReached: (req, res, opts) => {
console.log(req.slowDown.current);
console.log(req.slowDown.remaining);
console.log(req.slowDown.limit);
},
});
class MockStore implements slowDown.Store {
incr(key: string, cb: slowDown.StoreIncrementCallback) { }
decrement(key: string) { }
resetKey(key: string) { }
}
const slowerWithStore = slowDown({
store: new MockStore()
});
+111
View File
@@ -0,0 +1,111 @@
// Type definitions for express-slow-down 1.1
// Project: https://github.com/nfriedly/express-slow-down
// Definitions by: Jeremy Forsythe <https://github.com/jdforsythe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import express = require("express");
declare namespace SlowDown {
type StoreIncrementCallback = (err?: {}, hits?: number) => void;
interface SlowDownRequestAugmentation {
/**
* The `options.delayAfter` value
*/
limit: number;
/**
* The number of requests in the current window
*/
current: number;
/**
* the number of requests remaining before rate-limiting begins
*/
remaining: number;
/**
* When the window will reset, `current` will return to `0`, and `remaining` will return
* to limit. Represents milliseconds since epoch (compare to `Date.now()`). This field
* depends on store support. It will be `undefined` if the store does not provide the value.
*/
resetTime?: number;
/**
* Amount of delay imposed on current request in milliseconds
*/
delay: number;
}
/**
* Express Request with the added `slowDown` property
*/
interface RequestWithSlowDown extends express.Request {
slowDown: SlowDownRequestAugmentation;
}
interface Store {
incr(key: string, cb: StoreIncrementCallback): void;
decrement(key: string): void;
resetKey(key: string): void;
}
/**
* express-slow-down options
*/
interface Options {
/**
* How long to keep records of requests in memory. Defaults to `60000` (1 minute)
*/
windowMs?: number;
/**
* Max number of connections during `windowMs` before starting to delay responses.
* Defaults to `1`. Set to `0` to disable delaying.
*/
delayAfter?: number;
/**
* How long to delay the response, multiplied by `(number recent hits - delayAfter)`.
* Defaults to `1000` (1 second). Set to `0` to disable delaying.
*/
delayMs?: number;
/**
* When `true` failed requests (response status >= 400) won't be counted. Defaults to `false`.
*/
skipFailedRequests?: boolean;
/**
* When `true` successful requests (response status < 400) won't be counted. Defaults to `false`.
*/
skipSuccessfulRequests?: boolean;
/**
* Function used to generate keys. By default user IP address (`req.ip`) is used.
* Default: `(req, res) => req.ip`
*/
keyGenerator?(req: express.Request, res: express.Response): string;
/**
* Function used to skip requests. Returning `true` from the function will skip delaying for that request.
* Default: `(req, res) => false`
*/
skip?(req: express.Request, res: express.Response): boolean;
/**
* Function to execute the first time the limit is reached within `windowMs`.
* Default: `(req, res, opts) => {}`
*/
onLimitReached?(req: RequestWithSlowDown, res: express.Response, optionsUsed: Options): void;
/**
* The storage to use when persisting request attempts. By default, the MemoryStore is used.
*/
store?: Store;
}
}
declare function SlowDown(options: SlowDown.Options): express.RequestHandler;
export = SlowDown;
+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",
"express-slow-down-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+75 -11
View File
@@ -1,4 +1,4 @@
// Type definitions for WebExtension Development in FireFox 64.0
// Type definitions for WebExtension Development in FireFox 65.0
// Project: https://developer.mozilla.org/en-US/Add-ons/WebExtensions
// Definitions by: Jasmin Bom <https://github.com/jsmnbom>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -178,6 +178,8 @@ declare namespace browser._manifest {
alternate_urls?: string[];
/** @deprecated Unsupported on Firefox. */
prepopulated_id?: number;
/** Encoding of the search term. */
encoding?: string;
/** Sets the default engine to a built-in engine only. */
is_default?: boolean;
/**
@@ -455,14 +457,17 @@ declare namespace browser._manifest {
interface ThemeType {
images?: {
additional_backgrounds?: ImageDataOrExtensionURL[];
/** @deprecated Please use _theme.images.theme_frame_, this alias will be removed in Firefox 69. */
headerURL?: ImageDataOrExtensionURL;
theme_frame?: ImageDataOrExtensionURL;
};
colors?: {
tab_selected?: ThemeColor;
/** @deprecated Please use _theme.colors.frame_, this alias will be removed in Firefox 69. */
accentcolor?: ThemeColor;
frame?: ThemeColor;
frame_inactive?: ThemeColor;
/** @deprecated Please use _theme.colors.tab_background_text_, this alias will be removed in Firefox 69. */
textcolor?: ThemeColor;
tab_background_text?: ThemeColor;
tab_background_separator?: ThemeColor;
@@ -470,6 +475,7 @@ declare namespace browser._manifest {
tab_text?: ThemeColor;
tab_line?: ThemeColor;
toolbar?: ThemeColor;
/** @deprecated Please use _theme.colors.bookmark_text_, this alias will be removed in Firefox 69. */
toolbar_text?: ThemeColor;
bookmark_text?: ThemeColor;
toolbar_field?: ThemeColor;
@@ -3535,11 +3541,6 @@ declare namespace browser.userScripts {
unregister(): Promise<any>;
}
/** A set of API methods provided by the extensions to its userScripts */
interface ExportedAPIMethods {
[key: string]: (...args: any[]) => any;
}
/* userScripts functions */
/**
* Register a user script programmatically given its `userScripts.UserScriptOptions`, and resolves to a
@@ -3547,12 +3548,28 @@ declare namespace browser.userScripts {
*/
function register(userScriptOptions: UserScriptOptions): Promise<RegisteredUserScript>;
/* userScripts events */
/**
* Provides a set of custom API methods available to the registered userScripts
* Event called when a new userScript global has been created
*
* Allowed in: Content scripts only
*/
function setScriptAPIs(exportedAPIMethods: ExportedAPIMethods): void;
const onBeforeScript: WebExtEvent<(userScript: {
/** The userScript metadata (as set in userScripts.register) */
metadata: any;
/** The userScript global */
global: any;
/**
* Exports all the properties of a given plain object as userScript globals
* @param sourceObject A plain object whose properties are exported as userScript globals
*/
defineGlobals: (sourceObject: object) => void;
/**
* Convert a given value to make it accessible to the userScript code
* @param value A value to convert into an object accessible to the userScript
*/
export: (value: any) => any;
}) => void>;
}
/**
@@ -5570,16 +5587,24 @@ declare namespace browser.geckoProfiler {
| "stackwalk"
| "tasktracer"
| "threads"
| "trackopts";
| "trackopts"
| "jstracer";
type Supports = "windowLength";
/* geckoProfiler functions */
/** Starts the profiler with the specified settings. */
function start(settings: {
/**
* The size in bytes of the buffer used to store profiling data. A larger value allows capturing a profile that
* covers a greater amount of time.
* The maximum size in bytes of the buffer used to store profiling data. A larger value allows capturing a
* profile that covers a greater amount of time.
*/
bufferSize: number;
/**
* The length of the window of time that's kept in the buffer. Any collected samples are discarded as soon as
* they are older than the number of seconds specified in this setting. Zero means no duration restriction.
*/
windowLength?: number;
/**
* Interval in milliseconds between samples of profiling data. A smaller value will increase the detail of the
* profiles captured.
@@ -5821,6 +5846,8 @@ declare namespace browser.contextMenus {
* context where there is no current page, such as in a launcher context menu.
*/
pageUrl?: string;
/** The id of the frame of the element where the context menu was clicked. */
frameId?: number;
/** The URL of the frame of the element where the context menu was clicked, if it was in a frame. */
frameUrl?: string;
/** The text for the context selection, if any. */
@@ -6100,6 +6127,8 @@ declare namespace browser.menus {
* context where there is no current page, such as in a launcher context menu.
*/
pageUrl?: string;
/** The id of the frame of the element where the context menu was clicked. */
frameId?: number;
/** The URL of the frame of the element where the context menu was clicked, if it was in a frame. */
frameUrl?: string;
/** The text for the context selection, if any. */
@@ -6939,6 +6968,8 @@ declare namespace browser.tabs {
sharingState?: SharingState;
/** Whether the tab is drawing attention. */
attention?: boolean;
/** The ID of this tab's successor, if any; `tabs.TAB_ID_NONE` otherwise. */
successorTabId?: number;
}
/**
@@ -7320,6 +7351,10 @@ declare namespace browser.tabs {
openerTabId?: number;
/** Whether the load should replace the current history entry for the tab. */
loadReplace?: boolean;
/**
* The ID of this tab's successor. If specified, the successor tab must be in the same window as this tab.
*/
successorTabId?: number;
}): Promise<Tab | undefined>;
/**
* Modifies the properties of a tab. Properties that are not specified in `updateProperties` are not modified.
@@ -7349,6 +7384,10 @@ declare namespace browser.tabs {
openerTabId?: number;
/** Whether the load should replace the current history entry for the tab. */
loadReplace?: boolean;
/**
* The ID of this tab's successor. If specified, the successor tab must be in the same window as this tab.
*/
successorTabId?: number;
}): Promise<Tab | undefined>;
/**
@@ -7517,6 +7556,29 @@ declare namespace browser.tabs {
*/
function hide(tabIds: number | number[]): Promise<number[]>;
/**
* Removes an array of tabs from their lines of succession and prepends or appends them in a chain to another tab.
* @param tabIds An array of tab IDs to move in the line of succession. For each tab in the array, the tab's
* current predecessors will have their successor set to the tab's current successor, and each tab will then be
* set to be the successor of the previous tab in the array. Any tabs not in the same window as the tab
* indicated by the second argument (or the first tab in the array, if no second argument) will be skipped.
* @param [tabId] The ID of a tab to set as the successor of the last tab in the array, or `tabs.TAB_ID_NONE` to
* leave the last tab without a successor. If options.append is true, then this tab is made the predecessor of
* the first tab in the array instead.
*/
function moveInSuccession(tabIds: number[], tabId?: number, options?: {
/** Whether to move the tabs before (false) or after (true) tabId in the succession. Defaults to false. */
append?: boolean;
/**
* Whether to link up the current predecessors or successor (depending on options.append) of tabId to the other
* side of the chain after it is prepended or appended. If true, one of the following happens: if
* options.append is false, the first tab in the array is set as the successor of any current predecessors of
* tabId; if options.append is true, the current successor of tabId is set as the successor of the last tab in
* the array. Defaults to false.
*/
insert?: boolean;
}): Promise<any>;
/* tabs events */
/**
* Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired, but you can
@@ -7571,6 +7633,8 @@ declare namespace browser.tabs {
const onActivated: WebExtEvent<(activeInfo: {
/** The ID of the tab that has become active. */
tabId: number;
/** The ID of the tab that was previously active, if that tab is still open. */
previousTabId?: number;
/** The ID of the window the active tab changed inside of. */
windowId: number;
}) => void>;
@@ -1,4 +1,4 @@
// Type definitions for Google Apps Script 2018-12-26
// Type definitions for Google Apps Script 2019-01-06
// Project: https://developers.google.com/apps-script/
// Definitions by: motemen <https://github.com/motemen/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -50,6 +50,8 @@ declare namespace GoogleAppsScript {
FieldType: typeof FieldType;
getConfig(): Config;
getFields(): Fields;
newDebugError(): DebugError;
newUserError(): UserError;
}
/**
@@ -83,6 +85,21 @@ declare namespace GoogleAppsScript {
createCommunityConnector(): CommunityConnector;
}
/**
* An error that is only visible to admins of the connector.
*
* var cc = DataStudioApp.createCommunityConnector();
*
* cc.newDebugError()
* .setText("This is the debug error text.")
* .throwException();
*/
export interface DebugError {
printJson(): string;
setText(text: string): DebugError;
throwException(): void;
}
/**
* Contains field-related data. Its properties determine how the field is used in Data Studio.
*
@@ -295,6 +312,23 @@ declare namespace GoogleAppsScript {
setPlaceholder(placeholder: string): TextInput;
}
/**
* An error that is shown to users of the connector.
*
* var cc = DataStudioApp.createCommunityConnector();
*
* cc.newUserError()
* .setText("This is the debug error text.")
* .setDebugText("This text is only shown to admins.")
* .throwException();
*/
export interface UserError {
printJson(): string;
setDebugText(text: string): UserError;
setText(text: string): UserError;
throwException(): void;
}
}
}
+21 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Google Apps Script 2018-12-26
// Type definitions for Google Apps Script 2019-01-06
// Project: https://developers.google.com/apps-script/
// Definitions by: motemen <https://github.com/motemen/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -322,6 +322,8 @@ declare namespace GoogleAppsScript {
insertTable(numRows: Integer, numColumns: Integer): Table;
insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table;
insertTable(table: Table): Table;
insertTextBox(text: string): Shape;
insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape;
insertVideo(videoUrl: string): Video;
insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video;
insertVideo(video: Video): Video;
@@ -576,6 +578,8 @@ declare namespace GoogleAppsScript {
insertTable(numRows: Integer, numColumns: Integer): Table;
insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table;
insertTable(table: Table): Table;
insertTextBox(text: string): Shape;
insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape;
insertVideo(videoUrl: string): Video;
insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video;
insertVideo(video: Video): Video;
@@ -682,6 +686,8 @@ declare namespace GoogleAppsScript {
insertTable(numRows: Integer, numColumns: Integer): Table;
insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table;
insertTable(table: Table): Table;
insertTextBox(text: string): Shape;
insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape;
insertVideo(videoUrl: string): Video;
insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video;
insertVideo(video: Video): Video;
@@ -880,6 +886,7 @@ declare namespace GoogleAppsScript {
appendSlide(layout: Layout): Slide;
appendSlide(predefinedLayout: PredefinedLayout): Slide;
appendSlide(slide: Slide): Slide;
appendSlide(slide: Slide, linkingMode: SlideLinkingMode): Slide;
getEditors(): Base.User[];
getId(): string;
getLayouts(): Layout[];
@@ -900,6 +907,7 @@ declare namespace GoogleAppsScript {
insertSlide(insertionIndex: Integer, layout: Layout): Slide;
insertSlide(insertionIndex: Integer, predefinedLayout: PredefinedLayout): Slide;
insertSlide(insertionIndex: Integer, slide: Slide): Slide;
insertSlide(insertionIndex: Integer, slide: Slide, linkingMode: SlideLinkingMode): Slide;
removeEditor(emailAddress: string): Presentation;
removeEditor(user: Base.User): Presentation;
removeViewer(emailAddress: string): Presentation;
@@ -1102,6 +1110,9 @@ declare namespace GoogleAppsScript {
getPlaceholders(): PageElement[];
getShapes(): Shape[];
getSheetsCharts(): SheetsChart[];
getSlideLinkingMode(): SlideLinkingMode;
getSourcePresentationId(): string;
getSourceSlideObjectId(): string;
getTables(): Table[];
getVideos(): Video[];
getWordArts(): WordArt[];
@@ -1127,17 +1138,26 @@ declare namespace GoogleAppsScript {
insertTable(numRows: Integer, numColumns: Integer): Table;
insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table;
insertTable(table: Table): Table;
insertTextBox(text: string): Shape;
insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape;
insertVideo(videoUrl: string): Video;
insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video;
insertVideo(video: Video): Video;
insertWordArt(wordArt: WordArt): WordArt;
move(index: Integer): void;
refreshSlide(): void;
remove(): void;
replaceAllText(findText: string, replaceText: string): Integer;
replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer;
selectAsCurrentPage(): void;
unlink(): void;
}
/**
* The mode of links between slides.
*/
export enum SlideLinkingMode { UNSUPPORTED, LINKED, NOT_LINKED }
/**
* The relative position of a Slide.
*/
+72
View File
@@ -286,3 +286,75 @@ got('http://todomvc.com', {
// Test got.TimeoutError.
got('http://todomvc.com', {timeout: 1}).catch((err) => err instanceof got.TimeoutError);
// Test hooks.
got('example.com', {
hooks: {
beforeRedirect: [
options => {
if (options.hostname === 'deadSite') {
options.hostname = 'fallbackSite';
}
}
]
}
});
got('example.com', {
hooks: {
beforeRetry: [
(options, error, retryCount) => {
if (error instanceof got.HTTPError && error.statusCode === 413) { // Payload too large
options.body = 'new body';
}
}
]
}
});
got('example.com', {
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) { // Unauthorized
const updatedOptions = {
headers: {
token: 'new token' // Refresh the access token
}
};
// Make a new retry
return retryWithMergedOptions(updatedOptions);
}
// No changes otherwise
return response;
}
]
}
});
// Test async hooks.
{
const doSomethingAsync = (): Promise<any> => {
throw new Error('unimplemented');
};
got('example.com', {
hooks: {
beforeRedirect: [
async () => {
await doSomethingAsync();
}
],
beforeRetry: [
async () => {
await doSomethingAsync();
}
],
afterResponse: [
async (response) => {
await doSomethingAsync();
return response;
}
]
}
});
}
+45 -7
View File
@@ -1,4 +1,4 @@
// Type definitions for got 9.2
// Type definitions for got 9.3
// Project: https://github.com/sindresorhus/got#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Linus Unnebäck <https://github.com/LinusU>
@@ -102,12 +102,50 @@ declare namespace got {
type GotUrl = string | https.RequestOptions | Url | URL;
type Hook<T> = (options: T) => any;
type Hooks<T> = Record<'beforeRequest', Array<Hook<T>>>;
/**
* Hooks allow modifications during the request lifecycle. Hook functions may be async and are
* run serially.
*
* @see https://github.com/sindresorhus/got#hooks
* @template Options Request options.
* @template Body Response body type.
*/
interface Hooks<Options, Body extends Buffer | string | object> {
beforeRequest?: Array<BeforeRequestHook<Options>>;
beforeRedirect?: Array<BeforeRedirectHook<Options>>;
beforeRetry?: Array<BeforeRetryHook<Options>>;
afterResponse?: Array<AfterResponseHook<Options, Body>>;
}
/**
* @param options Normalized request options.
*/
type BeforeRequestHook<Options> = (options: Options) => any;
/**
* @param options Normalized request options.
*/
type BeforeRedirectHook<Options> = (options: Options) => any;
/**
* @param options Normalized request options.
* @param error Request error.
* @param retryCount Number of retry.
*/
type BeforeRetryHook<Options> = (options: Options, error: GotError, retryCount: number) => any;
/**
* @param response Response object.
* @param retryWithMergedOptions Retries request with the updated options.
*/
type AfterResponseHook<Options, Body extends Buffer | string | object> = (
response: Response<Body>,
retryWithMergedOptions: (updateOptions: Options) => GotPromise<Body>
) => Response<Body> | Promise<Response<Body>>;
interface GotBodyOptions<E extends string | null> extends GotOptions<E> {
body?: string | Buffer | nodeStream.Readable;
hooks?: Hooks<GotBodyOptions<E>>;
hooks?: Hooks<GotBodyOptions<E>, string | Buffer | nodeStream.Readable>;
}
interface GotJSONOptions extends GotOptions<string | null> {
@@ -115,14 +153,14 @@ declare namespace got {
body?: object;
form?: boolean;
json: true;
hooks?: Hooks<GotJSONOptions>;
hooks?: Hooks<GotJSONOptions, object>;
}
interface GotFormOptions<E extends string | null> extends GotOptions<E> {
body?: {[key: string]: any};
body?: Record<string, any>;
form: true;
json?: boolean;
hooks?: Hooks<GotFormOptions<E>>;
hooks?: Hooks<GotFormOptions<E>, Record<string, any>>;
}
interface GotOptions<E extends string | null> extends InternalRequestOptions {
-17
View File
@@ -1,17 +0,0 @@
import * as hibp from 'hibp';
hibp
.search('someAccountOrEmail')
.then(data => {
if (data.breaches || data.pastes) {
// Bummer...
console.log(data);
} else {
// Phew! We're clear.
console.log('Good news — no pwnage found!');
}
})
.catch(err => {
// Something went wrong.
console.log(err.message);
});
-97
View File
@@ -1,97 +0,0 @@
// Type definitions for hibp 7.2
// Project: https://github.com/wkovacs64/hibp
// Definitions by: Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="node" />
export interface BreachOptions {
domain?: string;
truncate?: boolean;
}
export interface Breach {
Name: string;
Title: string;
Domain: string;
BreachDate: string;
AddedDate: string;
ModifiedDate: string;
PwnCount: number;
Description: string;
LogoPath: string;
DataClasses: string[];
IsVerified: boolean;
IsFabricated: boolean;
IsSensitive: boolean;
IsRetired: boolean;
IsSpamList: boolean;
}
export interface Paste {
Id: string;
Source: string;
Title: string;
Date: string;
EmailCount: number;
}
export interface Range {
suffix: string;
count: number;
}
/**
* Fetches data for a specific breach event.
*/
export function breach(breachName: string): Promise<Breach>;
/**
* Fetches breach data for a specific account.
*/
export function breachedAccount(account: string, options?: BreachOptions): Promise<Breach[]>;
/**
* Fetches all breach events in the system.
*/
export function breaches(options?: { domain?: string }): Promise<Breach[]>;
/**
* Fetches all data classes in the system.
*/
export function dataClasses(): Promise<string[]>;
/**
* Fetches paste data for a specific email address.
*/
export function pasteAccount(email: string): Promise<Paste[]>;
/**
* Fetches the number of times the the given password has been exposed in a breach (0 indicating no exposure).
* The password is given in plain text, but only the first 5 characters of its SHA-1 hash will be submitted to the API.
*/
export function pwnedPassword(password: string): Promise<number>;
/**
* Fetches the SHA-1 hash suffixes for the given 5-character SHA-1 hash prefix.
*
* When a password hash with the same first 5 characters is found in the Pwned Passwords repository,
* the API will respond with an HTTP 200 and include the suffix of every hash beginning with the specified prefix,
* followed by a count of how many times it appears in the data set.
*
* This function parses the response and returns a more structured format.
*/
export function pwnedPasswordRange(prefix: string): Promise<Range[]>;
/**
* Fetches all breaches and all pastes associated with the provided account (email address or username).
*
* Note that the remote API does not support querying pastes by username (only email addresses),
* so in the event the provided account is not a valid email address,
* only breach data is queried and the "pastes" field of the resulting object will always be null.
*
* This is exactly how searching via the current web interface behaves, which this convenience method is designed to mimic.
*
*/
export function search(account: string, options?: BreachOptions): Promise<{ breaches?: Breach[], pastes?: Paste[] }>;
+8 -1
View File
@@ -23,7 +23,14 @@ class pLoader extends Hls.DefaultConfig.loader {
if (Hls.isSupported()) {
const video = <HTMLVideoElement> document.getElementById('video');
const hls = new Hls({ pLoader, startFragPrefetch: true });
const hls = new Hls({
pLoader,
startFragPrefetch: true,
debug: {
log: (...args: any[]) => console.log(...args)
}
});
const version: string = Hls.version;
hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8');
hls.attachMedia(video);
+22 -3
View File
@@ -1,8 +1,9 @@
// Type definitions for hls.js 0.10
// Type definitions for hls.js 0.12
// Project: https://github.com/video-dev/hls.js
// Definitions by: John G. Gainfort, Jr. <https://github.com/jgainfort>
// Johan Brook <https://github.com/brookback>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.4
// Event Keys
type K_MEDIA_ATTACHING = "hlsMediaAttaching";
@@ -307,6 +308,16 @@ declare namespace Hls {
// interface SubtitleTracks {}
type CustomLogger = (...args: any[]) => void;
interface CustomLoggerObject {
warn?: CustomLogger;
info?: CustomLogger;
log?: CustomLogger;
debug?: CustomLogger;
error?: CustomLogger;
}
interface Config {
/**
* (default: false)
@@ -319,7 +330,7 @@ declare namespace Hls {
* setting config.debug = true; will turn on debug logs on JS console.
* a logger object could also be provided for custom logging: config.debug = customLogger;
*/
debug: boolean;
debug: boolean | CustomLoggerObject;
/**
* (default: true)
* if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event
@@ -475,6 +486,14 @@ declare namespace Hls {
* Android Google Chrome, etc. set this value to true.
*/
liveDurationInfinity: boolean;
/**
* (default: Infinity)
* Sets the maximum length of the buffer, in seconds, to keep during a live stream. Any video
* buffered past this time will be evicted. Infinity means no restriction on back buffer length;
* 0 keeps the minimum amount. The minimum amount is equal to the target duration of a segment
* to ensure that current playback is not interrupted.
*/
liveBackBufferLength: number;
/**
* (default: true)
* Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops.
+17 -14
View File
@@ -828,10 +828,12 @@ declare global {
ca: Array<string | Buffer>;
}
type MessagePayload = string | Record<string, any>;
/** Callback information for a passed message */
interface MessageCallbackInfo {
/** The original message payload */
message: string | object;
message: MessagePayload;
/** ID of this callback */
id: number;
// ???
@@ -839,14 +841,13 @@ declare global {
/** Timestamp of this message */
time: number;
}
type MessageCallback = (result?: any) => void;
/** A message being passed between adapter instances */
interface Message {
/** The command to be executed */
command: string;
/** The message payload */
message: string | object;
message: MessagePayload;
/** The source of this message */
from: string;
/** ID of this message */
@@ -1038,8 +1039,8 @@ declare global {
* @param command (optional) Command name of the target instance. Default: "send"
* @param message The message (e.g. params) to send.
*/
sendTo(instanceName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
sendTo(instanceName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
sendTo(instanceName: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void;
sendTo(instanceName: string, command: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void;
/**
* Sends a message to a specific instance or all instances of some specific adapter.
* @param instanceName The instance to send this message to.
@@ -1048,18 +1049,18 @@ declare global {
* @param command (optional) Command name of the target instance. Default: "send"
* @param message The message (e.g. params) to send.
*/
sendToAsync(instanceName: string, message: string | object): Promise<any>;
sendToAsync(instanceName: string, command: string, message: string | object): Promise<any>;
sendToAsync(instanceName: string, message: MessagePayload): Promise<Message | undefined>;
sendToAsync(instanceName: string, command: string, message: MessagePayload): Promise<Message | undefined>;
/**
* Sends a message to a specific host or all hosts.
*/
sendToHost(hostName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
sendToHost(hostName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void;
sendToHost(hostName: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void;
sendToHost(hostName: string, command: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void;
/**
* Sends a message to a specific host or all hosts.
*/
sendToHostAsync(hostName: string, message: string | object): Promise<any>;
sendToHostAsync(hostName: string, command: string, message: string | object): Promise<any>;
sendToHostAsync(hostName: string, message: MessagePayload): Promise<Message | undefined>;
sendToHostAsync(hostName: string, command: string, message: MessagePayload): Promise<Message | undefined>;
/** Convert ID to {device: D, channel: C, state: S} */
idToDCS(id: string): {
@@ -1125,9 +1126,9 @@ declare global {
getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: unknown, callback: GetObjectsCallback): void;
// tslint:enable:unified-signatures
/** Get foreign objects by pattern, by specific type and resolve their enums. */
getForeignObjectsAsync(pattern: string, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
getForeignObjectsAsync(pattern: string, type: ObjectType, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
getForeignObjectsAsync(pattern: string, type: ObjectType, enums: EnumList, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectCallback>>;
getForeignObjectsAsync(pattern: string, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectsCallback>>;
getForeignObjectsAsync(pattern: string, type: ObjectType, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectsCallback>>;
getForeignObjectsAsync(pattern: string, type: ObjectType, enums: EnumList, options?: unknown): Promise<CallbackReturnTypeOf<GetObjectsCallback>>;
/** Creates or overwrites an object (which might not belong to this adapter) in the object db */
setForeignObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void;
setForeignObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void;
@@ -1591,6 +1592,8 @@ declare global {
// TODO: Redefine callbacks as subclass of GenericCallback
type GenericCallback<T> = (err: string | null, result?: T) => void;
type MessageCallback = (response?: Message) => void;
type SetObjectCallback = (err: string | null, obj: { id: string }) => void;
type GetObjectCallback = (err: string | null, obj: ioBroker.Object | null | undefined) => void;
type GetEnumCallback = (err: string | null, enums: Record<string, Enum>, requestedEnum: string) => void;
+47 -1
View File
@@ -99,7 +99,8 @@ function messageHandler(msg: ioBroker.Message) {
msg.callback.time.toFixed();
msg.command.toLowerCase();
msg.from.toLowerCase();
msg.message.toString();
typeof msg.message === "object" && msg.message.anything;
typeof msg.message === "string" && msg.message.toLowerCase();
}
function unloadHandler(callback: ioBroker.EmptyCallback) {
@@ -170,6 +171,9 @@ adapter.getForeignObject("obj.id", (err, obj) => { });
adapter.getObjectAsync("obj.id").then(obj => obj._id.toLowerCase());
adapter.getForeignObjectAsync("obj.id").then(obj => obj._id.toLowerCase());
adapter.getForeignObjects("*", (err, objs) => objs["foo"]._id.toLowerCase());
adapter.getForeignObjectsAsync("*").then(objs => objs["foo"]._id.toLowerCase());
adapter.subscribeObjects("*");
adapter.subscribeStates("*");
adapter.subscribeForeignObjects("*");
@@ -195,3 +199,45 @@ switch (adapter.log.level) {
default:
assertNever(adapter.log.level);
}
adapter.sendTo("foo.0", "command", "message");
adapter.sendTo("foo.0", "message");
adapter.sendTo("foo.0", "command", {msg: "message"});
adapter.sendTo("foo.0", {msg: "message"});
function handleMessageResponse(response?: ioBroker.Message) {
if (!response) return;
response._id.toFixed();
response.callback.ack.valueOf();
response.callback.id.toFixed();
response.callback.message.toString();
response.callback.time.toFixed();
response.command.toLowerCase();
response.from.toLowerCase();
typeof response.message === "object" && response.message.anything;
typeof response.message === "string" && response.message.toLowerCase();
}
adapter.sendTo("foo.0", "command", "message", handleMessageResponse);
adapter.sendTo("foo.0", "message", handleMessageResponse);
adapter.sendTo("foo.0", "command", {msg: "message"}, handleMessageResponse);
adapter.sendTo("foo.0", {msg: "message"}, handleMessageResponse);
adapter.sendToAsync("foo.0", "command", "message").then(handleMessageResponse);
adapter.sendToAsync("foo.0", "message").then(handleMessageResponse);
adapter.sendToAsync("foo.0", "command", {msg: "message"}).then(handleMessageResponse);
adapter.sendToAsync("foo.0", {msg: "message"}).then(handleMessageResponse);
adapter.sendToHost("host-foo", "command", "message");
adapter.sendToHost("host-foo", "message");
adapter.sendToHost("host-foo", "command", {msg: "message"});
adapter.sendToHost("host-foo", {msg: "message"});
adapter.sendToHost("host-foo", "command", "message", handleMessageResponse);
adapter.sendToHost("host-foo", "message", handleMessageResponse);
adapter.sendToHost("host-foo", "command", {msg: "message"}, handleMessageResponse);
adapter.sendToHost("host-foo", {msg: "message"}, handleMessageResponse);
adapter.sendToHostAsync("host-foo", "command", "message").then(handleMessageResponse);
adapter.sendToHostAsync("host-foo", "message").then(handleMessageResponse);
adapter.sendToHostAsync("host-foo", "command", {msg: "message"}).then(handleMessageResponse);
adapter.sendToHostAsync("host-foo", {msg: "message"}).then(handleMessageResponse);
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for is-valid-path 0.1
// Project: https://github.com/jonschlinkert/is-valid-path
// Definitions by: Zlatko Andonovski <https://github.com/Goldsmith42>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function isValidPath(path?: string | null): boolean;
export = isValidPath;
@@ -0,0 +1,18 @@
// Tests are from the NPM README (https://www.npmjs.com/package/is-valid-path).
import isValid = require('is-valid-path');
isValid('abc.js');
isValid('abc/def/ghi.js');
isValid('foo.js');
isValid();
isValid(null);
isValid('!foo.js');
isValid('*.js');
isValid('**/abc.js');
isValid('abc/*.js');
isValid('abc/(aaa|bbb).js');
isValid('abc/[a-z].js');
isValid('abc/{a,b}.js');
isValid('abc/?.js');
+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",
"is-valid-path-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+14
View File
@@ -39,11 +39,15 @@ interface NodeRequire {
/**
* Returns the actual module instead of a mock, bypassing all checks on
* whether the module should receive a mock implementation or not.
*
* @deprecated Use `jest.requireActual` instead.
*/
requireActual(moduleName: string): any;
/**
* Returns a mock module instead of the actual module, bypassing all checks
* on whether the module should be required normally or not.
*
* @deprecated Use `jest.requireMock`instead.
*/
requireMock(moduleName: string): any;
}
@@ -127,6 +131,16 @@ declare namespace jest {
* Mocks a module with an auto-mocked version when it is being required.
*/
function mock(moduleName: string, factory?: any, options?: MockOptions): typeof jest;
/**
* Returns the actual module instead of a mock, bypassing all checks on
* whether the module should receive a mock implementation or not.
*/
function requireActual(moduleName: string): any;
/**
* Returns a mock module instead of the actual module, bypassing all checks
* on whether the module should be required normally or not.
*/
function requireMock(moduleName: string): any;
/**
* Resets the module registry - the cache of all required modules. This is
* useful to isolate modules where local state might conflict between tests.
+6
View File
@@ -251,6 +251,12 @@ jest
.useFakeTimers()
.useRealTimers();
// https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename
jest.requireActual("./thisReturnsTheActualModule");
// https://jestjs.io/docs/en/jest-object#jestrequiremockmodulename
jest.requireMock("./thisAlwaysReturnsTheMock");
/* Mocks and spies */
const mock1: jest.Mock = jest.fn();
+2 -2
View File
@@ -4,6 +4,7 @@
// Zoltan Ujvary <https://github.com/ujvzolee>
// Simon Colmer <https://github.com/workshop2>
// XtrimSystems <https://github.com/xtrimsystems>
// Marcin Obiedziński <https://github.com/marcinobiedz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference types="node"/>
@@ -111,11 +112,10 @@ export declare class Board {
io: any;
id: string;
repl: any;
repl: Repl;
isReady: boolean;
pins: Array<Pin>;
port: string;
inject: Repl;
on(event: string, cb: () => void): this;
on(event: "ready", cb: () => void): this;
+24 -24
View File
@@ -8,7 +8,7 @@ declare namespace __Combinatorics {
interface IGenerator<T> {
/**
* Returns the element or undefined if no more element is available.
* Returns the element or undefined if no more elements are available.
*/
next():T;
@@ -18,24 +18,24 @@ declare namespace __Combinatorics {
forEach(f:(item:T) => void):void;
/**
* All elements at once with function applied to each element.
* Returns an array that is the output of calling the callback function separately on each element.
*/
map<TResult>(f:(item:T) => TResult):TResult[];
/**
* Returns an array with elements that passes the filter function.
* Returns an array of elements that return `true` for the filter function.
*/
filter(predicate:(item:T) => boolean):T[];
/**
* All elements at once.
* Returns an array of all elements.
*/
toArray():T[];
/**
* Returns the number of elements to be generated which equals to generator.toArray().length
* but it is precalculated without actually generating elements.
* Handy when you prepare for large iteration.
* Returns the total number of elements to be generated. This equals the result of calling
* `generator.toArray().length` but it is precalculated without actually generating any elements.
* Handy when doing setup for a potentially long-running loop.
*/
length:number;
@@ -44,7 +44,7 @@ declare namespace __Combinatorics {
interface IPredictableGenerator<T> extends IGenerator<T> {
/**
* Returns the nth element (starting 0).
* Returns the nth element (indexed from 0).
*/
nth(n:number):T;
@@ -53,11 +53,10 @@ declare namespace __Combinatorics {
interface ICartesianProductGenerator<T> extends IPredictableGenerator<T> {
/**
* Arguments are coordinates in integer.
* Arguments can be out of bounds but it returns undefined in such cases.
* Arguments are integer coordinates.
* Arguments can be out of bounds but it returns `undefined` in such cases.
*/
get(...coordinates:number[]):T;
}
/**
@@ -76,46 +75,47 @@ declare namespace __Combinatorics {
function factorial(n:number):number;
/**
* Returns the factoradic representation of n in array, in least significant order.
* Returns the factoradic representation of `n` in an array, in
* least significant order.
* See http://en.wikipedia.org/wiki/Factorial_number_system
*/
function factoradic(n:number):number[];
/**
* Generates the power set of array.
* Generates the power set of `a`.
*/
function power<T>(a:T[]):IPredictableGenerator<T[]>;
/**
* Generates the combination of array with n elements.
* When n is ommited, the length of the array is used.
* Generates the combination of `a` with `n` elements.
* `n` defaults to the length of `a`.
*/
function combination<T>(a:T[], n?:number):IGenerator<T[]>;
/**
* Generates the combination of array with n elements, which
* Generates the combination of `a` with `n` elements, which
* also supports larger sets of elements.
* When n is ommited, the length of the array is used.
* Somewhat slower than combination()
* When `n` is ommited, the length of the array is used.
* Somewhat slower than `combination()`
*/
function bigCombination<T>(a:T[], n?:number):IGenerator<T[]>;
/**
* Generates the permutation of array with n elements.
* When n is ommited, the length of the array is used.
* Generates the permutation of `a` with `n` elements.
* `n` defaults to the length of `a`.
*/
function permutation<T>(a:T[], n?:number):IGenerator<T[]>;
/**
* Generates the permutation of the combination of n.
* Equivalent to permutation(combination(a)), but more efficient.
* Generates the permutation of the combination of `a`.
* Equivalent to `permutation(combination(a))`, but more efficient.
*/
function permutationCombination<T>(a:T[]):IGenerator<T[]>;
/**
* Generates n-digit "numbers" where each digit is an element in array.
* Generates `n`-digit "numbers" where each digit is an element in array.
* Note this "number" is in the least significant order.
* When n is ommited, the length of the array is used.
* `n` defaults to the length of `a`.
*/
function baseN<T>(a:T[], n?:number):IPredictableGenerator<T[]>;
+7 -5
View File
@@ -1,4 +1,4 @@
// Type definitions for KeyboardJS v2.4.1
// Type definitions for KeyboardJS v2.4.2
// Project: https://github.com/RobertWHurst/KeyboardJS
// Definitions by: Vincent Bortone <https://github.com/vbortone>,
// David Asmuth <https://github.com/piranha771>,
@@ -92,14 +92,16 @@ declare namespace keyboardjs {
/**
* Triggers a key press. Stays in pressed state until released.
* @param keyCombo String of keys to be pressed to execute 'pressed' callbacks.
* @param keyCombo String of keys or keyCode to be pressed to execute 'pressed' callbacks.
* @param event The KeyEvent, can be null.
*/
export function pressKey(keyCombo: string): void
export function pressKey(keyCombo: string | number, event?: KeyEvent): void;
/**
* Triggers a key release.
* @param keyCombo String of keys to be released to execute 'released' callbacks.
* @param keyCombo String of keys or keyCode to be released to execute 'released' callbacks.
* @param event The KeyEvent, can be null.
*/
export function releaseKey(keyCombo: string): void;
export function releaseKey(keyCombo: string | number, event?: KeyEvent): void;
/**
* Releases all keys.
*/
+33
View File
@@ -0,0 +1,33 @@
// Type definitions for @keyv/mysql 1.1
// Project: https://github.com/lukechilds/keyv-mysql
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
import { Store } from 'keyv';
import { EventEmitter } from 'events';
export = KeyvMysql;
declare class KeyvMysql extends EventEmitter implements Store<string | undefined> {
readonly ttlSupport: false;
namespace?: string;
constructor(uri?: string);
constructor(options?: KeyvMysql.Options); // tslint:disable-line:unified-signatures
get(key: string): Promise<string | undefined>;
set(key: string, value: string | undefined): Promise<any>;
delete(key: string): Promise<boolean>;
clear(): Promise<void>;
}
declare namespace KeyvMysql {
interface Options {
uri?: string;
table?: string;
keySize?: number;
}
}
+12
View File
@@ -0,0 +1,12 @@
import Keyv = require('keyv');
import KeyvMysql = require('@keyv/mysql');
new Keyv('mysql://user:pass@localhost:3306/dbname', { table: 'cache' });
new KeyvMysql('mysql://user:pass@localhost:3306/dbname');
new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' });
new KeyvMysql({ table: 'cache' });
new KeyvMysql({ keySize: 100 });
const mysql = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' });
new Keyv({ store: mysql });
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@keyv/mysql": [
"keyv__mysql"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"keyv__mysql-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -4
View File
@@ -140,7 +140,7 @@ interface KnockoutSubscribableStatic {
interface KnockoutSubscription {
/**
* Terminates a subscription
* Terminates a subscription
*/
dispose(): void;
}
@@ -213,9 +213,6 @@ interface KnockoutReadonlyComputed<T> extends KnockoutReadonlyObservable<T> {
interface KnockoutComputed<T> extends KnockoutReadonlyComputed<T>, KnockoutObservable<T>, KnockoutComputedFunctions<T> {
fn: KnockoutComputedFunctions<any>;
// It's possible for 'a' to be undefined, since the equalityComparer is run on the initial
// computation with undefined as the first argument. This is user-relevant for deferred computeds.
equalityComparer(a: T | undefined, b: T): boolean;
/**
* Manually disposes the computed observable, clearing all subscriptions to dependencies.
* This function is useful if you want to stop a computed observable from being updated or want to clean up memory for a
+12 -18
View File
@@ -19,12 +19,6 @@
import * as Koa from "koa";
declare module "koa" {
interface Context {
params: any;
}
}
declare namespace Router {
export interface IRouterOptions {
/**
@@ -61,11 +55,11 @@ declare namespace Router {
}
export interface IMiddleware {
(ctx: Router.IRouterContext, next: () => Promise<any>): any;
(ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise<any>): any;
}
export interface IParamMiddleware {
(param: string, ctx: Router.IRouterContext, next: () => Promise<any>): any;
(param: string, ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise<any>): any;
}
export interface IRouterAllowedMethodsOptions {
@@ -88,7 +82,7 @@ declare namespace Router {
sensitive?: boolean;
strict?: boolean;
}
export interface IUrlOptionsQuery {
query: object | string;
}
@@ -190,19 +184,19 @@ declare class Router {
*/
put(name: string, path: string | RegExp, ...middleware: Array<Router.IMiddleware>): Router;
put(path: string | RegExp | (string | RegExp)[], ...middleware: Array<Router.IMiddleware>): Router;
/**
* HTTP link method
*/
link(name: string, path: string | RegExp, ...middleware: Array<Router.IMiddleware>): Router;
link(path: string | RegExp | (string | RegExp)[], ...middleware: Array<Router.IMiddleware>): Router;
/**
* HTTP unlink method
*/
unlink(name: string, path: string | RegExp, ...middleware: Array<Router.IMiddleware>): Router;
unlink(path: string | RegExp | (string | RegExp)[], ...middleware: Array<Router.IMiddleware>): Router;
/**
* HTTP delete method
@@ -283,21 +277,21 @@ declare class Router {
/**
* Generate URL for route. Takes either map of named `params` or series of
* arguments (for regular expression routes)
*
*
* router = new Router();
* router.get('user', "/users/:id", ...
*
*
* router.url('user', { id: 3 });
* // => "/users/3"
*
*
* Query can be generated from third argument:
*
*
* router.url('user', { id: 3 }, { query: { limit: 1 } });
* // => "/users/3?limit=1"
*
*
* router.url('user', { id: 3 }, { query: "limit=1" });
* // => "/users/3?limit=1"
*
*
*/
url(name: string, params: any, options?: Router.IUrlOptionsQuery): string;
url(name: string, params: any, options?: Router.IUrlOptionsQuery): Error;
+5 -1
View File
@@ -1,7 +1,7 @@
import Koa = require("koa");
import Router = require("koa-router");
const app = new Koa();
const app = new Koa<{}, {}>();
const router = new Router({
prefix: "/users"
@@ -49,6 +49,10 @@ const match = router.match('/users/:id', 'GET');
let layer: Router.Layer
let layerOptions: Router.ILayerOptions
const mw: Router.IMiddleware = (ctx: Router.IRouterContext, next: () => Promise<any>) => {
ctx.body = "Ok";
};
app.use(router.routes());
app.use(router.allowedMethods());
+26 -2
View File
@@ -7,10 +7,12 @@
export * from 'libsodium-wrappers';
import {
Uint8ArrayOutputFormat,
StringOutputFormat,
KeyPair,
onetimeauth_state_address,
state_address,
StringKeyPair,
StringOutputFormat,
Uint8ArrayOutputFormat,
} from 'libsodium-wrappers';
export const crypto_auth_hmacsha256_BYTES: number;
@@ -77,6 +79,12 @@ export const crypto_stream_xchacha20_KEYBYTES: number;
export const crypto_stream_xchacha20_NONCEBYTES: number;
export const crypto_box_curve25519xchacha20poly1305_NONCEBYTES: number;
export const crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES: number;
export const crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES: number;
export function crypto_auth_hmacsha256(
message: string | Uint8Array,
key: Uint8Array,
@@ -113,6 +121,18 @@ export function crypto_auth_hmacsha512_keygen(outputFormat?: StringOutputFormat
export function crypto_auth_hmacsha512_verify(tag: Uint8Array, message: string | Uint8Array, key: Uint8Array): boolean;
export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): KeyPair;
export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: StringOutputFormat | null): StringKeyPair;
export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array;
export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat?: StringOutputFormat | null): string;
export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array;
export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: StringOutputFormat | null): string;
export function crypto_hash_sha256(
message: string | Uint8Array,
outputFormat?: Uint8ArrayOutputFormat | null,
@@ -240,6 +260,10 @@ export function crypto_sign_ed25519_sk_to_seed(
outputFormat?: StringOutputFormat | null,
): string;
export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat?: StringOutputFormat | null): string;
export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array;
export function crypto_stream_chacha20_ietf_xor(
input_message: string | Uint8Array,
nonce: Uint8Array,
+8 -8
View File
@@ -886,30 +886,30 @@ export function crypto_secretstream_xchacha20poly1305_keygen(outputFormat?: Uint
export function crypto_secretstream_xchacha20poly1305_keygen(outputFormat?: StringOutputFormat | null): string;
export function crypto_secretstream_xchacha20poly1305_pull(
state_address?: secretstream_xchacha20poly1305_state_address,
cipher?: string | Uint8Array,
state_address: secretstream_xchacha20poly1305_state_address,
cipher: string | Uint8Array,
ad?: string | Uint8Array | null,
outputFormat?: Uint8ArrayOutputFormat | null,
): { message: Uint8Array; tag: Uint8Array };
export function crypto_secretstream_xchacha20poly1305_pull(
state_address?: secretstream_xchacha20poly1305_state_address,
cipher?: string | Uint8Array,
state_address: secretstream_xchacha20poly1305_state_address,
cipher: string | Uint8Array,
ad?: string | Uint8Array | null,
outputFormat?: StringOutputFormat | null,
): { message: string; tag: Uint8Array };
export function crypto_secretstream_xchacha20poly1305_push(
state_address?: secretstream_xchacha20poly1305_state_address,
message_chunk?: string | Uint8Array,
state_address: secretstream_xchacha20poly1305_state_address,
message_chunk: string | Uint8Array,
ad?: string | Uint8Array | null,
tag?: number,
outputFormat?: Uint8ArrayOutputFormat | null,
): Uint8Array;
export function crypto_secretstream_xchacha20poly1305_push(
state_address?: secretstream_xchacha20poly1305_state_address,
message_chunk?: string | Uint8Array,
state_address: secretstream_xchacha20poly1305_state_address,
message_chunk: string | Uint8Array,
ad?: string | Uint8Array | null,
tag?: number,
outputFormat?: StringOutputFormat | null,
+7 -4
View File
@@ -1,8 +1,11 @@
// Type definitions for linkifyjs 2.1
// Project: https://github.com/SoapBox/linkifyjs#readme
// Definitions by: Sean Zhu <https://github.com/szhu>
// Ovidiu Bute <https://github.com/ovidiubute>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// TypeScript Version: 2.8
import * as React from "react";
export type PossiblyFuncOfHrefAndType<T> =
| T
@@ -26,9 +29,9 @@ export interface LinkifyOptions {
* Also accepts a function that takes the unformatted href, the link type
* (e.g., 'url', 'email', etc.) and returns the object.
*/
attributes?: PossiblyFuncOfHrefAndType<{
[attrName: string]: string;
}> | null;
attributes?: PossiblyFuncOfHrefAndType<
React.AnchorHTMLAttributes<HTMLAnchorElement>
> | null;
/**
* className
-141
View File
@@ -1,141 +0,0 @@
import linkifyHtml from "linkifyjs/html";
// From the docs here: https://soapbox.github.io/linkifyjs/docs/options.html
/* attributes */
linkifyHtml("github.com", {
attributes: {
rel: "nofollow"
}
});
/* className */
linkifyHtml("github.com", {
className: "new-link--url"
});
linkifyHtml("github.com", {
className(href, type) {
return "new-link--" + type;
}
});
linkifyHtml("github.com", {
className: {
url: "new-link--url",
email(href: string) {
return "new-link--email";
}
}
});
/* events */
linkifyHtml("", {
events: {
click(e) {
alert("Link clicked!");
},
mouseover(e) {
alert("Link hovered!");
}
}
});
/* defaultProtocol */
/* format */
linkifyHtml("", {
format(value, type) {
if (type === "url" && value.length > 50) {
value = value.slice(0, 50) + "…";
}
return value;
}
});
linkifyHtml("", {
format: {
url(value) {
return value.length > 50 ? value.slice(0, 50) + "…" : value;
}
}
});
/* formatHref */
linkifyHtml("This site is #rad", {
formatHref(href, type) {
if (type === "hashtag") {
href = "https://twitter.com/hashtag/" + href.substring(1);
}
return href;
}
});
linkifyHtml("Hey @dhh, check out issue #23", {
formatHref: {
mention(href) {
return "https://github.com" + href;
},
ticket(href) {
return (
"https://github.com/SoapBox/linkifyjs/issues/" +
href.substring(1)
);
}
}
});
/* ignoreTags */
linkifyHtml(
// tslint:disable-next-line:prefer-template
'Please ignore <script>var a = {}; a.com = "Hi";</script> \n' +
"but do <span>b.ca</span>",
{
ignoreTags: ["script", "style"]
}
);
/* nl2br */
/* tagName */
linkifyHtml("github.com", {
tagName: "span"
});
linkifyHtml("#swag", {
tagName: {
hashtag: "span"
}
});
/* target */
linkifyHtml("github.com", {
target: "_parent"
});
linkifyHtml("test-email@example.com", {
target: {
url: "_parent",
email: null
}
});
/* validate */
// Don't linkify links that don't begin in a protocol
// e.g., "http://google.com" will be linkified, but "google.com" will not.
linkifyHtml("www.google.com", {
validate: {
url(value) {
return /^(http|ftp)s?:\/\//.test(value);
}
}
});
+227
View File
@@ -0,0 +1,227 @@
import * as React from "react";
import linkifyHtml from "linkifyjs/html";
import Linkify from "linkifyjs/react";
declare function describe(desc: string, f: () => void): void;
describe("linkifyjs/html", () => {
/**
* The following tests were taken directly from the documentation:
* https://soapbox.github.io/linkifyjs/docs/options.html
*/
/* attributes */
linkifyHtml("github.com", {
attributes: {
rel: "nofollow"
}
});
/* className */
linkifyHtml("github.com", {
className: "new-link--url"
});
linkifyHtml("github.com", {
className(href, type) {
return "new-link--" + type;
}
});
linkifyHtml("github.com", {
className: {
url: "new-link--url",
email(href: string) {
return "new-link--email";
}
}
});
/* events */
linkifyHtml("", {
events: {
click(e) {
alert("Link clicked!");
},
mouseover(e) {
alert("Link hovered!");
}
}
});
/* defaultProtocol */
/* format */
linkifyHtml("", {
format(value, type) {
if (type === "url" && value.length > 50) {
value = value.slice(0, 50) + "…";
}
return value;
}
});
linkifyHtml("", {
format: {
url(value) {
return value.length > 50 ? value.slice(0, 50) + "…" : value;
}
}
});
/* formatHref */
linkifyHtml("This site is #rad", {
formatHref(href, type) {
if (type === "hashtag") {
href = "https://twitter.com/hashtag/" + href.substring(1);
}
return href;
}
});
linkifyHtml("Hey @dhh, check out issue #23", {
formatHref: {
mention(href) {
return "https://github.com" + href;
},
ticket(href) {
return (
"https://github.com/SoapBox/linkifyjs/issues/" +
href.substring(1)
);
}
}
});
/* ignoreTags */
linkifyHtml(
// tslint:disable-next-line:prefer-template
'Please ignore <script>var a = {}; a.com = "Hi";</script> \n' +
"but do <span>b.ca</span>",
{
ignoreTags: ["script", "style"]
}
);
/* nl2br */
/* tagName */
linkifyHtml("github.com", {
tagName: "span"
});
linkifyHtml("#swag", {
tagName: {
hashtag: "span"
}
});
/* target */
linkifyHtml("github.com", {
target: "_parent"
});
linkifyHtml("test-email@example.com", {
target: {
url: "_parent",
email: null
}
});
/* validate */
// Don't linkify links that don't begin in a protocol
// e.g., "http://google.com" will be linkified, but "google.com" will not.
linkifyHtml("www.google.com", {
validate: {
url(value) {
return /^(http|ftp)s?:\/\//.test(value);
}
}
});
});
describe("linkifyjs/react", () => {
/**
* The following tests were taken directly from the documentation:
* https://soapbox.github.io/linkifyjs/docs/linkify-react.html
*/
/* Usage */
{
// render()
const options = {
/* … */
};
const content =
"For help with GitHub.com, please email support@github.com";
<Linkify tagName="p" options={options}>
{content}
</Linkify>;
}
/* Events */
{
const content =
"For help with GitHub.com, please email support@github.com";
const linkProps = {
onClick: (event: any) => {
if (!confirm("Are you sure you want to leave this page?")) {
event.preventDefault();
}
}
};
<Linkify options={{ attributes: linkProps }}>{content}</Linkify>;
}
/**
* The following tests were made specifically for DefinitelyTyped.
*/
/* Default values for all props */
{
const content =
"For help with GitHub.com, please email support@github.com";
<Linkify>
<span>{content}</span>
</Linkify>;
}
/* Custom class name */
{
const content =
"For help with GitHub.com, please email support@github.com";
<Linkify
options={{
className: "custom-class-name"
}}
>
<span>{content}</span>
</Linkify>;
}
/* Custom tag name */
{
const content =
"For help with GitHub.com, please email support@github.com";
<Linkify
options={{
tagName: "p"
}}
>
<span>{content}</span>
</Linkify>;
}
});
+11
View File
@@ -0,0 +1,11 @@
import * as React from "react";
import { LinkifyOptions } from "./index";
export interface LinkifyProps {
options?: LinkifyOptions;
tagName?: string;
}
declare class Linkify extends React.Component<LinkifyProps> {}
export default Linkify;
+5 -13
View File
@@ -1,25 +1,17 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"jsx": "preserve"
},
"files": [
"index.d.ts",
"html.d.ts",
"linkifyjs-tests.ts"
]
"files": ["index.d.ts", "html.d.ts", "react.d.ts", "linkifyjs-tests.tsx"]
}
+47
View File
@@ -0,0 +1,47 @@
// Type definitions for @loadable/component 5.2
// Project: https://github.com/smooth-code/loadable-components
// Definitions by: Martynas Kadiša <https://github.com/martynaskadisa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as React from 'react';
export interface DefaultImportedComponent<P> {
default: React.ComponentType<P>;
}
export type DefaultComponent<P> = React.ComponentType<P> | DefaultImportedComponent<P>;
export interface Options {
fallback?: JSX.Element;
}
export type LoadableComponent<T> = React.ComponentType<T & { fallback?: JSX.Element }>;
export type LoadableLibrary<TModule> = React.ComponentType<{
fallback?: JSX.Element;
children?: (module: TModule) => React.ReactNode;
ref?: React.Ref<TModule>;
}> &
TModule;
declare function lib<T>(
loadFn: (props: object) => Promise<T>,
options?: Options
): LoadableLibrary<T>;
declare function loadableFunc<T>(
loadFn: (props: T) => Promise<DefaultComponent<T>>,
options?: Options
): LoadableComponent<T>;
declare const loadable: typeof loadableFunc & { lib: typeof lib };
export default loadable;
export namespace lazy {
function lib<TModule>(loadFn: (props: object) => Promise<TModule>): LoadableLibrary<TModule>;
}
export function lazy<T>(loadFn: (props: T) => Promise<DefaultComponent<T>>): LoadableComponent<T>;
export function loadableReady(done?: () => any): Promise<void>;
@@ -0,0 +1,117 @@
import * as React from 'react';
import loadable, { lazy, loadableReady } from '@loadable/component';
const TestComponent: React.SFC<{ foo: string }> = () => <>test</>;
function defaultImportComponentLoader() {
return new Promise<{ default: typeof TestComponent }>(resolve => resolve({ default: TestComponent }));
}
function importComponentLoader() {
return new Promise<typeof TestComponent>(resolve => resolve(TestComponent));
}
const lib = {
getTestObj: () => ({ bar: 'bar', foo: 'foo' })
};
function defaultImportLibLoader() {
return new Promise<{ default: typeof lib }>(resolve => resolve(({ default: lib })));
}
function importLibLoader() {
return new Promise<typeof lib>(resolve => resolve(lib));
}
// loadable
{
// Should infer props from imported component with default export
const LoadableDefaultComponent = loadable(defaultImportComponentLoader);
<LoadableDefaultComponent foo="test-prop" />;
// Should infer props from imported component without default export
const LoadableComponent = loadable(importComponentLoader);
<LoadableComponent foo="test-prop" />;
// Should allow passing JSX element to fallback in options
loadable(defaultImportComponentLoader, { fallback: <div>loading...</div> });
// Should allow passing `fallback` prop to loadable component
<LoadableComponent foo="test" fallback={<div>loading...</div>} />;
}
// lazy
{
// Should infer props from imported component with default export
const LazyDefaultComponent = lazy(defaultImportComponentLoader);
<LazyDefaultComponent foo="test" />;
// Should infer props from imported component without default export
const LazyComponent = lazy(importComponentLoader);
<LazyDefaultComponent foo="test" />;
// Should allow passing fallback prop
<LazyComponent foo="test" fallback={<div>loading...</div>} />;
}
// loadable.lib
{
// Should infer types from module with default export and reflect them in children render prop
const LoadableDefaultLibrary = loadable.lib(defaultImportLibLoader);
<LoadableDefaultLibrary>
{({ default: { getTestObj } }) => getTestObj().foo}
</LoadableDefaultLibrary>;
// Should infer types from module without default export and reflect them in children render prop
const LoadableLibrary = loadable.lib(importLibLoader);
<LoadableLibrary>
{({ getTestObj }) => getTestObj().foo}
</LoadableLibrary>;
// Should allow passing fallback JSX element
loadable.lib(importLibLoader, { fallback: <div>loading lib...</div> });
// Should allow passing fallback prop
<LoadableLibrary fallback={<div>Loading library...</div>}>
{({ getTestObj }) => getTestObj().foo}
</LoadableLibrary>;
// Should reflect inferred types from module in ref
const ref = React.createRef<typeof LoadableLibrary>();
<LoadableLibrary ref={ref} />;
ref.current!.getTestObj().foo;
}
// lazy.lib
{
// Should infer types from module with default export and reflect them in children render prop
const LazyDefaultLibrary = lazy.lib(defaultImportLibLoader);
<LazyDefaultLibrary>
{({ default: { getTestObj } }) => getTestObj().foo}
</LazyDefaultLibrary>;
// Should infer types from module without default export and reflect them in children render prop
const LazyLibrary = lazy.lib(importLibLoader);
<LazyLibrary>
{({ getTestObj }) => getTestObj().foo}
</LazyLibrary>;
// Should allow passing fallback prop
<LazyLibrary fallback={<div>Loading library...</div>}>
{({ getTestObj }) => getTestObj().foo}
</LazyLibrary>;
// Should reflect inferred types from module in ref
const ref = React.createRef<typeof LazyLibrary>();
<LazyLibrary ref={ref} />;
ref.current!.getTestObj().foo;
}
// loadableReady
{
// Should allow passing callback argument
loadableReady(() => {});
// Should return a promise
loadableReady().then(() => {});
}
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"jsx": "react",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@loadable/component": [
"loadable__component"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"loadable__component-tests.tsx"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+86
View File
@@ -0,0 +1,86 @@
// Type definitions for @loadable/server 5.2
// Project: https://github.com/smooth-code/loadable-components
// Definitions by: Martynas Kadiša <https://github.com/martynaskadisa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { ComponentType, ReactElement, Component } from 'react';
export type ChunkExtractorOptions = {
/**
* Webpack entrypoints to load (default to `["main"]`)
*/
entrypoints?: string | string[];
/**
* Optional output path (only for `requireEntrypoint`)
*/
outputPath?: string;
} & ({
/**
* Stats file path generated using `@loadable/webpack-plugin`
*/
statsFile: string;
} | {
/**
* Stats generated using `@loadable/webpack-plugin`.
*/
stats: object;
});
/**
* Used to collect chunks server-side and get them as script tags or script elements
*/
export class ChunkExtractor {
constructor(options: ChunkExtractorOptions);
/**
* Wrap your application in a `ChunkExtractorManager`
*/
collectChunks(
/**
* JSX element that will be wrapped in `ChunkExtractorManager`
*/
element: JSX.Element
): JSX.Element;
/**
* Require the entrypoint of your application as a commonjs module.
*/
requireEntrypoint(name?: string): { default: ComponentType };
/**
* Get scripts as a string of `<script>` tags
*/
getScriptTags(): string[];
/**
* Get scripts as an array of React `<script>` elements.
*/
getScriptElements(): Array<ReactElement<{}>>;
/**
* Get "prefetch" and "preload" links as a string of `<link>` tags
*/
getLinkTags(): string[];
/**
* Get "prefetch" and "preload" links as an array of React `<link>` elements
*/
getLinkElements(): Array<ReactElement<{}>>;
/**
* Get style links as a string of `<link>` tags
*/
getStyleTags(): string[];
/**
* Get style links as an array of React `<link>` elements
*/
getStyleElements(): Array<ReactElement<{}>>;
}
export interface ChunkExtractorManagerProps {
extractor: ChunkExtractor;
}
export class ChunkExtractorManager extends Component<ChunkExtractorManagerProps> {}
@@ -0,0 +1,74 @@
import * as React from 'react';
import { ChunkExtractor } from '@loadable/server';
// Should be satisfied by `stats` or `statsFile`
new ChunkExtractor({ stats: {} });
new ChunkExtractor({ statsFile: './path/to/stats' });
const {
collectChunks,
getLinkElements,
getLinkTags,
getScriptElements,
getScriptTags,
getStyleElements,
getStyleTags,
requireEntrypoint
} = new ChunkExtractor({ stats: {} });
// collectChunks
{
// Should accept jsx as first argument
collectChunks(<div>Test</div>);
// Should return jsx
const jsx: JSX.Element = collectChunks(<div>Test</div>);
}
// getLinkElements
{
// Should return an array of React elements
const elements: Array<React.ReactElement<{}>> = getLinkElements();
}
// getLinkTags
{
// Should return an arary of strings
const tags: string[] = getLinkTags();
}
// getScriptElements
{
// Should return an array of React elements
const elements: Array<React.ReactElement<{}>> = getScriptElements();
}
// getScriptTags
{
// Should return an arary of strings
const tags: string[] = getScriptTags();
}
// getStyleElements
{
// Should return an array of React elements
const elements: Array<React.ReactElement<{}>> = getStyleElements();
}
// getStyleTags
{
// Should return an arary of strings
const tags: string[] = getStyleTags();
}
// requireEntrypoint
{
// Should work without params
requireEntrypoint();
// Should accept string
requireEntrypoint('main');
// Should return component on default property
const entry: { default: React.ComponentType } = requireEntrypoint();
}
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"jsx": "react",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@loadable/server": [
"loadable__server"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"loadable__server-tests.tsx"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+2 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for @mapbox/geo-viewport 0.3
// Type definitions for @mapbox/geo-viewport 0.4
// Project: https://github.com/mapbox/geo-viewport
// Definitions by: Fabio Berta <https://github.com/fnberta>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -10,6 +10,6 @@ export interface GeoViewport {
export type BoundingBox = [number, number, number, number];
export function viewport(bounds: BoundingBox, dimensions: [number, number], minzoom?: number, maxzoom?: number, tileSize?: number): GeoViewport;
export function viewport(bounds: BoundingBox, dimensions: [number, number], minzoom?: number, maxzoom?: number, tileSize?: number, allowFloat?: boolean): GeoViewport;
export function bounds(viewport: { lon: number; lat: number } | [number, number], zoom: number, dimensions: [number, number], tileSize?: number): BoundingBox;
+1
View File
@@ -24,6 +24,7 @@ declare namespace Mark {
acrossElements?: boolean;
caseSensitive?: boolean;
ignoreJoiners?: boolean;
ignorePunctuation?: string[];
wildcards?: 'disabled' | 'enabled' | 'withSpaces';
each?(element: Element): void;
+6 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for Marked 0.5
// Type definitions for Marked 0.6
// Project: https://github.com/markedjs/marked
// Definitions by: William Orr <https://github.com/worr>
// BendingBender <https://github.com/BendingBender>
@@ -81,7 +81,7 @@ declare namespace marked {
code(code: string, language: string, isEscaped: boolean): string;
blockquote(quote: string): string;
html(html: string): string;
heading(text: string, level: number, raw: string): string;
heading(text: string, level: number, raw: string, slugger: Slugger): string;
hr(): string;
list(body: string, ordered: boolean, start: number): string;
listitem(text: string): string;
@@ -109,6 +109,10 @@ declare namespace marked {
lex(src: string): TokensList;
}
class Slugger {
slug(value: string): string;
}
interface Rules {
[ruleName: string]: RegExp | Rules;
}
+3 -2
View File
@@ -44,6 +44,7 @@ console.log(tokens2);
const re: RegExp | marked.Rules = lexer.rules['code'];
const renderer = new marked.Renderer();
renderer.heading = (text, level, raw) => {
return text + level.toString() + raw;
const slugger = new marked.Slugger();
renderer.heading = (text, level, raw, slugger) => {
return text + level.toString() + slugger.slug(raw);
};
+13 -6
View File
@@ -173,7 +173,7 @@ declare namespace Mithril {
type ChildArrayOrPrimitive = ChildArray | string | number | boolean;
/** Virtual DOM nodes, or vnodes, are Javascript objects that represent an element (or parts of the DOM). */
interface Vnode<Attrs = {}, State extends Lifecycle<Attrs, State> = Lifecycle<Attrs, State>> {
interface Vnode<Attrs = {}, State extends Lifecycle<Attrs, State> = {}> {
/** The nodeName of a DOM element. It may also be the string [ if a vnode is a fragment, # if it's a text vnode, or < if it's a trusted HTML vnode. Additionally, it may be a component. */
tag: string | ComponentTypes<Attrs, State>;
/** A hashmap of DOM attributes, events, properties and lifecycle methods. */
@@ -194,7 +194,7 @@ declare namespace Mithril {
// In some lifecycle methods, Vnode will have a dom property
// and possibly a domSize property.
interface VnodeDOM<Attrs = {}, State extends Lifecycle<Attrs, State> = Lifecycle<Attrs, State>> extends Vnode<Attrs, State> {
interface VnodeDOM<Attrs = {}, State extends Lifecycle<Attrs, State> = {}> extends Vnode<Attrs, State> {
/** Points to the element that corresponds to the vnode. */
dom: Element;
/** This defines the number of DOM elements that the vnode represents (starting from the element referenced by the dom property). */
@@ -210,7 +210,7 @@ declare namespace Mithril {
* Any Javascript object that has a view method can be used as a Mithril component.
* Components can be consumed via the m() utility.
*/
interface Component<Attrs = {}, State extends Lifecycle<Attrs, State> = Lifecycle<Attrs, State>> extends Lifecycle<Attrs, State> {
interface Component<Attrs = {}, State extends Lifecycle<Attrs, State> = {}> extends Lifecycle<Attrs, State> {
/** Creates a view out of virtual elements. */
view(this: State, vnode: Vnode<Attrs, State>): Children | null | void;
}
@@ -242,16 +242,23 @@ declare namespace Mithril {
* Any function that returns an object with a view method can be used as a Mithril component.
* Components can be consumed via the m() utility.
*/
type FactoryComponent<A = {}> = (vnode: Vnode<A, {}>) => Component<A, {}>;
type FactoryComponent<A = {}> = (vnode: Vnode<A>) => Component<A>;
/**
* Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse.
* Any function that returns an object with a view method can be used as a Mithril component.
* Components can be consumed via the m() utility.
*/
type ClosureComponent<A = {}> = FactoryComponent<A>;
/**
* Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse.
* Any Javascript object that has a view method is a Mithril component. Components can be consumed via the m() utility.
*/
type Comp<Attrs = {}, State extends Lifecycle<Attrs, State> = Lifecycle<Attrs, State>> = Component<Attrs, State> & State;
type Comp<Attrs = {}, State extends Lifecycle<Attrs, State> = {}> = Component<Attrs, State> & State;
/** Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. Components can be consumed via the m() utility. */
type ComponentTypes<A = {}, S extends Lifecycle<A, S> = Lifecycle<A, S>> = Component<A, S> | { new (vnode: CVnode<A>): ClassComponent<A> } | FactoryComponent<A>;
type ComponentTypes<A = {}, S extends Lifecycle<A, S> = {}> = Component<A, S> | { new (vnode: CVnode<A>): ClassComponent<A> } | FactoryComponent<A>;
/** This represents the attributes available for configuring virtual elements, beyond the applicable DOM attributes. */
interface Attributes extends Lifecycle<any, any> {
+4 -4
View File
@@ -116,7 +116,7 @@ const FRAME_BUDGET = 100;
{
// define a component
const Greeter: m.Comp<{ style: string }, {}> = {
const Greeter: m.Comp<{ style: string }> = {
view(vnode) {
return m("div", vnode.attrs, ["Hello ", vnode.children]);
}
@@ -191,7 +191,7 @@ const FRAME_BUDGET = 100;
////////////////////////////////////////////////////////////////////////////////
{
const Fader: m.Comp<{}, {}> = {
const Fader: m.Comp = {
onbeforeremove(vnode) {
vnode.dom.classList.add("fade-out");
return new Promise(resolve => {
@@ -227,7 +227,7 @@ const FRAME_BUDGET = 100;
}
};
const Form: m.Comp<{term: string}, {}> = {
const Form: m.Comp<{term: string}> = {
oninit(vnode) {
state.term = vnode.attrs.term || ""; // populated from the `history.state` property if the user presses the back button
},
@@ -239,7 +239,7 @@ const FRAME_BUDGET = 100;
}
};
const Layout: m.Comp<{}, {}> = {
const Layout: m.Comp = {
view(vnode) {
return m(".layout", vnode.children);
}
+36 -2
View File
@@ -1,5 +1,5 @@
import m = require('mithril');
import { Component, FactoryComponent, Vnode } from 'mithril';
import * as m from 'mithril';
import { Component, ClosureComponent, FactoryComponent } from 'mithril';
///////////////////////////////////////////////////////////
// 0.
@@ -50,6 +50,13 @@ const comp2: FactoryComponent<Comp2Attrs> = vnode => ({ // vnode is inferred
}
});
// 2a. Test ClosureComponent type alias
const comp2a: ClosureComponent<Comp2Attrs> = vnode => ({ // vnode is inferred
view({attrs: {title, description}}) { // Comp2Attrs type is inferred
return [m('h2', title), m('p', description)];
}
});
///////////////////////////////////////////////////////////
// 3.
// Declares attrs type inline.
@@ -80,6 +87,31 @@ const comp3: FactoryComponent<{pageHead: string}> = () => ({
}
});
// 3.a Test ClosureComponent type alias
const comp3a: ClosureComponent<{pageHead: string}> = () => ({
oncreate({dom}) {
// Can do stuff with dom
},
view({attrs}) {
return m('.page',
m('h1', attrs.pageHead),
m(comp2,
{
// attrs is type checked - nice!
title: "A Title",
description: "Some descriptive text.",
onremove(vnode) {
console.log("comp2 was removed");
},
}
),
// Test other hyperscript parameter variations
m(comp1, m(comp1)),
m('br')
);
}
});
///////////////////////////////////////////////////////////
// 4.
// Stateful component using closure method & var
@@ -152,7 +184,9 @@ m.route(document.body, '/', {
'/comp0': comp0,
'/comp1': comp1,
'/comp2': comp2,
'/comp2a': comp2a,
'/comp3': comp3,
'/comp3a': comp3a,
'/comp4': comp4,
'/comp5': comp5
});
+1 -1
View File
@@ -89,7 +89,7 @@ route(document.body, '/', {
test4: {
onmatch(args, path) {
// Must provide a Promise type if we want type checking
return new Promise<Component<{title: string}, {}>>((resolve, reject) => {
return new Promise<Component<{title: string}>>((resolve, reject) => {
resolve(component2);
});
}
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for mongoose-paginate-v2 1.0
// Project: https://github.com/aravindnc/mongoose-paginate-v2
// Definitions by: Linus Brolin <https://github.com/linusbrolin>
// simonxca <https://github.com/simonxca>
// woutgg <https://github.com/woutgg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
//
// Based on type declarations for mongoose-paginate 5.0.0.
declare module 'mongoose' {
interface CustomLabels {
totalDocs?: string;
limit?: string;
page?: string;
totalPages?: string;
docs?: string;
nextPage?: string;
prevPage?: string;
}
interface PaginateOptions {
/* tslint:disable-next-line: ban-types */
select?: Object | string;
/* tslint:disable-next-line: ban-types */
sort?: Object | string;
customLabels?: CustomLabels;
collation?: CollationOptions;
/* tslint:disable-next-line: ban-types */
populate?: Object[] | string[] | Object | string;
lean?: boolean;
leanWithId?: boolean;
offset?: number;
page?: number;
limit?: number;
}
interface PaginateResult<T> {
docs: T[];
total: number;
limit: number;
page?: number;
pages?: number;
offset?: number;
[customLabel: string]: T[] | number | undefined;
}
interface PaginateModel<T extends Document> extends Model<T> {
paginate(query?: object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult<T>) => void): Promise<PaginateResult<T>>;
}
function model(
name: string,
schema?: Schema,
collection?: string,
skipInit?: boolean): PaginateModel<any>;
}
import mongoose = require('mongoose');
export function _(schema: mongoose.Schema): void;
@@ -0,0 +1,80 @@
/**
* Created by Linus Brolin <https://github.com/linusbrolin/>.
*/
import {
Schema,
model,
PaginateModel,
PaginateOptions,
PaginateResult,
Document
} from 'mongoose';
import mongoosePaginate = require('mongoose-paginate');
import { Router, Request, Response } from 'express';
//#region Test Models
interface User extends Document {
email: string;
username: string;
password: string;
}
const UserSchema: Schema = new Schema({
email: String,
username: String,
password: String
});
UserSchema.plugin(mongoosePaginate);
interface UserModel<T extends Document> extends PaginateModel<T> {}
const UserModel: UserModel<User> = model<User>('User', UserSchema) as UserModel<User>;
//#endregion
//#region Test Paginate
const router: Router = Router();
router.get('/users.json', (req: Request, res: Response) => {
const descending = true;
const options: PaginateOptions = {};
options.select = 'email username';
options.sort = { username: (descending ? -1 : 1) };
options.collation = { locale: 'en_US', strength: 1 };
options.populate = '';
options.lean = true;
options.leanWithId = false;
options.offset = 0;
options.page = 1;
options.limit = 10;
options.customLabels = {
totalDocs: 'totalDocsCustom',
limit: 'limitCustom',
page: 'pageCustom',
totalPages: 'totalPagesCustom',
docs: 'docsCustom',
nextPage: 'nextPageCustom',
prevPage: 'prevPageCustom'
};
UserModel
.paginate({}, options, (err: any, value: PaginateResult<User>) => {
if (err) {
console.log(err);
return res.status(500).send(err);
}
console.log('totalDocs: ' + value.totalDocsCustom);
console.log('limit: ' + value.limitCustom);
console.log('page: ' + value.pageCustom);
console.log('nextPage: ' + value.nextPageCustom);
console.log('prevPage: ' + value.prevPageCustom);
console.log('totalPages: ' + value.totalPagesCustom);
console.log('offset: ' + value.offset);
console.log('docs: ');
console.dir(value.docsCustom);
return res.json(value);
});
});
//#endregion
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"mongoose-paginate-v2-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+7 -2
View File
@@ -1,7 +1,6 @@
// Type definitions for Mongoose 5.3.4
// Project: http://mongoosejs.com/
// Definitions by: horiuchi <https://github.com/horiuchi>
// sindrenm <https://github.com/sindrenm>
// lukasz-zak <https://github.com/lukasz-zak>
// Alorel <https://github.com/Alorel>
// jendrikw <https://github.com/jendrikw>
@@ -1894,7 +1893,13 @@ declare module "mongoose" {
* is an Array. See the examples.
*/
geometry(object: { type: string, coordinates: any[] }): this;
/**
* Returns the current query options as a JSON object.
* @returns current query options
*/
getOptions(): any;
/**
* Returns the current query conditions as a JSON object.
* @returns current query conditions
+1 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for Mongoose 4.7.1
// Project: http://mongoosejs.com/
// Definitions by: simonxca <https://github.com/simonxca>, horiuchi <https://github.com/horiuchi>, sindrenm <https://github.com/sindrenm>, lukasz-zak <https://github.com/lukasz-zak>
// Definitions by: simonxca <https://github.com/simonxca>, horiuchi <https://github.com/horiuchi>, lukasz-zak <https://github.com/lukasz-zak>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
+180
View File
@@ -0,0 +1,180 @@
// Type definitions for Navigator.Permissions 0.1
// Project: https://developer.mozilla.org/en-US/docs/Web/API/Permissions
// Definitions by: Vince Varga <https://github.com/vargavince91>, MindDoc <https://github.com/minddocdev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/**
* Namespace for `navigator.permissions` type definitions.
*
* As the Permissions API is only supported by Firefox and Chrome
* https://caniuse.com/#feat=permissions-api
* the TypeScript team has not yet added it to lib.dom.d.ts
* https://github.com/Microsoft/TypeScript/issues/24923
* In the meantime, these type definitions can be used.
*
* The documentation is based on the MDN web docs
* https://developer.mozilla.org/en-US/docs/Web/API/Permissions
*/
declare namespace NavigatorPermissions {
/**
* Permission state values.
*/
type PermissionState =
'granted' |
'denied' |
'prompt';
/**
* The `PermissionStatus` interface of the Permissions API provides the state
* of an object and an event handler for monitoring changes to said state.
*
* This is an experimental technology
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PermissionStatus}
*/
interface PermissionStatus extends EventTarget {
/**
* Returns the state of a requested permission.
*/
readonly state: PermissionState;
/**
* Returns the state of a requested permission.
* Later versions of the specification replace this with
* `PermissionStatus.state`.
* @deprecated
*/
readonly status: PermissionState;
/**
* An event called whenever `PermissionStatus.status` changes.
*/
onchange: ((this: this, event: Event) => any) | null;
}
/**
* Permission name options.
*/
type PermissionName =
'accelerometer' |
'accessibility-events' |
'ambient-light-sensor' |
'background-sync' |
'camera' |
'clipboard-read' |
'clipboard-write' |
'geolocation' |
'gyroscope' |
'magnetometer' |
'microphone' |
'midi' |
'notifications' |
'payment-handler' |
'persistent-storage' |
'push';
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query}
*/
interface PermissionDescriptor<N extends PermissionName> {
/**
* The name of the API whose permissions you want to query.
*
* Please, be aware, that not all of these are supported in every browser
* that supports the Permissions API. For example, in Firefox you can't query
* the `'microphone'` or `'camera'` and it'll throw `TypeError`
*/
name: N;
}
interface PushPermissionDescriptor extends PermissionDescriptor<'push'> {
/**
* Indicates whether you want to show a notification for every message
* or be able to send silent push
* notifications. The default is `false`. Not supported in Firefox.
*/
userVisibleOnly?: boolean;
}
interface MidiPermissionDescriptor extends PermissionDescriptor<'midi'> {
/**
* Indicates whether you need and/or receive system exclusive
* messages. The default is false.
*/
sysex?: boolean;
}
// Map permission names to correctly typed descriptors.
interface NameDescriptorMap {
// ??? Question ???:
// Is there a better way to handle this case and remove repeated code,
// something like
// <N extends PermissionName, D extends PermissionDescriptor<N>> {
// [n in N]: D; // this line to cover all basic cases
// // and the custom permission descriptors for midi and push
// }
'accelerometer': PermissionDescriptor<'accelerometer'>;
'accessibility-events': PermissionDescriptor<'accessibility-events'>;
'ambient-light-sensor': PermissionDescriptor<'ambient-light-sensor'>;
'background-sync': PermissionDescriptor<'background-sync'>;
'camera': PermissionDescriptor<'camera'>;
'clipboard-read': PermissionDescriptor<'clipboard-read'>;
'clipboard-write': PermissionDescriptor<'clipboard-write'>;
'geolocation': PermissionDescriptor<'geolocation'>;
'gyroscope': PermissionDescriptor<'gyroscope'>;
'magnetometer': PermissionDescriptor<'magnetometer'>;
'microphone': PermissionDescriptor<'microphone'>;
'notifications': PermissionDescriptor<'notifications'>;
'payment-handler': PermissionDescriptor<'payment-handler'>;
'persistent-storage': PermissionDescriptor<'persistent-storage'>;
// These permission descriptors support extra properties
'midi': MidiPermissionDescriptor;
'push': PushPermissionDescriptor;
}
/**
* The `Permissions` interface of the Permissions API provides the core
* Permission API functionality, such as methods for querying and
* revoking permissions.
*
* This is an experimental technology.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions}
*/
interface Permissions {
/**
* The `Permissions.query()` method of the `Permissions` interface returns
* the state of a user permission on the global scope.
* @param permissionDescriptor object that sets
* options for the query operation consisting of a comma-separated list
* of name-value pairs.
* (Is comma-separated list really supported? It is mentioned in the docs, but does not work).
* @returns the user permission status for a given API.
* @throws `TypeError` Retrieving the `PermissionDescriptor` information
* failed in some way, or the permission doesn't exist or is currently
* unsupported (e.g. `midi`, or `push` with `userVisibleOnly`).
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query}
*/
query(permissionDescriptor: NameDescriptorMap[keyof NameDescriptorMap]): Promise<PermissionStatus>;
/**
* The `Permissions.revoke()` method of the `Permissions` interface reverts a
* currently set permission back to its default state, which is usually `prompt`.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/revoke}
*/
revoke(permissionDescriptor: NameDescriptorMap[keyof NameDescriptorMap]): Promise<PermissionStatus>;
}
/**
* Navigator type definition with possible `permissions` API support.
*
* This interface adds the `permissions` property to the navigator.
*/
interface NavigatorPermissions extends Navigator {
/**
* Provides the core Permission API functionality, such as querying and revoking permissions.
*
* The typing takes into account that the feature is not widely supported,
* making code using this API more secure by forcing considering the `undefined` case.
*/
permissions?: Permissions;
}
}
@@ -0,0 +1,45 @@
// Here are some examples for Navigator.Permissions types.
// Open it in your IDE with TypeScript support and observe the types and documentation help
// that this module provides
// Navigator from lib.dom might have permissions
const nav = navigator as NavigatorPermissions.NavigatorPermissions;
async function exampleQueryAndEventListeners() {
// Force users to check for undefined as the feature is not widely supported
if (typeof nav.permissions === 'undefined') { return; }
const permissionsStatus = await nav.permissions.query({ name: 'camera' });
// Possible state values are known to users:
const isDenied = permissionsStatus.state === 'denied';
// if compared to any non-valid value, it warns
// const tsShouldWarn = permissionsStatus.state === 'can you see the warning?';
permissionsStatus.addEventListener('change', (event) => {
console.log('permission state changed');
// I couldn't find a way to set the EventTarget's type to PermissionStatus
console.log('new PermissionStatus', event.target);
});
}
function exampleQueryOptions() {
// Force users to check for undefined as the feature is not widely supported
if (typeof nav.permissions === 'undefined') { return; }
// query method checks if the name is a valid permission name
nav.permissions.query({ name: 'camera' });
// Other names would cause type errors
// nav.permissions.query({ name: 'invalid name' });
// When permission name is 'push', userVisibleOnly property is also supported
nav.permissions.query({ name: 'push', userVisibleOnly: true });
// For other names, it would fail:
// nav.permissions.query({ name: 'camera', userVisibleOnly: true });
// When permission name is 'midi', sysex property is also supported
nav.permissions.query({ name: 'midi', sysex: true });
// For other names, it would fail:
// nav.permissions.query({ name: 'camera', sysex: true });
}
function exampleIgnoreUndefinedCheck() {
// Using the ! after permissions will let you bypass the undefined-check
nav.permissions!.query({ name: 'microphone' });
}
@@ -19,6 +19,6 @@
},
"files": [
"index.d.ts",
"sip.js-tests.ts"
"navigator-permissions-tests.ts"
]
}
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+9 -6
View File
@@ -1,6 +1,9 @@
// Type definitions for needle 2.0
// Project: https://github.com/tomas/needle
// Definitions by: San Chen <https://github.com/bigsan>, Niklas Mollenhauer <https://github.com/nikeee>, Matanel Sindilevich <https://github.com/sindilevich>
// Definitions by: San Chen <https://github.com/bigsan>,
// Niklas Mollenhauer <https://github.com/nikeee>,
// Matanel Sindilevich <https://github.com/sindilevich>,
// Bryan Spears <https://github.com/bryanspears>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -20,7 +23,7 @@ declare namespace core {
type ReadableStream = NodeJS.ReadableStream;
type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void;
type NeedleCallback = (error: Error | null, response: NeedleResponse, body: any) => void;
interface Cookies {
[name: string]: any;
@@ -240,11 +243,11 @@ declare function needle(method: core.NeedleReadonlyHttpVerbs, url: string, optio
declare function needle(method: core.NeedleHttpVerbs, url: string, data: core.BodyData, options?: core.NeedleOptions): Promise<core.NeedleResponse>;
declare namespace needle {
type BodyData = core.BodyData;
type NeedleCallback = core.NeedleCallback;
type NeedleHttpVerbs = core.NeedleHttpVerbs;
export type BodyData = core.BodyData;
export type NeedleCallback = core.NeedleCallback;
export type NeedleHttpVerbs = core.NeedleHttpVerbs;
export type NeedleOptions = core.NeedleOptions;
type ReadableStream = core.ReadableStream;
export type ReadableStream = core.ReadableStream;
/**
* Lets override the defaults for all future requests.
+74 -13
View File
@@ -1103,6 +1103,7 @@ declare namespace Office {
* @param callback - Optional. Accepts a callback method to handle the dialog creation attempt. If successful, the AsyncResult.value is a Dialog object.
*/
displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult<Dialog>) => void): void;
displayDialogAsync(startAddress: string, callback?: (result: AsyncResult<Dialog>) => void): void;
/**
* Delivers a message from the dialog box to its parent/opener page. The page calling this API must be on the same domain as the parent.
* @param message Accepts a message from the dialog to deliver to the add-in. In addition to a boolean, anything that can serialized to a string including JSON and XML can be sent.
@@ -2295,6 +2296,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult<void>) => void): void;
addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void;
/**
* Returns the data contained within the binding.
*
@@ -2310,6 +2312,7 @@ declare namespace Office {
* If the `coercionType` parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic.
*/
getDataAsync<T>(options?: GetBindingDataOptions, callback?: (result: AsyncResult<T>) => void): void;
getDataAsync<T>(callback?: (result: AsyncResult<T>) => void): void;
/**
* Removes the specified handler from the binding for the specified event type.
*
@@ -2321,6 +2324,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult<void>) => void): void;
removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult<void>) => void): void;
/**
* Writes data to the bound section of the document represented by the specified binding object.
*
@@ -2452,6 +2456,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
setDataAsync(data: TableData | any, options?: SetBindingDataOptions, callback?: (result: AsyncResult<void>) => void): void;
setDataAsync(data: TableData | any, callback?: (result: AsyncResult<void>) => void): void;
}
/**
@@ -2601,6 +2606,7 @@ declare namespace Office {
* The `value` property of the result is the Binding object that represents the specified named item.
*/
addFromNamedItemAsync(itemName: string, bindingType: BindingType, options?: AddBindingFromNamedItemOptions, callback?: (result: AsyncResult<Binding>) => void): void;
addFromNamedItemAsync(itemName: string, bindingType: BindingType, callback?: (result: AsyncResult<Binding>) => void): void;
/**
* Create a binding by prompting the user to make a selection on the document.
*
@@ -2632,6 +2638,7 @@ declare namespace Office {
* The `value` property of the result is the Binding object that represents the selection specified by the user.
*/
addFromPromptAsync(bindingType: BindingType, options?: AddBindingFromPromptOptions, callback?: (result: AsyncResult<Binding>) => void): void;
addFromPromptAsync(bindingType: BindingType, callback?: (result: AsyncResult<Binding>) => void): void;
/**
* Create a binding based on the user's current selection.
*
@@ -2668,6 +2675,7 @@ declare namespace Office {
* The `value` property of the result is the Binding object that represents the selection specified by the user.
*/
addFromSelectionAsync(bindingType: BindingType, options?: AddBindingFromSelectionOptions, callback?: (result: AsyncResult<Binding>) => void): void;
addFromSelectionAsync(bindingType: BindingType, callback?: (result: AsyncResult<Binding>) => void): void;
/**
* Gets all bindings that were previously created.
*
@@ -2695,6 +2703,7 @@ declare namespace Office {
* The `value` property of the result is an array that contains each binding created for the referenced Bindings object.
*/
getAllAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<Binding[]>) => void): void;
getAllAsync(callback?: (result: AsyncResult<Binding[]>) => void): void;
/**
* Retrieves a binding based on its Name
*
@@ -2725,6 +2734,7 @@ declare namespace Office {
* The `value` property of the result is the Binding object specified by the id in the call.
*/
getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<Binding>) => void): void;
getByIdAsync(id: string, callback?: (result: AsyncResult<Binding>) => void): void;
/**
* Removes the binding from the document
*
@@ -2754,6 +2764,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
releaseByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
releaseByIdAsync(id: string, callback?: (result: AsyncResult<void>) => void): void;
}
/**
* Represents an XML node in a tree in a document.
@@ -2809,6 +2820,7 @@ declare namespace Office {
* The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the `xPath` parameter.
*/
getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<CustomXmlNode[]>) => void): void;
getNodesAsync(xPath: string, callback?: (result: AsyncResult<CustomXmlNode[]>) => void): void;
/**
* Gets the node value.
*
@@ -2820,6 +2832,7 @@ declare namespace Office {
* The `value` property of the result is a string that contains the value of the referenced node.
*/
getNodeValueAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getNodeValueAsync(callback?: (result: AsyncResult<string>) => void): void;
/**
* Gets the text of an XML node in a custom XML part.
*
@@ -2831,6 +2844,7 @@ declare namespace Office {
* The `value` property of the result is a string that contains the inner text of the referenced nodes.
*/
getTextAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getTextAsync(callback?: (result: AsyncResult<string>) => void): void;
/**
* Gets the node's XML.
*
@@ -2842,6 +2856,7 @@ declare namespace Office {
* The `value` property of the result is a string that contains the XML of the referenced node.
*/
getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getXmlAsync(callback?: (result: AsyncResult<string>) => void): void;
/**
* Sets the node value.
*
@@ -2853,6 +2868,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
setNodeValueAsync(value: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
setNodeValueAsync(value: string, callback?: (result: AsyncResult<void>) => void): void;
/**
* Asynchronously sets the text of an XML node in a custom XML part.
*
@@ -2866,6 +2882,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
setTextAsync(text: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
setTextAsync(text: string, callback?: (result: AsyncResult<void>) => void): void;
/**
* Sets the node XML.
*
@@ -2877,6 +2894,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
setXmlAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
setXmlAsync(xml: string, callback?: (result: AsyncResult<void>) => void): void;
}
/**
* Represents a single CustomXMLPart in an {@link Office.CustomXmlParts} collection.
@@ -2927,6 +2945,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, callback?: (result: AsyncResult<void>) => void): void;
/**
* Deletes the Custom XML Part.
*
@@ -2936,6 +2955,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
deleteAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
deleteAsync(callback?: (result: AsyncResult<void>) => void): void;
/**
* Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath.
*
@@ -2947,6 +2967,7 @@ declare namespace Office {
* The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the xPath parameter.
*/
getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<CustomXmlNode[]>) => void): void;
getNodesAsync(xPath: string, callback?: (result: AsyncResult<CustomXmlNode[]>) => void): void;
/**
* Asynchronously gets the XML inside this custom XML part.
*
@@ -2957,6 +2978,7 @@ declare namespace Office {
* The `value` property of the result is a string that contains the XML of the referenced CustomXmlPart object.
*/
getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getXmlAsync(callback?: (result: AsyncResult<string>) => void): void;
/**
* Removes an event handler for the specified event type.
*
@@ -2969,6 +2991,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, options?: RemoveHandlerOptions, callback?: (result: AsyncResult<void>) => void): void;
removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, callback?: (result: AsyncResult<void>) => void): void;
}
/**
@@ -3108,6 +3131,7 @@ declare namespace Office {
* The `value` property of the result is the newly created CustomXmlPart object.
*/
addAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<CustomXmlPart>) => void): void;
addAsync(xml: string, callback?: (result: AsyncResult<CustomXmlPart>) => void): void;
/**
* Asynchronously gets the specified custom XML part by its id.
*
@@ -3118,6 +3142,7 @@ declare namespace Office {
* If there is no custom XML part with the specified id, the method returns null.
*/
getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<CustomXmlPart>) => void): void;
getByIdAsync(id: string, callback?: (result: AsyncResult<CustomXmlPart>) => void): void;
/**
* Asynchronously gets the specified custom XML part(s) by its namespace.
*
@@ -3127,6 +3152,7 @@ declare namespace Office {
* The `value` property of the result is an array of CustomXmlPart objects that match the specified namespace.
*/
getByNamespaceAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<CustomXmlPart[]>) => void): void;
getByNamespaceAsync(ns: string, callback?: (result: AsyncResult<CustomXmlPart[]>) => void): void;
}
/**
* Represents a collection of CustomXmlPart objects.
@@ -3162,6 +3188,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
addNamespaceAsync(prefix: string, ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
addNamespaceAsync(prefix: string, ns: string, callback?: (result: AsyncResult<void>) => void): void;
/**
* Asynchronously gets the namespace mapped to the specified prefix.
*
@@ -3176,6 +3203,7 @@ declare namespace Office {
* The `value` property of the result is a string that contains the namespace mapped to the specified prefix.
*/
getNamespaceAsync(prefix: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getNamespaceAsync(prefix: string, callback?: (result: AsyncResult<string>) => void): void;
/**
* Asynchronously gets the prefix for the specified namespace.
*
@@ -3190,6 +3218,7 @@ declare namespace Office {
* The `value` property of the result is a string that contains the prefix of the specified namespace.
*/
getPrefixAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getPrefixAsync(ns: string, callback?: (result: AsyncResult<string>) => void): void;
}
/**
* An abstract class that represents the document the add-in is interacting with.
@@ -3345,6 +3374,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult<void>) => void): void;
/**
* Returns the state of the current view of the presentation (edit or read).
*
@@ -3374,6 +3404,7 @@ declare namespace Office {
* such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View.
*/
getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<"edit" | "read">) => void): void;
getActiveViewAsync(callback?: (result: AsyncResult<"edit" | "read">) => void): void;
/**
* Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB).
* Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure.
@@ -3418,6 +3449,7 @@ declare namespace Office {
* The `value` property of the result is the File object.
*/
getFileAsync(fileType: FileType, options?: GetFileOptions, callback?: (result: AsyncResult<Office.File>) => void): void;
getFileAsync(fileType: FileType, callback?: (result: AsyncResult<Office.File>) => void): void;
/**
* Gets file properties of the current document.
*
@@ -3447,6 +3479,7 @@ declare namespace Office {
* The `value` property of the result is the file's properties (with the URL found at `asyncResult.value.url`).
*/
getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<Office.FileProperties>) => void): void;
getFilePropertiesAsync(callback?: (result: AsyncResult<Office.FileProperties>) => void): void;
/**
* Reads the data contained in the current selection in the document.
*
@@ -3538,7 +3571,8 @@ declare namespace Office {
* This is returned in the data structure or format you specified with the coercionType parameter.
* (See Remarks for more information about data coercion.)
*/
getSelectedDataAsync<T>(coerciontype: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult<T>) => void): void;
getSelectedDataAsync<T>(coercionType: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult<T>) => void): void;
getSelectedDataAsync<T>(coercionType: Office.CoercionType, callback?: (result: AsyncResult<T>) => void): void;
/**
* Goes to the specified object or location in the document.
*
@@ -3581,6 +3615,7 @@ declare namespace Office {
* The `value` property of the result is the current view.
*/
goToByIdAsync(id: string | number, goToType: GoToType, options?: GoToByIdOptions, callback?: (result: AsyncResult<any>) => void): void;
goToByIdAsync(id: string | number, goToType: GoToType, callback?: (result: AsyncResult<any>) => void): void;
/**
* Removes an event handler for the specified event type.
*
@@ -3610,6 +3645,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult<void>) => void): void;
removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult<void>) => void): void;
/**
* Writes the specified data into the current selection.
*
@@ -3723,6 +3759,7 @@ declare namespace Office {
* The AsyncResult.value property always returns undefined because there is no object or data to retrieve.
*/
setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult<void>) => void): void;
setSelectedDataAsync(data: string | TableData | any[][], callback?: (result: AsyncResult<void>) => void): void;
/**
* Project documents only. Get Project field (Ex. ProjectWebAccessURL).
* @param fieldId Project level fields.
@@ -3747,6 +3784,7 @@ declare namespace Office {
* </table>
*/
getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult<any>) => void): void;
/**
* Project documents only. Get resource field for provided resource Id. (Ex.ResourceName)
* @param resourceId Either a string or value of the Resource Id.
@@ -3772,6 +3810,7 @@ declare namespace Office {
* </table>
*/
getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult<string>) => void): void;
/**
* Project documents only. Get the current selected Resource's Id.
* @param options Provides an option for preserving context data of any type, unchanged, for use in a callback.
@@ -3795,6 +3834,7 @@ declare namespace Office {
* </table>
*/
getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getSelectedResourceAsync(callback?: (result: AsyncResult<string>) => void): void;
/**
* Project documents only. Get the current selected Task's Id.
* @param options Provides an option for preserving context data of any type, unchanged, for use in a callback.
@@ -3818,6 +3858,7 @@ declare namespace Office {
* </table>
*/
getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getSelectedTaskAsync(callback?: (result: AsyncResult<string>) => void): void;
/**
* Project documents only. Get the current selected View Type (Ex. Gantt) and View Name.
* @param options Provides an option for preserving context data of any type, unchanged, for use in a callback.
@@ -3843,6 +3884,7 @@ declare namespace Office {
* </table>
*/
getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
getSelectedViewAsync(callback?: (result: AsyncResult<any>) => void): void;
/**
* Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId.
* @param taskId Either a string or value of the Task Id.
@@ -3870,6 +3912,7 @@ declare namespace Office {
* </table>
*/
getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
getTaskAsync(taskId: string, callback?: (result: AsyncResult<any>) => void): void;
/**
* Project documents only. Get task field for provided task Id. (Ex. StartDate).
* @param taskId Either a string or value of the Task Id.
@@ -3895,6 +3938,7 @@ declare namespace Office {
* </table>
*/
getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult<any>) => void): void;
/**
* Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too.
* @param options Provides an option for preserving context data of any type, unchanged, for use in a callback.
@@ -3920,6 +3964,7 @@ declare namespace Office {
* </table>
*/
getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
getWSSUrlAsync(callback?: (result: AsyncResult<any>) => void): void;
/**
* Project documents only. Get the maximum index of the collection of resources in the current project.
*
@@ -3946,6 +3991,7 @@ declare namespace Office {
* </table>
*/
getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<number>) => void): void;
getMaxResourceIndexAsync(callback?: (result: AsyncResult<number>) => void): void;
/**
* Project documents only. Get the maximum index of the collection of tasks in the current project.
*
@@ -3972,6 +4018,7 @@ declare namespace Office {
* </table>
*/
getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<number>) => void): void;
getMaxTaskIndexAsync(callback?: (result: AsyncResult<number>) => void): void;
/**
* Project documents only. Get the GUID of the resource that has the specified index in the resource collection.
*
@@ -3999,6 +4046,7 @@ declare namespace Office {
* </table>
*/
getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult<string>) => void): void;
/**
* Project documents only. Get the GUID of the task that has the specified index in the task collection.
*
@@ -4026,6 +4074,7 @@ declare namespace Office {
* </table>
*/
getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult<string>) => void): void;
/**
* Project documents only. Set resource field for specified resource Id.
*
@@ -4054,6 +4103,7 @@ declare namespace Office {
* </table>
*/
setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult<void>) => void): void;
/**
* Project documents only. Set task field for specified task Id.
*
@@ -4082,6 +4132,7 @@ declare namespace Office {
* </table>
*/
setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult<void>) => void): void;
}
/**
* Provides information about the document that raised the SelectionChanged event.
@@ -4332,6 +4383,7 @@ declare namespace Office {
* </table>
*/
addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult<void>) => void): void;
/**
* Retrieves the specified setting.
*
@@ -4487,6 +4539,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult<void>) => void): void;
removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult<void>) => void): void;
/**
* Persists the in-memory copy of the settings property bag in the document.
*
@@ -4544,6 +4597,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
saveAsync(options?: SaveSettingsOptions, callback?: (result: AsyncResult<void>) => void): void;
saveAsync(callback?: (result: AsyncResult<void>) => void): void;
/**
* Sets or creates the specified setting.
*
@@ -4804,6 +4858,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
addColumnsAsync(tableData: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
addColumnsAsync(tableData: TableData | any[][], callback?: (result: AsyncResult<void>) => void): void;
/**
* Adds the specified data to the table as additional rows.
*
@@ -4844,6 +4899,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
addRowsAsync(rows: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
addRowsAsync(rows: TableData | any[][], callback?: (result: AsyncResult<void>) => void): void;
/**
* Deletes all non-header rows and their values in the table, shifting appropriately for the host application.
*
@@ -4871,6 +4927,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
deleteAllDataValuesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
deleteAllDataValuesAsync(callback?: (result: AsyncResult<void>) => void): void;
/**
* Clears formatting on the bound table.
*
@@ -4895,6 +4952,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
clearFormatsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
clearFormatsAsync(callback?: (result: AsyncResult<void>) => void): void;
/**
* Gets the formatting on specified items in the table.
*
@@ -4949,6 +5007,7 @@ declare namespace Office {
* The `value` property of the result is an array containing one or more JavaScript objects specifying the formatting of their corresponding cells.
*/
getFormatsAsync(cellReference?: any, formats?: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void;
getFormatsAsync(cellReference?: any, formats?: any[], callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void;
/**
* Sets formatting on specified items and data in the table.
*
@@ -5062,6 +5121,7 @@ declare namespace Office {
* @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}.
*/
setFormatsAsync(cellFormat: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
setFormatsAsync(cellFormat: any[], callback?: (result: AsyncResult<void>) => void): void;
/**
* Updates table formatting options on the bound table.
*
@@ -5115,6 +5175,7 @@ declare namespace Office {
*
*/
setTableOptionsAsync(tableOptions: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
setTableOptionsAsync(tableOptions: any, callback?: (result: AsyncResult<void>) => void): void;
}
/**
* Represents the data in a table or a {@link Office.TableBinding}.
@@ -8703,7 +8764,7 @@ declare namespace Office {
*
* In addition to this signature, this method also has the following signature:
*
* `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult<string>) => void): void;`
* `getAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult<string>) => void): void;`
*
* @param coercionType The format for the returned body.
* @param options Optional. An object literal that contains one or more of the following properties:
@@ -8711,7 +8772,7 @@ declare namespace Office {
* @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult.
* The body is provided in the requested format in the asyncResult.value property.
*/
getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
getAsync(coercionType: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
/**
* Returns the current body in a specified format.
*
@@ -8732,7 +8793,7 @@ declare namespace Office {
* @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult.
* The body is provided in the requested format in the asyncResult.value property.
*/
getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult<string>) => void): void;
getAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult<string>) => void): void;
/**
* Gets a value that indicates whether the content is in HTML or text format.
@@ -10215,7 +10276,7 @@ declare namespace Office {
* asyncContext: Developers can provide any object they wish to access in the callback method.
* @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult.
*/
getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult<any>) => void): void;
getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult<any>) => void): void;
/**
* Asynchronously returns selected data from the subject or body of a message.
*
@@ -10241,7 +10302,7 @@ declare namespace Office {
* @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of
* type Office.AsyncResult.
*/
getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult<string>) => void): void;
getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult<string>) => void): void;
/**
* Asynchronously loads custom properties for this add-in on the selected item.
*
@@ -12146,7 +12207,7 @@ declare namespace Office {
* @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of
* type Office.AsyncResult.
*/
getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult<any>) => void): void;
getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult<any>) => void): void;
/**
* Asynchronously returns selected data from the subject or body of a message.
*
@@ -12174,7 +12235,7 @@ declare namespace Office {
* @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of
* type Office.AsyncResult.
*/
getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult<any>) => void): void;
getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult<any>) => void): void;
/**
* Removes an attachment from a message or appointment.
*
@@ -13618,7 +13679,7 @@ declare namespace Office {
* @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of
* type Office.AsyncResult.
*/
getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult<any>) => void): void;
getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult<any>) => void): void;
/**
* Asynchronously returns selected data from the subject or body of a message.
*
@@ -13646,7 +13707,7 @@ declare namespace Office {
* @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of
* type Office.AsyncResult.
*/
getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult<any>) => void): void;
getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult<any>) => void): void;
/**
* Asynchronously loads custom properties for this add-in on the selected item.
*
@@ -61745,7 +61806,7 @@ declare namespace Word {
readonly id: number;
/**
*
* Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty.
* Gets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty.
*
* [Api set: WordApi 1.1]
*/
@@ -61980,7 +62041,7 @@ declare namespace Word {
insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;
/**
*
* Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'.
* Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. This method is only supported if the content control encompasses one or more paragraphs in entirety.
*
* [Api set: WordApi 1.1]
*
@@ -61990,7 +62051,7 @@ declare namespace Word {
insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph;
/**
*
* Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'.
* Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. This method is only supported if the content control encompasses one or more paragraphs in entirety.
*
* [Api set: WordApi 1.1]
*
+810 -113
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
import * as ol from 'openlayers';
export default ol.interaction.Extent;
+1
View File
@@ -75,6 +75,7 @@
"interaction/dragrotateandzoom.d.ts",
"interaction/dragzoom.d.ts",
"interaction/draw.d.ts",
"interaction/extent.d.ts",
"interaction/interaction.d.ts",
"interaction/keyboardpan.d.ts",
"interaction/keyboardzoom.d.ts",

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