diff --git a/types/ansicolors/index.d.ts b/types/ansicolors/index.d.ts index 6750283895..dd1a872e57 100644 --- a/types/ansicolors/index.d.ts +++ b/types/ansicolors/index.d.ts @@ -1,8 +1,45 @@ // Type definitions for ansicolors // Project: https://github.com/thlorenz/ansicolors -// Definitions by: rogierschouten +// Definitions by: Benjamin Arthur Lupton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare var colors: { [index: string]: (s: string) => string; }; -export = colors; +interface Colors extends String { + (value: string): string + white: this + black: this + blue: this + cyan: this + green: this + magenta: this + red: this + yellow: this + brightBlack: this + brightRed: this + brightGreen: this + brightYellow: this + brightBlue: this + brightMagenta: this + brightCyan: this + brightWhite: this + bgBlack: this + bgRed: this + bgGreen: this + bgYellow: this + bgBlue: this + bgMagenta: this + bgCyan: this + bgWhite: this + bgBrightBlack: this + bgBrightRed: this + bgBrightGreen: this + bgBrightYellow: this + bgBrightBlue: this + bgBrightMagenta: this + bgBrightCyan: this + bgBrightWhite: this + open: this + close: this + colors: this +} +declare const colors: Colors +export default colors diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index c2adb63a30..de6de9a2c6 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -47,7 +47,8 @@ appInsights = { startTrackEvent(name: string) { return null; }, stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; }, + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, + resultCode: number, properties?: { [name: string]: string }, measurements?: { [name: string]: number }) { return null; }, trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; }, trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; }, trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: AI.SeverityLevel) { return null; }, @@ -86,7 +87,7 @@ appInsights.trackTrace("message", null); appInsights.trackTrace("message", { a: '1', b: '2' }, AI.SeverityLevel.Error); // trackDependency -appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null); +appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null, {prop1: 'abc'}, {meas1: 4.5}); // flush appInsights.flush(); diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 5fbbc3a0f5..002a950637 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -670,14 +670,16 @@ declare module Microsoft.ApplicationInsights { context: ITelemetryContext; queue: Array<() => void>; /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops, + * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view + * and send the event. * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. */ startTrackPage(name?: string): any; /** - * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements. + * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`. + * @param name The string you used as the name in `startTrackPage`. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. @@ -689,7 +691,7 @@ declare module Microsoft.ApplicationInsights { measurements?: { [name: string]: number }): any; /** * Logs that a page or other item was viewed. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param name The string you used as the name in `startTrackPage`. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. @@ -701,13 +703,13 @@ declare module Microsoft.ApplicationInsights { properties?: { [name: string]: string }, measurements?: { [name: string]: number }, duration?: number): any; /** - * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. + * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends. * @param name A string that identifies this event uniquely within the document. */ startTrackEvent(name: string): any; /** - * Log an extended event that you started timing with {@link startTrackEvent}. - * @param name The string you used to identify this event in startTrackEvent. + * Log an extended event that you started timing with `startTrackEvent`. + * @param name The string you used to identify this event in `startTrackEvent`. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ @@ -734,8 +736,11 @@ declare module Microsoft.ApplicationInsights { * @param totalTime total request time * @param success indicates if the request was sessessful * @param resultCode response code returned by the dependency request + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): any; + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, + properties?: { [name: string]: string }, measurements?: { [name: string]: number }): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 1a1bf712d7..70f8c5f0b6 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -4,10 +4,14 @@ import * as t from "@babel/types"; // Examples from: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md const MyVisitor: Visitor = { Identifier: { - enter() { + enter(path) { + // $ExpectType NodePath + path; console.log("Entered!"); }, - exit() { + exit(path) { + // $ExpectType NodePath + path; console.log("Exited!"); } } @@ -109,3 +113,40 @@ const BindingKindTest: Visitor = { kind === 'anythingElse'; }, }; + +interface SomeVisitorState { someState: string; } + +const VisitorStateTest: Visitor = { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + Identifier(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + FunctionDeclaration: { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + } + } +}; diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index e35b12780f..89e242129b 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -143,17 +143,17 @@ export class Binding { constantViolations: NodePath[]; } -export type Visitor = VisitNodeObject & { - [P in Node["type"]]?: VisitNode>; +export type Visitor = VisitNodeObject & { + [Type in Node["type"]]?: VisitNode>; }; -export type VisitNode = VisitNodeFunction | VisitNodeObject; +export type VisitNode = VisitNodeFunction | VisitNodeObject; -export type VisitNodeFunction = (this: T, path: NodePath

, state: any) => void; +export type VisitNodeFunction = (this: S, path: NodePath

, state: S) => void; -export interface VisitNodeObject { - enter?(path: NodePath, state: any): void; - exit?(path: NodePath, state: any): void; +export interface VisitNodeObject { + enter?: VisitNodeFunction; + exit?: VisitNodeFunction; } export class NodePath { diff --git a/types/baidu-app/baidu-app-tests.ts b/types/baidu-app/baidu-app-tests.ts new file mode 100644 index 0000000000..9987a650ee --- /dev/null +++ b/types/baidu-app/baidu-app-tests.ts @@ -0,0 +1,2007 @@ +(() => { + swan.request({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + method: 'GET', + dataType: 'json', + data: { + key: 'value' + }, + header: { + 'content-type': 'application/json' // 默认值 + }, + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + const requestTask = swan.request({ + url: 'test.php', // 仅为示例,并非真实的接口地址 + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + success(res) { + console.log(res.data); + } + }); + // 取消请求任务 + requestTask.abort(); +})(); + +(() => { + swan.chooseImage({ + success(res) { + swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + filePath: res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); +})(); + +(() => { + const uploadTask = swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 开发者服务器 url + filePath: '', // res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + uploadTask.onProgressUpdate(res => { + console.log('上传进度', res.progress); + console.log('已经上传的数据长度', res.totalBytesSent); + console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend); + }); + + uploadTask.abort(); // 取消上传任务 +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + // 下载成功 + if (res.statusCode === 200) { + console.log("临时文件路径" + res.tempFilePath); + } + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const downloadTask = swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + console.log(res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + downloadTask.onProgressUpdate(res => { + console.log('下载进度', res.progress); + console.log('已经下载的数据长度', res.totalBytesWritten); + console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite); + }); + + downloadTask.abort(); // 取消下载任务 +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen((res) => { + console.log('WebSocket连接已打开!', res.header); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' // 仅为示例,并非真实的服务地址 + }); + swan.onSocketError((res) => { + console.log('WebSocket连接打开失败,请检查!'); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); + swan.onSocketMessage((res) => { + console.log('收到服务器内容:', res.data); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com', + success(res) { + swan.closeSocket(); + } + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + + swan.onSocketClose((res) => { + console.log('WebSocket 已关闭!'); + }); + + swan.onSocketOpen(() => { + swan.closeSocket(); + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrIdCard({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrBankCard({ + image, + success(res) { + console.log(res.result.bank_name); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrDrivingLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrVehicleLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); +})(); + +(() => { + swan.ai.textReview({ + content: '', + success(res) { + console.log(res.result.spam); // 0 表示审核通过 + } + }); +})(); + +(() => { + swan.ai.textToAudio({ + ctp: '1', + lan: 'zh', + tex: '这是一段测试文字', + success(res) { + console.log(res.filePath); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.imageAudit({ + image, + success(res) { + console.log(res.conclusionType); // 1 为合规 + } + }); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.advancedGeneralIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.objectDetectIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.carClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.dishClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.logoClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.animalClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.plantClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); +})(); + +(() => { + const voiceRecognizer = swan.ai.getVoiceRecognizer(); + + voiceRecognizer.onStart(() => { + console.log('voice start'); + }); + voiceRecognizer.onRecognize(res => { + console.log('voice recognize', res); + }); + voiceRecognizer.onFinish(res => { + console.log('voice end', res); + }); + voiceRecognizer.onError(err => { + console.log('voice error', err); + }); + + const options = { + mode: 'dnn', + longSpeech: false + }; + + voiceRecognizer.start(options); +})(); + +(() => { + swan.chooseImage({ + count: 1, + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success(res) { + // 成功则返回图片的本地文件路径列表 tempFilePaths + console.log(res.tempFilePaths); + // 文件列表对象 + console.log(res.tempFiles); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [], // 需要预览的图片http链接列表 + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + swan.getImageInfo({ + src: '/xxx/xxx.jpg', + success(res) { + // 成功则返回图片高,宽,本地路径 + console.log(res.width); + console.log(res.height); + console.log(res.path); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.saveImageToPhotosAlbum({ + filePath: '/xxx/xxx.jpg', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const recorderManager = swan.getRecorderManager(); + + recorderManager.onStart(() => { + // 开始录音事件 + console.log('recorder start'); + }); + recorderManager.onPause(() => { + // 暂停录音事件 + console.log('recorder pause'); + }); + recorderManager.onStop((res) => { + // 停止录音事件 + console.log('recorder stop', res); + const { tempFilePath } = res; + }); + + const options = { + duration: 10000, + sampleRate: 44100, + numberOfChannels: 1, + encodeBitRate: 96000, + format: 'aac' + }; + + recorderManager.start(options); +})(); + +(() => { + const backgroundAudioManager = swan.getBackgroundAudioManager(); + + backgroundAudioManager.title = '此时此刻'; + backgroundAudioManager.epname = '此时此刻'; + backgroundAudioManager.singer = '许巍'; + backgroundAudioManager.coverImgUrl = 'xxx'; + backgroundAudioManager.src = 'xxx'; +})(); + +(() => { + const innerAudioContext = swan.createInnerAudioContext(); + innerAudioContext.src = 'xxx'; + innerAudioContext.autoplay = true; + innerAudioContext.seek({ + position: 10 + }); + innerAudioContext.onPlay((res) => { + console.log('开始播放'); + }); +})(); + +(() => { + Page({ + data: { + sourceType: ['album', 'camera'], + compressed: false, + maxDuration: 60, + src: '' + }, + + chooseVideo() { + const self = this; + swan.chooseVideo({ + sourceType: this.getData('sourceType'), + compressed: this.getData('compressed'), + maxDuration: this.getData('maxDuration'), + success(res) { + // 成功返回选定视频的临时文件路径 + self.setData('src', res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); + swan.saveVideoToPhotosAlbum({ + filePath: 'bdfile://xxx', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const myVideo = swan.createVideoContext('myVideo'); + myVideo.play(); +})(); + +(() => { + swan.chooseImage({ + count: 1, + success(res) { + const tempFilePaths = res.tempFilePaths; + swan.saveFile({ + tempFilePath: tempFilePaths[0], + success(res) { + const savedFilePath = res.savedFilePath; + } + }); + } + }); + swan.getFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.digest); + } + }); + swan.getSavedFileList({ + success(res) { + const fileList = res.fileList; + } + }); + swan.getSavedFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.createTime); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getSavedFileList({ + success(res) { + if (res.fileList.length > 0) { + swan.removeSavedFile({ + filePath: res.fileList[0].filePath, + success(res) { + console.log(res.filePath); + } + }); + } + } + }); +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx.pdf', + success(res) { + const filePath = res.tempFilePath; + swan.openDocument({ + filePath, + success(res) { + console.log('打开文档成功'); + } + }); + } + }); +})(); + +(() => { + swan.setStorage({ + key: 'key', + data: 'value' + }); +})(); + +(() => { + try { + swan.setStorageSync('key', 'value'); + } catch (e) { + } + swan.getStorage({ + key: 'key', + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageSync('key'); + } catch (e) { + } + swan.getStorageInfo({ + success(res) { + console.log(res.keys); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageInfoSync(); + console.log(result); + } catch (e) { + } +})(); + +(() => { + swan.removeStorage({ + key: 'key', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + swan.removeStorageSync('key'); + } catch (e) { + } + try { + swan.clearStorageSync(); + } catch (e) { + } +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + console.log('纬度:' + res.latitude); + console.log('经度:' + res.longitude); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + swan.openLocation({ + latitude: res.latitude, + longitude: res.longitude, + scale: 18 + }); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + let mapContext: swan.MapContext; + Page({ + data: { + latitude: '40.042500', + longitude: '116.274040', + }, + onReady() { + mapContext = swan.createMapContext('myMap'); + }, + getCenterLocation() { + mapContext.getCenterLocation({ + success(res) { + console.log("经度" + res.longitude); + console.log("纬度" + res.latitude); + } + }); + }, + moveToLocation() { + mapContext.moveToLocation(); + }, + translateMarker() { + mapContext.translateMarker({ + markerId: 0, + rotate: 90, + autoRotate: true, + duration: 1000, + destination: { + latitude: 23.10229, + longitude: 113.3345211, + }, + animationEnd() { + console.log('animation end'); + } + }); + }, + includePoints() { + mapContext.includePoints({ + padding: [10], + points: [{ + latitude: 23, + longitude: 113.33, + }, { + latitude: 23, + longitude: 113.3345211, + }] + }); + }, + getRegion() { + mapContext.getRegion({ + success(res) { + console.log("西南角的经纬度" + res.southwest); + console.log("东北角的经纬度" + res.northeast); + } + }); + } + }); +})(); + +(() => { + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + ctx.draw(); + } + }); + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + } + }); + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + + ctx.draw(); + + swan.canvasGetImageData({ + canvasId: 'myCanvas', + x: 0, + y: 0, + width: 100, + height: 100, + success(res) { + console.log(res); + } + }); + const data = new Uint8ClampedArray([255, 0, 0, 1]); + swan.canvasPutImageData({ + canvasId: 'myCanvas', + data, + x: 0, + y: 0, + width: 1, + height: 2, + success(res) { + console.log('success'); + } + }); + swan.canvasToTempFilePath({ + x: 100, + y: 200, + width: 50, + height: 50, + destWidth: 100, + destHeight: 100, + canvasId: 'myCanvas', + success(res) { + console.log(res.tempFilePath); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.setShadow(10, 50, 50, 'red'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create linear gradient + const grd = ctx.createLinearGradient(0, 0, 200, 0); + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createCircularGradient(75, 50, 50); + grd.addColorStop(0, 'red'); + grd.addColorStop(1, 'blue'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createLinearGradient(30, 10, 120, 10); + grd.addColorStop(0, 'red'); + grd.addColorStop(0.16, 'orange'); + grd.addColorStop(0.33, 'yellow'); + grd.addColorStop(0.5, 'green'); + grd.addColorStop(0.66, 'cyan'); + grd.addColorStop(0.83, 'blue'); + grd.addColorStop(1, 'purple'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(5); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(10); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(10); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(10); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setLineDash([10, 20], 5); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(4); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(30, 30, 150, 75); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setStrokeStyle('blue'); + ctx.strokeRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('red'); + ctx.fillRect(0, 0, 150, 200); + ctx.setFillStyle('blue'); + ctx.fillRect(150, 0, 150, 200); + ctx.clearRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(10, 10, 100, 30); + ctx.setFillStyle('red'); + ctx.fill(); + ctx.beginPath(); + ctx.rect(10, 40, 100, 30); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 70, 100, 30); + ctx.rect(10, 100, 100, 30); + ctx.setFillStyle('green'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.lineTo(100, 10); + ctx.moveTo(10, 100); + ctx.lineTo(100, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.rect(10, 10, 100, 50); + ctx.lineTo(110, 60); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.arc(100, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.downloadFile({ + url: 'https://b.bdstatic.com/searchbox/icms/searchbox/img/LOGO300x300.jpg', + success(res) { + ctx.save(); + ctx.beginPath(); + ctx.arc(50, 50, 25, 0, 2 * Math.PI); + ctx.clip(); + ctx.drawImage(res.tempFilePath, 25, 25); + ctx.restore(); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('20', 20, 20); + ctx.setFontSize(30); + ctx.fillText('30', 40, 40); + ctx.setFontSize(40); + ctx.fillText('40', 60, 60); + ctx.setFontSize(50); + ctx.fillText('50', 90, 90); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('Hello', 20, 20); + ctx.fillText('World', 100, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(150, 20); + ctx.lineTo(150, 170); + ctx.stroke(); + + ctx.setFontSize(15); + ctx.setTextAlign('left'); + ctx.fillText('textAlign=left', 150, 60); + + ctx.setTextAlign('center'); + ctx.fillText('textAlign=center', 150, 80); + + ctx.setTextAlign('right'); + ctx.fillText('textAlign=right', 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(5, 75); + ctx.lineTo(295, 75); + ctx.stroke(); + + ctx.setFontSize(20); + + ctx.setTextBaseline('top'); + ctx.fillText('top', 5, 75); + + ctx.setTextBaseline('middle'); + ctx.fillText('middle', 50, 75); + + ctx.setTextBaseline('bottom'); + ctx.fillText('bottom', 120, 75); + + ctx.setTextBaseline('normal'); + ctx.fillText('normal', 200, 75); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.chooseImage({ + success(res) { + ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFillStyle('red'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('yellow'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.font = 'italic bold 20px cursive'; + const metrics = ctx.measureText('Hello World'); + console.log(metrics.width); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + const pattern = ctx.createPattern('/path/to/image', 'repeat-x'); + ctx.fillStyle = pattern; + ctx.fillRect(0, 0, 300, 150); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.quadraticCurveTo(20, 100, 200, 20); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + ctx.draw(); + ctx.fillRect(30, 30, 150, 100); + ctx.draw(); +})(); + +(() => { + swan.showToast({ + title: '我是标题', + icon: 'loading', + duration: 1000, + }); + swan.showLoading({ + title: '加载中', + mask: 'true' + }); + + setTimeout(() => { + swan.hideLoading(); + }, 2000); + + swan.showModal({ + title: '提示', + content: '这是一个模态弹窗', + cancelColor: '#999999', + confirmColor: '#0099cc', + success(res) { + if (res.confirm) { + console.log('用户点击了确定'); + } else if (res.cancel) { + console.log('用户点击了取消'); + } + } + }); + swan.showActionSheet({ + itemList: ['同意', '一般', '不同意'], + success(res) { + console.log(`用户点击了第${(res.tapIndex + 1)}个按钮`); + } + }); +})(); + +(() => { + swan.setNavigationBarTitle({ + title: '我是页面标题' + }); + swan.setNavigationBarColor({ + frontColor: '#ffffff', + backgroundColor: '#ff0000', + animation: { + duration: 500, + timingFunc: 'linear' + } + }); +})(); + +(() => { + swan.setTabBarBadge({ + index: 0, + text: '文本' + }); + swan.removeTabBarBadge({ + index: 0 + }); + swan.showTabBarRedDot({ + index: 0 + }); + swan.hideTabBarRedDot({ + index: 0 + }); + swan.setTabBarStyle({ + color: '#FFFFBD', + selectedColor: '#FFFFBD', + backgroundColor: '#FFFFBD', + borderStyle: 'white' + }); + swan.setTabBarItem({ + index: 0, + text: '文本', + // 图片路径 + iconPath: '/images/component_normal.png', + // 选中图片路径 + selectedIconPath: '/images/component_selected.png', + }); + swan.showTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.hideTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.navigateTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.redirectTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.switchTab({ + url: '/list', + }); + // 注意:调用 navigateTo 跳转时,调用页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码 + + // 当前是首页 + swan.navigateTo({ + url: 'list?key=value' + }); + + // 当前是列表页 + swan.navigateTo({ + url: 'detail?key=value' + }); + + // 在详情页内 navigateBack,将返回首页 + swan.navigateBack({ + delta: 2 + }); + swan.reLaunch({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); +})(); + +(() => { + const animation = swan.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 + }); + Page({ + data: { + animationData: {} + }, + starttoanimate() { + const animation = swan.createAnimation(); + animation.rotate(90).translateY(10).step(); + animation.rotate(-90).translateY(-10).step(); + this.setData({ + animationData: animation.export() + }); + } + }); +})(); + +(() => { + swan.pageScrollTo({ + scrollTop: 0, + duration: 300 + }); +})(); + +(() => { + Page({ + onPullDownRefresh() { + // do something + } + }); + swan.startPullDownRefresh(); + swan.stopPullDownRefresh(); +})(); + +(() => { + swan.createIntersectionObserver({} as any, { + selectAll: true + }).relativeTo('.container') + .observe('.ball', res => { + console.log(res.intersectionRect); // 相交区域 + console.log(res.intersectionRect.left); // 相交区域的左边界坐标 + console.log(res.intersectionRect.top); // 相交区域的上边界坐标 + console.log(res.intersectionRect.width); // 相交区域的宽度 + console.log(res.intersectionRect.height); // 相交区域的高度 + }); + Page({ + queryMultipleNodes() { + const query = swan.createSelectorQuery(); + query.select('#the-id').boundingClientRect(); + query.selectViewport().scrollOffset(); + query.exec((res) => { + // res[0].top, // #the-id节点的上边界坐标 + // res[1].scrollTop // 显示区域的竖直滚动位置 + }); + } + }); + Component({ + // queryMultipleNodes() { + // const query = swan.createSelectorQuery().in(this); + // query.select('#the-id').boundingClientRect((res) => { + // // res.top // 这个组件内 #the-id 节点的上边界坐标 + // }).exec(); + // } + }); + Page({ + getRect() { + swan.createSelectorQuery().select('#the-id').boundingClientRect((res) => { + const rect = res as swan.NodesRefRect; + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }).exec(); + }, + getAllRects() { + swan.createSelectorQuery().selectAll('.a-class').boundingClientRect((rects) => { + (rects as swan.NodesRefRect[]).forEach((rect) => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }); + }).exec(); + } + }); + Page({ + getScrollOffset() { + swan.createSelectorQuery().selectViewport().scrollOffset((res) => { + res.id; // 节点的ID + res.dataset; // 节点的dataset + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + }).exec(); + } + }); + Page({ + getFields() { + swan.createSelectorQuery().select('#the-id').fields({ + dataset: true, + size: true, + scrollOffset: true, + properties: ['scrollX', 'scrollY'], + computedStyle: ['margin', 'backgroundColor'] + }, (res) => { + res.dataset; // 节点的dataset + res.width; // 节点的宽度 + res.height; // 节点的高度 + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + res.scrollX; // 节点 scroll-x 属性的当前值 + res.scrollY; // 节点 scroll-y 属性的当前值 + // 此处返回指定要返回的样式名 + res.margin; + res.backgroundColor; + }).exec(); + } + }); +})(); + +(() => { + swan.getSystemInfo({ + success(res) { + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } + }); + try { + const res = swan.getSystemInfoSync(); + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } catch (e) { + // Do something when catch error + } + try { + const res = swan.getEnvInfoSync(); + console.log(res.appKey); + console.log(res.appName); + console.log(res.lastAppURL); + console.log(res.sdkVersion); + console.log(res.scheme); + } catch (e) { + // Do something when catch error + } + swan.canIUse('view.hover-class'); + swan.canIUse('scroll-view.scroll-x'); + swan.canIUse('cover-view'); + swan.canIUse('button.size.default'); + swan.canIUse('button.size.default'); + swan.canIUse('request.object.success.data'); + swan.canIUse('getSavedFileList'); + swan.canIUse('getSavedFileList.object'); + swan.canIUse('getSavedFileList.object.success'); +})(); + +(() => { + swan.onMemoryWarning((res) => { + console.log('onMemoryWarningReceive'); + }); +})(); + +(() => { + swan.getNetworkType({ + success(res) { + console.log(res.networkType); + } + }); + swan.onNetworkStatusChange((res) => { + console.log(res.isConnected); + console.log(res.networkType); + }); +})(); + +(() => { + swan.onAccelerometerChange((res) => { + console.log(res.x); + console.log(res.y); + console.log(res.z); + }); + swan.startAccelerometer({ + interval: 'ui' + }); + swan.stopAccelerometer(); +})(); + +(() => { + swan.onCompassChange((res) => { + console.log(res.direction); + }); + swan.startCompass(); + swan.stopCompass(); +})(); + +(() => { + swan.scanCode({ + success(res) { + console.log(res.result); + console.log(res.scanType); + } + }); +})(); + +(() => { + swan.onUserCaptureScreen(() => { + console.log('用户截屏了'); + }); +})(); + +(() => { + swan.makePhoneCall({ + phoneNumber: '000000' // 仅为示例,并非真实的电话号码 + }); +})(); + +(() => { + swan.setClipboardData({ + data: 'baidu', + success(res) { + swan.getClipboardData({ + success(res) { + console.log(res.data); // baidu + } + }); + } + }); + swan.getClipboardData({ + success(res) { + console.log(res.data); + } + }); +})(); + +(() => { + swan.getExtConfig({ + success(res) { + console.log(res.extConfig); + } + }); + const data = swan.getExtConfigSync(); + console.log(data.extConfig); +})(); + +(() => { + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址 + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('login fail', err); + } + }); + swan.checkSession({ + success(res) { + console.log('登录态有效'); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + swan.request({ + url: "https://xxx/decrypt_user_data", // 开发者服务器地址,对 data 进行解密 + data: { + data: res.data, + iv: res.iv + } + }); + } + }); + }, + fail(err) { + console.log('登录态无效'); + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址,用 code 换取 session_key + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('登录失败', err); + } + }); + } + }); + + try { + const result = swan.isLoginSync(); + console.log('isLoginSync', result); + } catch (e) { + console.log('error', e); + } +})(); + +(() => { + swan.authorize({ + scope: 'scope.userLocation', + success(res) { + // 用户已经同意智能小程序使用定位功能 + swan.getLocation(); + } + }); +})(); + +(() => { + swan.getSwanId({ + success(res) { + console.log(res.data.swanid); + } + }); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + } + }); +})(); + +(() => { + swan.openSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); + swan.getSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); +})(); + +(() => { + Page({ + onShareAppMessage() { + return { + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }; + } + }); + swan.openShare({ + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }); +})(); + +(() => { + swan.chooseAddress({ + success(res) { + console.log(res.userName); + console.log(res.postalCode); + console.log(res.provinceName); + console.log(res.cityName); + console.log(res.countyName); + console.log(res.detailInfo); + console.log(res.telNumber); + } + }); +})(); + +(() => { + swan.requestPolymerPayment({ + orderInfo: { + dealId: "470193086", + appKey: "MMMabc", + totalAmount: "1", + tpOrderId: "3028903626", + dealTitle: "智能小程序Demo支付测试", + signFieldsRange: 1, + rsaSign: '', + bizInfo: '' + }, + success(res) { + swan.showToast({ + title: '支付成功', + icon: 'success' + }); + }, + fail(err) { + swan.showToast({ + title: JSON.stringify(err) + }); + console.log('pay fail', err); + } + }); +})(); + +(() => { + swan.chooseInvoiceTitle({ + success(res) { + console.log(res.type); + console.log(res.title); + console.log(res.taxNumber); + console.log(res.companyAddress); + console.log(res.telephone); + console.log(res.bankName); + console.log(res.bankAccount); + } + }); +})(); + +(() => { + swan.navigateToSmartProgram({ + appKey: '4fecoAqgCIUtzIyA4FAPgoyrc4oUc25c', // 要打开的小程序 App Key + path: '', // 打开的页面路径,如果为空则打开首页 + extraData: { + foo: 'baidu' + }, + success(res) { + // 打开成功 + } + }); + swan.navigateBackSmartProgram({ + extraData: { + foo: 'baidu' + }, + success(res) { + // 返回成功 + } + }); +})(); + +(() => { + if (swan.setMetaDescription) { + swan.setMetaDescription({ + content: '当前小程序页面描述信息', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setMetaKeywords) { + swan.setMetaKeywords({ + content: '小程序, 关键字', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setDocumentTitle) { + swan.setDocumentTitle({ + title: '我是页面标题' + }); + } +})(); + +(() => { + swan.loadSubPackage({ + root: 'subpackage', + success(res) { + console.log('下载成功', res); + }, + fail(err) { + console.log('下载失败', err); + } + }); +})(); + +(() => { + const updateManager = swan.getUpdateManager(); + + updateManager.onCheckForUpdate((res) => { + // 请求完新版本信息的回调 + console.log(res.hasUpdate); + }); + + updateManager.onUpdateReady((res) => { + swan.showModal({ + title: '更新提示', + content: '新版本已经准备好,是否重启应用?', + success(res) { + if (res.confirm) { + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 + updateManager.applyUpdate(); + } + } + }); + }); + + updateManager.onUpdateFailed((res) => { + // 新的版本下载失败 + }); +})(); + +(() => { + // 打开调试 + swan.setEnableDebug({ + enableDebug: true + }); + + // 关闭调试 + swan.setEnableDebug({ + enableDebug: false + }); +})(); + +(() => { + swan.reportAnalytics('purchase', { + price: 120, + color: 'red' + }); +})(); diff --git a/types/baidu-app/index.d.ts b/types/baidu-app/index.d.ts new file mode 100644 index 0000000000..244e9dd473 --- /dev/null +++ b/types/baidu-app/index.d.ts @@ -0,0 +1,4758 @@ +// Type definitions for swan-app 2.2 +// Project: https://smartprogram.baidu.com/docs/develop/tutorial/codedir/ +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +declare namespace swan { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: string | ArrayBuffer; + statusCode: number; + header: any; + result: string; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + /** 开发者服务器返回的 HTTP 状态码 */ + statusCode: number; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion + // #region 网络API列表 + // 发起请求 + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | object; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE"; + /** 如果设为json,会尝试对返回的数据做一次 JSON.parse 默认值为json */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer 默认值为text + * @version 1.7.0 + */ + responseType?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + fail?(err: { errCode: number; errMsg: string; }): void; + } + /** + * swan.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): RequestTask; + + /** + * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 + */ + interface RequestTask { + abort(): void; + } + + interface UploadTask { + /** + * 监听上传进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 上传进度百分比 */ + progress: number; + /** 已经上传的数据长度,单位 Bytes */ + totalBytesSent: number; + /** 预期需要上传的数据总长度,单位 Bytes */ + totalBytesExpectedToSend: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + // 上传下载 + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + } + interface UploadFileResponse { + data: string; // 开发者服务器返回的数据 + statusCode: number; // 开发者服务器返回的 HTTP 状态码 + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 swan.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): UploadTask; + interface DownloadTask { + /** + * 监听下载进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 下载进度百分比 */ + progress: number; + /** 已经下载的数据长度,单位 Bytes */ + totalBytesWritten: number; + /** 预期需要下载的数据总长度,单位 Bytes */ + totalBytesExpectedToWrite: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + interface DownloadFileOptions extends BaseOptions { + /** 下载资源的 url */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): DownloadTask; + // WebSocket + interface ConnectSocketOptions extends BaseOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** + * 子协议数组 + * @version 1.4.0 + */ + protocols?: string[]; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: (res: any) => void): void; + /** 监听WebSocket错误。 */ + function onSocketError(callback: (error: any) => void): void; + interface SendSocketMessageOptions extends BaseOptions { + /** 需要发送的内容 */ + data: string | ArrayBuffer; + } + /** + * 通过 WebSocket 连接发送数据,需要先 swan.connectSocket, + * 并在 swan.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: DataResponse) => void): void; + /** + * 关闭WebSocket连接。 + */ + interface CloseSocketOptions extends BaseOptions { + code?: number; // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) 1.4.0 + reason?: string; // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + } + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(options?: CloseSocketOptions): void; + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: (res: any) => void): void; + /** + * 在接入AI之前需要使用管理员权限操作详细情况官网 + * https://smartprogram.baidu.com/docs/develop/api/ai/ + */ + // #region AI + namespace ai { + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + interface ocrIdCardOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false: 不检测旋转角度,默认不检测。 + id_card_side?: string; // front:身份证含照片的一面;back:身份证带国徽的一面。 + detect_risk?: boolean; // 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启。 + success?(res: ocrIdCardResponse): void; + } + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + interface ocrBankCardOptions extends BaseOptions { + image: string; // 图片资源地址 + success?(res: ocrBankCardResponse): void; + } + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + interface ocrDrivingLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true;false:不检测旋转角度,默认不检测。 + unified_valid_period?: boolean; // true: 归一化格式输出;false 或无此参数按非归一化格式输出。 + success?(res: ocrDrivingLicenseResponse): void; + } + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + interface ocrVehicleLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false:不检测旋转角度,默认不检测。 + accuracy?: string; // normal 使用快速服务,1200ms左右时延;缺省或其它值使用高精度服务,1600ms左右时延。 + success?(res: ocrVehicleLicenseResponse): void; + } + interface ocrIdCardResponse { + direction: number; // 图像方向,当 detect_direction=true 时存在。-1: 未定义,0: 正向,1: 逆时针90度,2: 逆时针180度,3: 逆时针270度。 + image_status: string; // normal-识别正常;reversed_side-身份证正反面颠倒;non_idcard-上传的图片中不包含身份证;blurred-身份证模糊;other_type_card-其他类型证照;over_exposure-身份证关键字段反光或过曝;unknown-未知状态。 + risk_type: string; // 输入参数 detect_risk = true 时,则返回该字段识别身份证类型: normal-正常身份证;copy-复印件;temporary-临时身份证;screen-翻拍;unknown-其他未知情况。 + edit_tool: string; // 如果参数 detect_risk = true 时,则返回此字段。如果检测身份证被编辑过,该字段指定编辑软件名称,如:Adobe Photoshop CC 2014 (Macintosh),如果没有被编辑过则返回值无此参数。 + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示words_result的元素个数。 + words_result: { // 定位和识别结果 + [key: string]: { + location: { // 位置数组(坐标0点为左上角) + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高。 + } + words: string; // 识别结果字符串 + } + }; + } + interface ocrBankCardResponse { + log_id: string; // 请求标识码,随机数,唯一。 + result: { // 返回结果 + bank_card_number: string; // 银行卡卡号 + bank_name: string; // 银行名,不能识别时为空 。 + bank_card_type: string; // 银行卡类型,0: 不能识别; 1: 借记卡; 2: 信用卡 。 + }; + } + interface ocrDrivingLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + interface ocrVehicleLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + function ocrIdCard(options: ocrIdCardOptions): void; + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + function ocrBankCard(options: ocrBankCardOptions): void; + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + function ocrDrivingLicense(options: ocrDrivingLicenseOptions): void; + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + function ocrVehicleLicense(options: ocrVehicleLicenseOptions): void; + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + interface textReviewOptions extends BaseOptions { + content: string; // 待审核文本,UTF-8,不可为空,不超过20000字节。 + success?(res: textReviewResponse): void; + } + interface textReviewResponse { + log_id: string; // 唯一的log id,用于问题定位。 + result: { // 审核结果详情 + spam: number; // 请求中是否包含违禁,0表示非违禁,1表示违禁,2表示建议人工复审 。 + reject: any[]; // 审核未通过的类别列表与详情 + review: any[]; // 待人工复审的类别列表与详情 + pass: Array<{ // 审核通过的类别列表与详情 + label: number; // 请求中的违禁类型 + score: number; // 违禁检测分,范围 0~1,数值从低到高代表风险程度的高低 。 + hit: string[]; // 违禁类型对应命中的违禁词集合,可能为空 。 + }>; + }; + /** + * 违禁labels类型说明: + * 值 说明 + * 1 暴恐违禁 + * 2 文本色情 + * 3 政治敏感 + * 4 恶意推广 + * 5 低俗辱骂 + */ + } + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + function textReview(options: textReviewOptions): void; + /** + * 将文本转换为可以播放的mp3文件。 + */ + interface textToAudioOptions extends BaseOptions { + tex: string; // 合成的文本,使用UTF-8编码,小于512个中文字或者英文数字(文本在百度服务器内转换为GBK后,长度必须小于1024字节)。 + ctp?: string | number; // 客户端类型选择,Web端填写固定值1。 + lan?: string; // 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh。 + spd?: string; // 语速,取值0-9,默认为5中语速。 + pit?: string; // 音调,取值0-9,默认为5中语调。 + vol?: string; // 音量,取值0-9,默认为5中音量。 + per?: string; // 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声。 + success?(res: textToAudioResponse): void; + } + interface textToAudioResponse { + filePath: string; + } + /** + * 将文本转换为可以播放的mp3文件。 + */ + function textToAudio(options: textToAudioOptions): void; + /** + * 自定义图像审核。 + */ + interface imageAuditOptions extends BaseOptions { + image: string; // 图像资源地址 + imgUrl?: string; // 网图URL地址,以网图形式请求,图片Url需要做UrlEncode,不能与image并存。 + success?(res: imageAuditResponse): void; + } + interface imageAuditResponse { + log_id: string; // 请求唯一id + conclusion: string; // 审核结果描述,成功才返回,失败不返回。 + conclusionType: number; // 审核结果标识,成功才返回,失败不返回。 + data: imageAuditdata[]; + // 审核项详细信息,响应成功并且conclusion为疑似或不合规时才返回,响应失败或conclusion为合规是不返回。 + } + interface imageAuditdata { + type: number; + msg: number; + probability: number; + stars: imageAuditdata[]; + words: number; + } + /** + * 自定义图像审核。 + */ + function imageAudit(options: imageAuditOptions): void; + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + interface GeneralIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: GeneralIdentifyResponse): void; + } + interface GeneralIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 标签结果数组 + keyword: string; // 图片中的物体或场景名称 + score: number; // 置信度,0-1 + root: string; // 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签。 + }>; + } + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + function advancedGeneralIdentify(options: GeneralIdentifyOptions): void; + /** + * 用户向服务请求检测图像中的主体位置。 + */ + interface DetectIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + with_face?: number; // 如果检测主体是人,主体区域是否带上人脸部分,0-不带人脸区域,其他-带人脸区域,裁剪类需求推荐带人脸,检索/识别类需求推荐不带人脸。默认取1,带人脸。 + success?(res: DetectIdentifyResponse): void; + } + interface DetectIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: { // 裁剪结果 + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高度。 + }; + } + /** + * 用户向服务请求检测图像中的主体位置。 + */ + function objectDetectIdentify(options: DetectIdentifyOptions): void; + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + interface carClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + color_result?: string; // 颜色 + top_num?: number; // 返回结果top n,默认5。 + success?(res: carClassifyResponse): void; + } + interface carClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ + name: string; // 车型名称,示例:宝马x6 + score: number; // 置信度,示例:0.5321 + year: string; // 年份 + }>; + location_result: { // 车在图片中的位置信息 + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; + } + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + function carClassify(options: carClassifyOptions): void; + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + interface dishClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + filter_threshold?: number; // 默认0.95,可以通过该参数调节识别效果,降低非菜识别率. + top_num?: number; // 返回结果top n,默认5。 + success?(res: dishClassifyResponse): void; + } + interface dishClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 菜品识别结果数组 + name: string; // 菜名,示例:鱼香肉丝。 + calorie: number; // 卡路里,每100g的卡路里含量。 + probability: number; // 识别结果中每一行的置信度值,0-1。 + }>; + } + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + function dishClassify(options: dishClassifyOptions): void; + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + interface logoClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + custom_lib?: boolean; // 是否只检索用户子库,true则只检索用户子库,false(默认)为检索底库+用户子库。 + success?(res: logoClassifyResponse): void; + } + interface logoClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + type: number; // type=0 为1千种高优商标识别结果;type=1 为2万类logo库的结果;其它type为自定义logo库结果。 + name: number; // 识别的品牌名称 + probability: number; // 分类结果置信度(0–1.0) + location: { + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; // 位置信息(左起像素位置、上起像素位置、像素宽、像素高) + }>; + } + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + function logoClassify(options: logoClassifyOptions): void; + /** + * 用于检测和识别图片中的动物信息 + */ + interface animalClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + top_num?: number; // 返回预测得分top结果数,默认为6 + success?(res: animalClassifyResponse): void; + } + interface animalClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + name: number; // 动物名称,示例:蒙古马。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的动物信息 + */ + function animalClassify(options: animalClassifyOptions): void; + /** + * 用于检测和识别图片中的植物信息 + */ + interface plantClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: plantClassifyResponse): void; + } + interface plantClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ // 菜品识别结果数组 + name: number; // 植物名称,示例:吉娃莲。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的植物信息 + */ + function plantClassify(options: plantClassifyOptions): void; + + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + interface VoiceRecognizerStart { + mode?: string; // 听音模式,有效值dnn/touch + longSpeech?: boolean; // 是否开启长语音 + context?: string; // 语音识别所用的场景值,有效值见下表格。 + } + interface VoiceRecognizeResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceErrorResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceRecognizerTask { + start(options: VoiceRecognizerStart): void; // 开始; + stop(): void; // 停止; + cancel(): void; // 取消; + onStart(callback: () => void): void; // 引擎准备就绪,可以开始说话; + onRecognize(callback: (res: VoiceRecognizeResponse) => void): void; // ;有识别结果返回 + onFinish(callback: (res: DataResponse) => void): void; // 识别完成; + onError(callback: (res: VoiceErrorResponse) => void): void; // 识别遇到错;误 + } + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + function getVoiceRecognizer(): VoiceRecognizerTask; + } + // #endregion + + // #endregion + // #region 媒体API列表 + // 媒体-----图片 + type ImageSizeType = "original" | "compressed"; + type ImageSourceType = "album" | "camera"; + type VideoSourceType = "album" | "camera"; + type CameraDevice = "front" | "back"; + interface TempFile { + /** 本地文件路径 */ + path: string; + /** 本地文件大小,单位:B */ + size: number; + } + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + /** + * 图片的本地文件列表,每一项是一个 File 对象 + * @version 1.2.0 + */ + tempFiles: TempFile[]; + } + interface ChooseImageOptions extends BaseOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: ImageSizeType[]; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: TempFilesData): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + interface PreviewImageOptions extends BaseOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + src: string; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + interface SaveImageToPhotosAlbumOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + filePath: string; + success(res: { errMsg: string }): void; + } + /** + * 保存图片到系统相册。 + * 需要用户授权 scope.writePhotosAlbum + * @version 1.2.0 + */ + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; + // 媒体-----录音 + interface StartRecordAudioOptions extends BaseOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 开始录音。当主动调用swan.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用swan.saveFile,在小程序下次启动时才能访问得到。 + * @deprecated 1.6.0 + */ + function startRecord(options: StartRecordAudioOptions): void; + + interface StopRecordAudioOptions extends BaseOptions { + success?(res: TempFileResponse): void; + } + /** + * 主动调用停止录音。 + */ + function stopRecord(options?: StopRecordAudioOptions): void; + type EncodeBitRate = + | 8000 + | 11025 + | 12000 + | 16000 + | 22050 + | 24000 + | 32000 + | 44100 + | 48000; + interface RecorderManagerStartOptions { + /** + * 指定录音的时长,单位 ms + * 如果传入了合法的 duration + * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) + */ + duration?: number; + /** + * 采样率,有效值 8000/16000/44100 + */ + sampleRate?: number; + /** + * 否 录音通道数,有效值 1/2 + */ + numberOfChannels?: number; + /** + * 编码码率 + * 采样率和码率有一定要求,具体有效值如下: + * 采样率 编码码率 + * + 8000 16000 ~ 48000 + * + 11025 16000 ~ 48000 + * + 12000 24000 ~ 64000 + * + 16000 24000 ~ 96000 + * + 22050 32000 ~ 128000 + * + 24000 32000 ~ 128000 + * + 32000 48000 ~ 192000 + * + 44100 64000 ~ 320000 + * + 48000 64000 ~ 320000 + */ + encodeBitRate: number; + /** 音频格式,有效值 aac/mp3 */ + format: string; + } + interface OnRecorderManagerStopOptions { + tempFilePath: string; + } + interface OnFrameRecordedOptions { + /** 录音分片结果数据 */ + frameBuffer: ArrayBuffer; + /** 当前帧是否正常录音结束前的最后一帧 */ + isLastFrame: boolean; + } + interface RecorderManager { + /** 开始录音 */ + start(options?: RecorderManagerStartOptions): void; + /** 暂停录音 */ + pause(): void; + /** 继续录音 */ + resume(): void; + /** 停止录音 */ + stop(): void; + /** 录音开始事件 */ + onStart(callback?: () => void): void; + /** 录音暂停事件 */ + onPause(callback?: () => void): void; + /** 录音恢复事件 */ + onResume(callback?: () => void): void; + /** 录音停止事件,会回调文件地址 */ + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; + /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; + /** 录音错误事件, 会回调错误信息 */ + onError(callback?: (err: ErrMsgResponse) => void): void; + } + /** + * 获取全局唯一的录音管理器 recorderManager + * @version 1.6.0 + */ + function getRecorderManager(): RecorderManager; + // 媒体-----音频播放控制 + interface PlayVoiceOptions extends BaseOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + * @deprecated 1.6.0 + */ + function playVoice(options: PlayVoiceOptions): void; + /** + * 暂停正在播放的语音。 + * 再次调用swan.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 swan.stopVoice。 + * @deprecated 1.6.0 + */ + function pauseVoice(): void; + /** + * 结束播放语音。 + * @deprecated 1.6.0 + */ + function stopVoice(): void; + // 媒体-----音乐播放控制 + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl: string; + } + interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { + /** 接口调用成功的回调函数 */ + success?(state: BackgroundAudioPlayerState): void; + /** 接口调用失败的回调函数 */ + fail?(): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(): void; + } + /** + * 获取音乐播放状态。 + * @deprecated 1.2.0 + */ + function getBackgroundAudioPlayerState( + options: GetBackgroundAudioPlayerStateOptions + ): void; + interface PlayBackgroundAudioOptions extends BaseOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + } + /** + * 播放音乐,同时只能有一首音乐正在播放。 + * @deprecated 1.2.0 + */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + /** + * 暂停播放音乐。 + * @deprecated 1.2.0 + */ + function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + interface SeekBackgroundAudioOptions extends BaseOptions { + /** 音乐位置,单位:秒 */ + position: number; + } + /** + * 控制音乐播放进度。 + * @deprecated 1.2.0 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + /** + * 停止播放音乐。 + * @deprecated 1.2.0 + */ + function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + /** + * 监听音乐播放。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPlay(callback: () => void): void; + /** + * 监听音乐暂停。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPause(callback: () => void): void; + /** + * 监听音乐停止。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioStop(callback: () => void): void; + interface BackgroundAudioManager { + /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ + readonly duration: number; + /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ + readonly currentTime: number; + /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ + readonly paused: boolean; + /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ + src?: string; + /** 音频开始播放的位置(单位:s) */ + startTime?: number; + /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ + buffered: number; + /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ + title?: string; + /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + epname?: string; + /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + singer?: string; + /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ + coverImgUrl?: string; + /** 播放 */ + play(): void; + /** 暂停 */ + pause(): void; + /** 停止 */ + stop(): void; + /** 跳转到指定位置,单位 s */ + seek(position: number): void; + /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ + onCanplay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放事件 */ + onPlay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频暂停事件 */ + onPause(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频停止事件 */ + onStop(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频自然播放结束事件 */ + onEnded(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放进度更新事件 */ + onTimeUpdate(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放错误事件 */ + onError(callback: (res: ErrCodeResponse) => void): void; + /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ + onWaiting(callback: (res: ErrCodeResponse) => void): void; + } + /** + * 获取全局唯一的背景音频管理器 backgroundAudioManager。 + * @version 1.2.0 + */ + function getBackgroundAudioManager(): BackgroundAudioManager; + // 媒体-----音频组件控制 + /** + * audioContext 通过 audioId 跟一个

- * With a flaky connection it is pretty common that the browser disconnects, - * but the actual test execution is still running without any problems. Karma does not treat a disconnection - * as immediate failure and will wait browserDisconnectTimeout (ms). - * If the browser reconnects during that time, everything is fine. - *

- */ - browserDisconnectTimeout?: number; - /** - * @default 0 - * @description The number of disconnections tolerated. - *

- * The disconnectTolerance value represents the maximum number of tries a browser will attempt - * in the case of a disconnection. Usually any disconnection is considered a failure, - * but this option allows you to define a tolerance level when there is a flaky network link between - * the Karma server and the browsers. - *

- */ - browserDisconnectTolerance?: number; - /** - * @default 10000 - * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). - *

- * If, during test execution, Karma does not receive any message from a browser within - * browserNoActivityTimeout (ms), it will disconnect from the browser - *

- */ - browserNoActivityTimeout?: number; - /** - * @default [] - * Possible Values: - *
    - *
  • Chrome (launcher comes installed with Karma)
  • - *
  • ChromeCanary (launcher comes installed with Karma)
  • - *
  • PhantomJS (launcher comes installed with Karma)
  • - *
  • Firefox (launcher requires karma-firefox-launcher plugin)
  • - *
  • Opera (launcher requires karma-opera-launcher plugin)
  • - *
  • Internet Explorer (launcher requires karma-ie-launcher plugin)
  • - *
  • Safari (launcher requires karma-safari-launcher plugin)
  • - *
- * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser - * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. - * You can capture any browser manually by opening the browser and visiting the URL where - * the Karma web server is listening (by default it is http://localhost:9876/). - */ - browsers?: string[]; - /** - * @default 60000 - * @description Timeout for capturing a browser (in ms). - *

- * The captureTimeout value represents the maximum boot-up time allowed for a - * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma - * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. - *

- */ - captureTimeout?: number; - client?: ClientOptions; - /** - * @default true - * @description Enable or disable colors in the output (reporters and logs). - */ - colors?: boolean; - /** - * @default 'Infinity' - * @description How many browsers Karma launches in parallel. - * Especially on services like SauceLabs and Browserstack, it makes sense only to launch a limited - * amount of browsers at once, and only start more when those have finished. Using this configuration, - * you can specify how many browsers should be running at once at any given point in time. - */ - concurrency?: number; - customLaunchers?: { [key: string]: CustomLauncher }; - /** - * @default [] - * @description List of files/patterns to exclude from loaded files. - */ - exclude?: string[]; - /** - * @default [] - * @description List of files/patterns to load in the browser. - */ - files?: Array; - /** - * @default [] - * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... - * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). - */ - frameworks?: string[]; - /** - * @default 'localhost' - * @description Hostname to be used when capturing browsers. - */ - hostname?: string; - /** - * @default {} - * @description Options object to be used by Node's https class. - * Object description can be found in the - * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) - */ - httpsServerOptions?: https.ServerOptions; - /** - * @default config.LOG_INFO - * Possible values: - *
    - *
  • config.LOG_DISABLE
  • - *
  • config.LOG_ERROR
  • - *
  • config.LOG_WARN
  • - *
  • config.LOG_INFO
  • - *
  • config.LOG_DEBUG
  • - *
- * @description Level of logging. - */ - logLevel?: string; - /** - * @default [{type: 'console'}] - * @description A list of log appenders to be used. See the documentation for [log4js] for more information. - */ - loggers?: { [name: string]: Appender } | Appender[]; - /** - * @default [] - * @description List of names of additional middleware you want the - * Karma server to use. Middleware will be used in the order listed. - * You must have installed the middleware via a plugin/framework - * (either inline or via NPM). Additional information can be found in - * [plugins](http://karma-runner.github.io/2.0/config/plugins.html). - * The plugin must provide an express/connect middleware function - * (details about this can be found in the - * [Express](http://expressjs.com/guide/using-middleware.html) docs). - */ - middleware?: string[]; - /** - * @default {} - * @description Redefine default mapping from file extensions to MIME-type. - * Set property name to required MIME, provide Array of extensions (without dots) as it's value. - */ - mime?: {[type: string]: string[]}; - /** - * @default ['karma-*'] - * @description List of plugins to load. A plugin can be a string (in which case it will be required - * by Karma) or an inlined plugin - Object. - * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. - * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). - */ - plugins?: any[]; - /** - * @default 9876 - * @description The port where the web server will be listening. - */ - port?: number; - /** - * @default {'**\/*.coffee': 'coffee'} - * @description A map of preprocessors to use. - * - * Preprocessors can be loaded through [plugins]. - * - * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) - * require an additional library to be installed (via NPM). - * - * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, - * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug - * your tests, you'll discover that your expected source code is completely changed from what you expected. Because - * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, - * but your interactive debugging does not. - * - */ - preprocessors?: { [name: string]: string | string[] }; - /** - * @default 'http:' - * Possible Values: - *
    - *
  • http:
  • - *
  • https:
  • - *
- * @description Protocol used for running the Karma webserver. - * Determines the use of the Node http or https class. - * Note: Using 'https:' requires you to specify httpsServerOptions. - */ - protocol?: string; - /** - * @default {} - * @description A map of path-proxy pairs. - */ - proxies?: { [path: string]: string }; - /** - * @default true - * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. - */ - proxyValidateSSL?: boolean; - /** - * @default 0 - * @description Karma will report all the tests that are slower than given time limit (in ms). - * This is disabled by default (since the default value is 0). - */ - reportSlowerThan?: number; - /** - * @default ['progress'] - * Possible Values: - *
    - *
  • dots
  • - *
  • progress
  • - *
- * @description A list of reporters to use. - * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. - * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). - */ - reporters?: string[]; - /** - * @default false - * @description Continuous Integration mode. - * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending - * on whether all tests passed or any tests failed. - */ - singleRun?: boolean; - /** - * @default ['polling', 'websocket'] - * @description An array of allowed transport methods between the browser and testing server. This configuration setting - * is handed off to [socket.io](http://socket.io/) (which manages the communication - * between browsers and the testing server). - */ - transports?: string[]; - /** - * @default '/' - * @description The base url, where Karma runs. - * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as - * sometimes you might want to proxy a url that is already taken by Karma. - */ - urlRoot?: string; - } - - interface ClientOptions { - /** - * @default undefined - * @description When karma run is passed additional arguments on the command-line, they - * are passed through to the test adapter as karma.config.args (an array of strings). - * The client.args option allows you to set this value for actions other than run. - * How this value is used is up to your test adapter - you should check your adapter's - * documentation to see how (and if) it uses this value. - */ - args?: string[]; - /** - * @default true - * @description Run the tests inside an iFrame or a new window - * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an - * iFrame and may need a new window to run. - */ - useIframe?: boolean; - /** - * @default true - * @description Capture all console output and pipe it to the terminal. - */ - captureConsole?: boolean; - /** - * @default false - * @description Run the tests on the same window as the client, without using iframe or a new window - */ - runInParent?: boolean; - /** - * @default true - * @description Clear the context window - * If true, Karma clears the context window upon the completion of running the tests. - * If false, Karma does not clear the context window upon the completion of running the tests. - * Setting this to false is useful when embedding a Jasmine Spec Runner Template. - */ - clearContext?: boolean; - } - - interface FilePattern { - /** - * The pattern to use for matching. This property is mandatory. - */ - pattern: string; - /** - * @default true - * @description If autoWatch is true all files that have set watched to true will be watched - * for changes. - */ - watched?: boolean; - /** - * @default true - * @description Should the files be included in the browser using \n' + + "but do b.ca", + { + 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); + } + } +}); diff --git a/types/linkifyjs/tsconfig.json b/types/linkifyjs/tsconfig.json new file mode 100644 index 0000000000..52b1940fcd --- /dev/null +++ b/types/linkifyjs/tsconfig.json @@ -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 + }, + "files": [ + "index.d.ts", + "html.d.ts", + "linkifyjs-tests.ts" + ] +} diff --git a/types/linkifyjs/tslint.json b/types/linkifyjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/linkifyjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ltx/index.d.ts b/types/ltx/index.d.ts index 33311a3175..1c313c5541 100644 --- a/types/ltx/index.d.ts +++ b/types/ltx/index.d.ts @@ -1,17 +1,17 @@ -// Type definitions for ltx 2.6 +// Type definitions for ltx 2.8 // Project: github.com/node-xmpp/ltx/ // Definitions by: PJakcson +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -export {Element } from './lib/Element'; -export {nameEqual, attrsEqual, childrenEqual, equal} from './lib/equal'; -export {isNode, isElement, isText} from './lib/is'; -export {clone} from './lib/clone'; -export {createElement} from './lib/createElement'; -export {escapeXML, unescapeXML, escapeXMLText, unescapeXMLText} from './lib/escape'; -export {Parser} from './lib/Parser'; -export {parse} from './lib/parse'; -export {tag} from './lib/tag'; -export {tagString} from './lib/tagString'; -export {stringify} from './lib/stringify'; +export * from './lib/Element'; +export * from './lib/equal'; +export * from './lib/is'; +export * from './lib/clone'; +export * from './lib/createElement'; +export * from './lib/escape'; +export * from './lib/Parser'; +export * from './lib/parse'; +export * from './lib/tag'; +export * from './lib/tagString'; +export * from './lib/stringify'; diff --git a/types/ltx/lib/Element.d.ts b/types/ltx/lib/Element.d.ts index 203eaa93b6..7f0d3de62e 100644 --- a/types/ltx/lib/Element.d.ts +++ b/types/ltx/lib/Element.d.ts @@ -1,21 +1,26 @@ +import { clone } from './clone'; + +export type Node = Element | TextNode; +export type TextNode = string | number; + /** * Element * * Attributes are in the element.attrs object. Children is a list of * either other Elements or Strings for text content. - **/ -export declare class Element { + */ +export class Element { name: string; - parent: Element; + parent: Element | null; children: Element[]; - attrs: any; + attrs: { [attrName: string]: any }; - constructor(name: string, attrs?: any); + constructor(name: string, attrs?: string | { [attrName: string]: any }); /** * if (element.is('message', 'jabber:client')) ... - **/ - is(name: string, xmlns?: any): boolean; + */ + is(name: string, xmlns?: string): boolean; /** * without prefix. @@ -24,50 +29,44 @@ export declare class Element { /** * retrieves the namespace of the current element, upwards recursively - **/ - getNS(): any; + */ + getNS(): string | undefined; /** * find the namespace to the given prefix, upwards recursively - **/ - findNS(prefix: string): any; + */ + findNS(prefix: string): string | undefined; /** * Recursiverly gets all xmlns defined, in the form of {url:prefix} - **/ - getXmlns(): any; + */ + getXmlns(): { [key: string]: string }; - setAttrs(attrs: any): void; + setAttrs(attrs: string | { [attrName: string]: any }): void; /** - * xmlns can be null, returns the matching attribute. - **/ - getAttr(name: string, xmlns?: any): any; + * returns the matching attribute. + */ + getAttr(name: string, xmlns?: string): any; - /** - * xmlns can be null - **/ - getChild(name: string, xmlns?: any): Element; + getChild(name: string, xmlns?: string): Element | undefined; - /** - * xmlns can be null - **/ - getChildren(name: string, xmlns?: any): Element[]; + getChildren(name: string, xmlns?: string): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element; + getChildByAttr( + attr: string, + val: any, + xmlns?: string, + recursive?: boolean + ): Element | undefined; + getChildrenByAttr(attr: string, val: any, xmlns?: string, recursive?: boolean): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildrenByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element[]; + getChildrenByFilter(filter: (child: Node) => boolean, recursive?: boolean): Element[]; getText(): string; - getChildText(name: string, xmlns?: any): string; + getChildText(name: string, xmlns?: string): string | null; /** * Return all direct descendents that are Elements. @@ -77,37 +76,39 @@ export declare class Element { getChildElements(): Element[]; /** returns uppermost parent */ - root(): Element; + root(): Element | this; - tree(): Element; + tree(): Element | this; /** just parent or itself */ - up(): Element; + up(): Element | this; /** create child node and return it */ - c(name: string, attrs?: any): Element; + c(name: string, attrs?: { [key: string]: any }): Element; + + cnode(child: T): T; /** add text node and return element */ - t(text: string): Element; + t(text: TextNode): this; /** * Either: * el.remove(childEl) * el.remove('author', 'urn:...') */ - remove(el: Element, xmlns?: any): Element; + remove(el: Element | string, xmlns?: string): this; - clone(): Element; + clone: typeof clone; - text(val: string): string; + text(val?: string): string; - attr(attr: any, val: any): any; + attr(attr: string, val?: any): any; toString(): string; - toJSON(): any; + toJSON(): ElementJson; - write(writer: any): void; + write(writer: (part: string) => void): void; nameEquals(el: Element): boolean; @@ -117,3 +118,9 @@ export declare class Element { equals(el: Element): boolean; } + +export interface ElementJson { + name: string; + attrs: { [attrName: string]: any }; + children: Array; +} diff --git a/types/ltx/lib/Parser.d.ts b/types/ltx/lib/Parser.d.ts index 083e3ace66..463029286f 100644 --- a/types/ltx/lib/Parser.d.ts +++ b/types/ltx/lib/Parser.d.ts @@ -1,5 +1,15 @@ /// import { EventEmitter } from 'events'; -export declare class Parser extends EventEmitter { - constructor(options?: any); +import { Element } from './Element'; + +export class Parser extends EventEmitter { + constructor(options?: ParserOptions); + + write(data: string): void; + end(data: string): void; +} + +export interface ParserOptions { + Parser?: typeof Parser; + Element?: typeof Element; } diff --git a/types/ltx/lib/clone.d.ts b/types/ltx/lib/clone.d.ts index 41193a3f40..15369e00d5 100644 --- a/types/ltx/lib/clone.d.ts +++ b/types/ltx/lib/clone.d.ts @@ -1 +1,3 @@ -export declare function clone(el: any): any; +import { Element } from './Element'; + +export function clone(el: T): T; diff --git a/types/ltx/lib/createElement.d.ts b/types/ltx/lib/createElement.d.ts index c372f11150..21527ae1b6 100644 --- a/types/ltx/lib/createElement.d.ts +++ b/types/ltx/lib/createElement.d.ts @@ -1,2 +1,6 @@ -import { Element } from './Element'; -export declare function createElement(name: string, attrs: any): Element; +import { Element, Node } from './Element'; +export function createElement( + name: string, + attrs?: string | { [attrName: string]: any }, + ...children: Node[] +): Element; diff --git a/types/ltx/lib/equal.d.ts b/types/ltx/lib/equal.d.ts index 520555e098..f7548c526b 100644 --- a/types/ltx/lib/equal.d.ts +++ b/types/ltx/lib/equal.d.ts @@ -1,4 +1,6 @@ -export declare function nameEqual(a: any, b: any): boolean; -export declare function attrsEqual(a: any, b: any): boolean; -export declare function childrenEqual(a: any, b: any): boolean; -export declare function equal(a: any, b: any): boolean; +import { Element } from './Element'; + +export function nameEqual(a: Element, b: Element): boolean; +export function attrsEqual(a: Element, b: Element): boolean; +export function childrenEqual(a: Element, b: Element): boolean; +export function equal(a: Element, b: Element): boolean; diff --git a/types/ltx/lib/escape.d.ts b/types/ltx/lib/escape.d.ts index 4bc45c223a..d390e860ed 100644 --- a/types/ltx/lib/escape.d.ts +++ b/types/ltx/lib/escape.d.ts @@ -1,4 +1,4 @@ -export declare function escapeXML(s: string): string; -export declare function unescapeXML(s: string): string; -export declare function escapeXMLText(s: string): string; -export declare function unescapeXMLText(s: string): string; +export function escapeXML(s: string): string; +export function unescapeXML(s: string): string; +export function escapeXMLText(s: string): string; +export function unescapeXMLText(s: string): string; diff --git a/types/ltx/lib/is.d.ts b/types/ltx/lib/is.d.ts index 6515d23f80..e62d919267 100644 --- a/types/ltx/lib/is.d.ts +++ b/types/ltx/lib/is.d.ts @@ -1,3 +1,5 @@ -export declare function isNode(el: any): boolean; -export declare function isElement(el: any): boolean; -export declare function isText(el: any): boolean; +import { Element, Node } from './Element'; + +export function isNode(el: any): el is Node; +export function isElement(el: any): el is Element; +export function isText(el: any): el is string; diff --git a/types/ltx/lib/parse.d.ts b/types/ltx/lib/parse.d.ts index cc4073113a..0e0a9b17cb 100644 --- a/types/ltx/lib/parse.d.ts +++ b/types/ltx/lib/parse.d.ts @@ -1 +1,4 @@ -export declare function parse(data: any, options?: any): any; +import { ParserOptions, Parser } from './Parser'; +import { Element } from './Element'; + +export function parse(data: string, options?: ParserOptions | Parser): Element; diff --git a/types/ltx/lib/stringify.d.ts b/types/ltx/lib/stringify.d.ts index 770f7d324f..9913f2318c 100644 --- a/types/ltx/lib/stringify.d.ts +++ b/types/ltx/lib/stringify.d.ts @@ -1 +1,3 @@ -export declare function stringify(el: any, indent: any, level: any): string; +import { Element } from './Element'; + +export function stringify(el: Element, indent?: number, level?: number): string; diff --git a/types/ltx/lib/tag.d.ts b/types/ltx/lib/tag.d.ts index 8bbcb6fe7b..11a9784bf0 100644 --- a/types/ltx/lib/tag.d.ts +++ b/types/ltx/lib/tag.d.ts @@ -1 +1,3 @@ -export declare function tag(d: any): any; +import { Element } from './Element'; + +export function tag(literals: string[], ...substitutions: string[]): Element; diff --git a/types/ltx/lib/tagString.d.ts b/types/ltx/lib/tagString.d.ts index 44036ce037..619ccbdb23 100644 --- a/types/ltx/lib/tagString.d.ts +++ b/types/ltx/lib/tagString.d.ts @@ -1 +1 @@ -export declare function tagString(d: any): string; +export function tagString(literals: string[], ...substitutions: string[]): string; diff --git a/types/ltx/ltx-tests.ts b/types/ltx/ltx-tests.ts index 522b7673c8..a7342ef54b 100644 --- a/types/ltx/ltx-tests.ts +++ b/types/ltx/ltx-tests.ts @@ -1,21 +1,147 @@ import * as ltx from 'ltx'; -ltx.parse(''); +let el: ltx.Element = null as any; +let maybeEl: ltx.Element | undefined = null as any; +let els: ltx.Element[] = []; +let bool: boolean; +const any: any = null; +let str: string = null as any; -const getChildTextElement = ltx.parse('body text') as ltx.Element; -if (getChildTextElement.getChildText('child') !== 'body text') { - throw new Error("body does not match"); +el = ltx.clone(el); + +bool = ltx.nameEqual(el, el); +bool = ltx.attrsEqual(el, el); +bool = ltx.childrenEqual(el, el); +bool = ltx.equal(el, el); + +el = ltx.createElement('el'); +el = ltx.createElement('el', 'xml'); +el = ltx.createElement('el', { foo: 'bar' }); +el = ltx.createElement('el', { foo: 'bar' }, el); +el = ltx.createElement('el', { foo: 'bar' }, 'hi'); + +if (ltx.isNode(any)) { + // $ExpectType Node + any; +} +if (ltx.isElement(any)) { + // $ExpectType Element + any; +} +if (ltx.isText(any)) { + // $ExpectType string + any; } -const p = new ltx.Parser(); +str = ltx.escapeXML(str); +str = ltx.unescapeXML(str); +str = ltx.escapeXMLText(str); +str = ltx.unescapeXMLText(str); + +el = ltx.parse(''); +el = ltx.parse('', (null as any) as ltx.Parser); +el = ltx.parse('', { Parser: (null as any) as typeof ltx.Parser }); +el = ltx.parse('', { Element: (null as any) as typeof ltx.Element }); + +el = ltx.tag(['document'], 'foo'); +str = ltx.tagString(['document'], 'foo'); + +str = ltx.stringify(el); +str = ltx.stringify(el, 1); +str = ltx.stringify(el, 1, 1); + +const getChildTextElement = ltx.parse('body text'); +if (getChildTextElement.getChildText('child') !== 'body text') { + throw new Error('body does not match'); +} + +let p: ltx.Parser; +p = new ltx.Parser(); +p = new ltx.Parser({ Parser: (null as any) as typeof ltx.Parser }); +p = new ltx.Parser({ Element: (null as any) as typeof ltx.Element }); p.on('tree', (ignored: any) => {}); - p.on('error', (ignored: any) => {}); -const el = new ltx.Element('root').c('children'); -el.c('child', {age: 5}).t('Hello').up() - .c('child', {age: 7}).t('Hello').up() - .c('child', {age: 99}).t('Hello').up(); +el = new ltx.Element('root').c('children'); -el.root().toString(); +bool = el.is('el'); +bool = el.is('el', 'ns'); +str = el.getName(); +let s: string | undefined = el.getNS(); +s = el.findNS('ns'); +const xmlns: { [key: string]: string } = el.getXmlns(); +el.setAttrs('ho'); +el.setAttrs({ my: 'attr' }); +el.getAttr('ho'); +el.getAttr('ho', 'ns'); +maybeEl = el.getChild('el'); +maybeEl = el.getChild('el', 'ns'); +els = el.getChildren('el'); +els = el.getChildren('el', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByAttr('my', 'attr'); +els = el.getChildrenByAttr('my', 'attr', 'ns'); +els = el.getChildrenByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}, true); +str = el.getText(); +let maybeS: string | null = el.getChildText('hi'); +maybeS = el.getChildText('hi', 'ns'); +els = el.getChildElements(); + +class MyEl extends ltx.Element { + foo: 'bar'; +} +let myEl = new MyEl('el'); + +// $ExpectType Element | MyEl +myEl.root(); +// $ExpectType Element | MyEl +myEl.tree(); +// $ExpectType Element | MyEl +myEl.up(); + +el = el.c('hi'); +el = el.c('hi', { my: 'attr' }); +myEl = myEl.cnode(myEl); +myEl = myEl.t('hi'); +myEl = myEl.t(1); +myEl = myEl.remove(el); +myEl = myEl.remove('el'); +myEl = myEl.remove('el', 'ns'); +myEl = myEl.clone(myEl); +str = el.text(); +str = el.text('val'); +el.attr('my'); +el.attr('my', 'attr'); +str = el.toString(); +const json: ltx.ElementJson = el.toJSON(); +el.write(part => { + // $ExpectType string + part; +}); +bool = el.nameEquals(el); +bool = el.attrsEquals(el); +bool = el.childrenEquals(el); +bool = el.equals(el); + +el.c('child', { age: 5 }) + .t('Hello') + .up() + .c('child', { age: 7 }) + .t('Hello') + .up() + .c('child', { age: 99 }) + .t('Hello') + .up(); diff --git a/types/ltx/tslint.json b/types/ltx/tslint.json index 5bb1e8735d..f93cf8562a 100644 --- a/types/ltx/tslint.json +++ b/types/ltx/tslint.json @@ -1,9 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // All are TODOs - "jsdoc-format": false, - "no-consecutive-blank-lines": false, - "strict-export-declare-modifiers": false - } + "extends": "dtslint/dt.json" } diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 91fb68cd96..f3389876b9 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1071,7 +1071,7 @@ declare namespace mapboxgl { export interface MapSourceDataEvent extends MapboxEvent { dataType: 'source'; isSourceLoaded: boolean; - source: Style; + source: Source; sourceId: string; sourceDataType: 'metadata' | 'content'; tile: any; diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index 422b255900..d119c76bd5 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -465,10 +465,10 @@ expectType(mapboxgl.Point.convert(pointlike)); expectType((url: string) => ({ url })); expectType((url: string, resourceType: mapboxgl.ResourceType) => ({ - url, - credentials: 'same-origin', - headers: { 'Accept-Encoding': 'compress' }, - method: 'POST', + url, + credentials: 'same-origin', + headers: { 'Accept-Encoding': 'compress' }, + method: 'POST', collectResourceTiming: true, })); diff --git a/types/mcrypt/index.d.ts b/types/mcrypt/index.d.ts new file mode 100644 index 0000000000..945cb88e59 --- /dev/null +++ b/types/mcrypt/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for mcrypt 0.1 +// Project: https://github.com/tugrul/node-mcrypt +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export function getAlgorithmNames(): string[]; +export function getModeNames(): string[]; + +export class MCrypt { + constructor(algorithm: string, mode: string); + open(key: string | Buffer, iv?: string | Buffer): void; + encrypt(plaintext: string | Buffer): Buffer; + decrypt(ciphertext: Buffer): Buffer; + generateIv(): Buffer; + validateKeySize(validate: boolean): void; + validateIvSize(validate: boolean): void; + selfTest(): boolean; + isBlockAlgorithmMode(): boolean; + isBlockAlgorithm(): boolean; + isBlockMode(): boolean; + getBlockSize(): number; + getKeySize(): number; + getSupportedKeySizes(): number[]; + getIvSize(): number; + hasIv(): boolean; + getAlgorithmName(): string; + getModeName(): string; +} diff --git a/types/mcrypt/mcrypt-tests.ts b/types/mcrypt/mcrypt-tests.ts new file mode 100644 index 0000000000..66614e08e3 --- /dev/null +++ b/types/mcrypt/mcrypt-tests.ts @@ -0,0 +1,51 @@ +import { getAlgorithmNames, getModeNames, MCrypt } from "mcrypt"; + +let plaintext: Buffer; +let ciphertext: Buffer; + +for (const algo of getAlgorithmNames()) { + console.log(algo.toUpperCase()); +} +for (const mode of getModeNames()) { + console.log(mode.toUpperCase()); +} + +const desEcb = new MCrypt("des", "ecb"); +desEcb.open("madepass"); + +ciphertext = desEcb.encrypt("too many secrets"); +console.log(ciphertext.toString("base64")); + +plaintext = desEcb.decrypt(ciphertext); +console.log(plaintext.toString()); + +const blowfishCfb = new MCrypt("blowfish", "cfb"); +const iv = blowfishCfb.generateIv(); +blowfishCfb.open("somekey", iv); +ciphertext = blowfishCfb.encrypt("sometext"); +console.log(Buffer.concat([iv, ciphertext]).toString("base64")); + +const bfEcb = new MCrypt("blowfish", "ecb"); +bfEcb.validateKeySize(false); +bfEcb.open("typeconfig.sys^_-"); + +const rjCbc = new MCrypt("rijndael-256", "cbc"); +rjCbc.validateIvSize(false); +rjCbc.open("$verysec$retkey$", "foobar"); + +console.log(blowfishCfb.getBlockSize() * 8); +console.log(blowfishCfb.getKeySize() * 8); +console.log(blowfishCfb.getSupportedKeySizes().map(v => v * 8)); +console.log(blowfishCfb.getIvSize() * 8); +console.log(blowfishCfb.getAlgorithmName().toUpperCase()); +console.log(blowfishCfb.getModeName().toUpperCase()); + +function assertBool(value: boolean) { + return value; +} + +assertBool(blowfishCfb.selfTest()); +assertBool(blowfishCfb.isBlockAlgorithmMode()); +assertBool(blowfishCfb.isBlockAlgorithm()); +assertBool(blowfishCfb.isBlockMode()); +assertBool(blowfishCfb.hasIv()); diff --git a/types/mcrypt/tsconfig.json b/types/mcrypt/tsconfig.json new file mode 100644 index 0000000000..1bb1454ce5 --- /dev/null +++ b/types/mcrypt/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mcrypt-tests.ts"] +} diff --git a/types/mcrypt/tslint.json b/types/mcrypt/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mcrypt/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mdast/index.d.ts b/types/mdast/index.d.ts index d7761bd38f..c1fcadec97 100644 --- a/types/mdast/index.d.ts +++ b/types/mdast/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/syntax-tree/mdast // Definitions by: Jun Lu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 import { Parent as UnistParent, Literal as UnistLiteral, Node } from 'unist'; diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index b31a8dd7b9..feb12923aa 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -19,6 +19,7 @@ // Mikael Lirbank // Hector Ribes // Florian Richter +// Erik Christensen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -44,10 +45,7 @@ export class MongoClient extends EventEmitter { static connect(uri: string, callback: MongoCallback): void; static connect(uri: string, options?: MongoClientOptions): Promise; static connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; - /** - * @deprecated - * http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect - */ + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect */ connect(): Promise; connect(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#close */ @@ -589,7 +587,7 @@ export class Db extends EventEmitter { indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */ - listCollections(filter?: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + listCollections(filter?: Object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */ /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; @@ -679,7 +677,7 @@ export interface CollectionCreateOptions extends CommonOptions { indexOptionDefaults?: object; viewOn?: string; pipeline?: any[]; - collation?: object; + collation?: CollationDocument; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */ @@ -737,7 +735,7 @@ export interface IndexOptions extends CommonOptions { * Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ partialFilterExpression?: any; - collation?: Object; + collation?: CollationDocument; default_language?: string } @@ -839,9 +837,9 @@ export interface Collection { createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise; createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */ - createIndexes(indexSpecs: Object[], callback: MongoCallback): void; - createIndexes(indexSpecs: Object[], options?: { session?: ClientSession }): Promise; - createIndexes(indexSpecs: Object[], options: { session?: ClientSession }, callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], options?: { session?: ClientSession }): Promise; + createIndexes(indexSpecs: IndexSpecification[], options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */ deleteMany(filter: FilterQuery, callback: MongoCallback): void; deleteMany(filter: FilterQuery, options?: CommonOptions): Promise; @@ -888,9 +886,9 @@ export interface Collection { findOneAndReplace(filter: FilterQuery, replacement: Object, options?: FindOneAndReplaceOption): Promise>; findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ - findOneAndUpdate(filter: FilterQuery, update: Object, callback: MongoCallback>): void; - findOneAndUpdate(filter: FilterQuery, update: Object, options?: FindOneAndUpdateOption): Promise>; - findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndUpdateOption, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options?: FindOneAndUpdateOption): Promise>; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options: FindOneAndUpdateOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; @@ -1294,11 +1292,12 @@ export interface CollectionAggregationOptions { * Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ bypassDocumentValidation?: boolean; + hint?: string | object; raw?: boolean; promoteLongs?: boolean; promoteValues?: boolean; promoteBuffers?: boolean; - collation?: Object; + collation?: CollationDocument; comment?: string session?: ClientSession; @@ -1560,7 +1559,7 @@ export interface FindOneOptions { readPreference?: ReadPreference | string; partial?: boolean; maxTimeMs?: number; - collation?: Object; + collation?: CollationDocument; session?: ClientSession; } @@ -1681,7 +1680,7 @@ export class Cursor extends Readable { close(): Promise; close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#collation */ - collation(value: Object): Cursor; + collation(value: CollationDocument): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#comment */ comment(value: string): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#count */ @@ -1827,24 +1826,30 @@ export class AggregationCursor extends Readable { unwind(field: string): AggregationCursor; } +/** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#~resultCallback */ +export type CommandCursorResult = any | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html */ export class CommandCursor extends Readable { + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(): Promise; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#batchSize */ batchSize(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#clone */ clone(): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#close */ - close(): Promise; - close(callback: MongoCallback): void; + close(): Promise; + close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#each */ - each(callback: MongoCallback): void; + each(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#isClosed */ isClosed(): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#maxTimeMS */ maxTimeMS(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#next */ - next(): Promise; - next(callback: MongoCallback): void; + next(): Promise; + next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#rewind */ @@ -1986,7 +1991,7 @@ export interface ChangeStreamOptions { maxAwaitTimeMS?: number; resumeAfter?: Object; batchSize?: number; - collation?: Object; + collation?: CollationDocument; readPreference?: ReadPreference; } @@ -2067,3 +2072,39 @@ export class Logger { */ static setLevel(level: string): void } + +/** https://docs.mongodb.com/manual/reference/collation/#collation-document-fields */ +export interface CollationDocument { + locale: string; + strength?: number; + caseLevel?: boolean; + caseFirst?: string; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; + +} + +/** https://docs.mongodb.com/manual/reference/command/createIndexes/ */ +export interface IndexSpecification { + key: object; + name?: string; + background?: boolean; + unique?: boolean; + partialFilterExpression?: object; + sparse?: boolean; + expireAfterSeconds?: number; + storageEngine?: object; + weights?: object; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + min?: number; + max?: number; + bucketSize?: number; + collation?: CollationDocument; +} diff --git a/types/mustache-express/index.d.ts b/types/mustache-express/index.d.ts new file mode 100644 index 0000000000..ff40de42d7 --- /dev/null +++ b/types/mustache-express/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for mustache-express 1.2 +// Project: https://github.com/bryanburgers/node-mustache-express#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Cache } from 'lru-cache'; + +export = mustacheExpress; + +declare function mustacheExpress( + partialsPath?: string, + partialsExt?: string +): mustacheExpress.ExpessEngine; + +declare namespace mustacheExpress { + interface ExpessEngine { + (path: string, options: any, cb: (...args: any[]) => any): any; + cache: TemplateCache; + } + + type TemplateCache = Cache; +} diff --git a/types/mustache-express/mustache-express-tests.ts b/types/mustache-express/mustache-express-tests.ts new file mode 100644 index 0000000000..9157798c7b --- /dev/null +++ b/types/mustache-express/mustache-express-tests.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import mustacheExpress = require('mustache-express'); + +const app = express(); +app.engine('mustache', mustacheExpress()); +app.engine('mustache', mustacheExpress('/partials')); +app.engine('mustache', mustacheExpress('/partials', '.mst')); + +// $ExpectType Cache +mustacheExpress().cache; diff --git a/types/mustache-express/tsconfig.json b/types/mustache-express/tsconfig.json new file mode 100644 index 0000000000..9afb989b62 --- /dev/null +++ b/types/mustache-express/tsconfig.json @@ -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", + "mustache-express-tests.ts" + ] +} diff --git a/types/mustache-express/tslint.json b/types/mustache-express/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mustache-express/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index f71cd9f6ec..b9edae0587 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1126,10 +1126,10 @@ declare module "http" { 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -1139,14 +1139,24 @@ declare module "http" { 'content-location'?: string; 'content-range'?: string; 'content-type'?: string; + 'cookie'?: string; 'date'?: string; + 'expect'?: string; 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; 'last-modified'?: string; 'location'?: string; 'pragma'?: string; 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; 'public-key-pins'?: string; + 'range'?: string; 'referer'?: string; 'retry-after'?: string; 'set-cookie'?: string[]; diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index 55ee5b6741..78b1801b0b 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -420,7 +420,7 @@ declare namespace fin { /** * The timeout for displaying a notification.Can be in milliseconds or "never". */ - duration?: number | "never"; + timeout?: number | "never"; /** * The url of the notification */ @@ -804,9 +804,9 @@ declare namespace fin { */ getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void; /** - * Gets the current state ("minimized", "maximized", or "restored") of the window. + * Gets the current state ("minimized", "maximized", or "normal") of the window. */ - getState(callback?: (state: "minimized" | "maximized" | "restored") => void, errorCallback?: (reason: string) => void): void; + getState(callback?: (state: "minimized" | "maximized" | "normal") => void, errorCallback?: (reason: string) => void): void; /** * Returns the zoom level of the window. */ diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index 167a6c86be..e4430ff9c2 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -207,7 +207,7 @@ function test_notification() { notification.close(); // sendMessage notification = new fin.desktop.Notification({ - duration: 10, + timeout: 10, url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, diff --git a/types/p-defer/index.d.ts b/types/p-defer/index.d.ts index 7eff607e7d..8386706d89 100644 --- a/types/p-defer/index.d.ts +++ b/types/p-defer/index.d.ts @@ -1,16 +1,17 @@ // Type definitions for p-defer 1.0 // Project: https://github.com/sindresorhus/p-defer // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace pDefer { - interface DeferredPromise { - resolve(value?: U | PromiseLike): Promise; - reject(reason: any): Promise; - promise: Promise; - } -} +export = pDefer; declare function pDefer(): pDefer.DeferredPromise; -export = pDefer; +declare namespace pDefer { + interface DeferredPromise { + resolve(value?: T | PromiseLike): void; + reject(reason: any): void; + promise: Promise; + } +} diff --git a/types/p-defer/p-defer-tests.ts b/types/p-defer/p-defer-tests.ts index 9ea4647620..f61bce624b 100644 --- a/types/p-defer/p-defer-tests.ts +++ b/types/p-defer/p-defer-tests.ts @@ -1,13 +1,13 @@ import pDefer = require('p-defer'); -function delay(deferred: pDefer.DeferredPromise, ms: number) { +function delay(deferred: pDefer.DeferredPromise, ms: number) { setTimeout(deferred.resolve, ms, '🦄'); return deferred.promise; } -let s: string; -async function f() { s = await delay(pDefer(), 100); } +const s: Promise = delay(pDefer(), 100); -async function u() { - const u: Promise = pDefer().resolve(); -} +// $ExpectType void +pDefer().resolve(); +// $ExpectType void +pDefer().reject('oh no'); diff --git a/types/passport-bnet/index.d.ts b/types/passport-bnet/index.d.ts new file mode 100644 index 0000000000..86255c782d --- /dev/null +++ b/types/passport-bnet/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for passport-bnet 2.0 +// Project: https://github.com/Blizzard/passport-bnet#readme +// Definitions by: Ivan Fernandes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Strategy as OAuth2Strategy, VerifyFunction, VerifyFunctionWithRequest } from 'passport-oauth2'; + +declare class BnetStrategy extends OAuth2Strategy { + constructor(options: BnetStrategy.StrategyOptions, verify: VerifyFunction); + constructor(options: BnetStrategy.StrategyOptionsWithRequest, verify: VerifyFunctionWithRequest); +} + +declare namespace BnetStrategy { + interface _BaseBnetOptions { + region?: string; + + scopeSeparator?: string; + customHeaders?: object; + authorizationURL?: string; + tokenURL?: string; + scope?: string; + clientID: string; + clientSecret: string; + callbackURL?: string; + } + + interface StrategyOptions extends _BaseBnetOptions { + passReqToCallback?: false; + } + + interface StrategyOptionsWithRequest extends _BaseBnetOptions { + passReqToCallback: true; + } + + function getHost(region: string): string; + + type Strategy = BnetStrategy; + const Strategy: typeof BnetStrategy; +} + +export = BnetStrategy; diff --git a/types/passport-bnet/passport-bnet-tests.ts b/types/passport-bnet/passport-bnet-tests.ts new file mode 100644 index 0000000000..06c0ffccec --- /dev/null +++ b/types/passport-bnet/passport-bnet-tests.ts @@ -0,0 +1,64 @@ +// Based on passport-oauth2/passport-oauth2-tests.ts + +import BnetStrategy = require("passport-bnet"); +import { Strategy, StrategyOptions, StrategyOptionsWithRequest } from "passport-bnet"; +import { Strategy as OAuth2Strategy, VerifyCallback } from "passport-oauth2"; +import { Request } from "express"; + +const strategyOptions1: StrategyOptions = { + authorizationURL: 'http://www.example.com/auth', + callbackURL: 'http://www.example.com/callback', + clientID: 'dummy', + clientSecret: 'secret', + tokenURL: 'http://www.example.com/token', + region: 'us', + scope: "email", + scopeSeparator: ' ', + customHeaders: {} +}; + +function verifyFunction1(_accessToken: string, _refreshToken: string, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(new Error('unimplemented')); +} + +function verifyFunction2(_accessToken: string, _refreshToken: string, _results: any, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(new Error('unimplemented')); +} + +const strategy1: BnetStrategy = new BnetStrategy(strategyOptions1, verifyFunction1); + +const strategy2: Strategy = new BnetStrategy(strategyOptions1, verifyFunction2); + +function verifyFunction3(_req: Request, _accessToken: string, _refreshToken: string, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(undefined, { userid: '1' }); +} + +function verifyFunction4(_req: Request, _accessToken: string, _refreshToken: string, _results: any, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(undefined, { userid: '1' }); +} + +const strategyOptions2: StrategyOptionsWithRequest = { + authorizationURL: 'http://www.example.com/auth', + callbackURL: 'http://www.example.com/callback', + clientID: 'dummy', + clientSecret: 'secret', + tokenURL: 'http://www.example.com/token', + region: 'us', + scope: "email", + scopeSeparator: ' ', + customHeaders: {}, + passReqToCallback: true +}; + +const strategy3: OAuth2Strategy = new BnetStrategy +(strategyOptions2, verifyFunction3); + +const strategy4: Strategy = new Strategy(strategyOptions2, verifyFunction4); + +class MyStrategy extends BnetStrategy { + useProtectedProperty() { + this._oauth2.get('http://www.example.com/profile', 'token', err => err.statusCode); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result) => result); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result, response) => response); + } +} diff --git a/types/passport-bnet/tsconfig.json b/types/passport-bnet/tsconfig.json new file mode 100644 index 0000000000..28da7a7a65 --- /dev/null +++ b/types/passport-bnet/tsconfig.json @@ -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", + "passport-bnet-tests.ts" + ] +} \ No newline at end of file diff --git a/types/passport-bnet/tslint.json b/types/passport-bnet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/passport-bnet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/passport-saml/index.d.ts b/types/passport-saml/index.d.ts index cc2faafe5c..9338b88deb 100644 --- a/types/passport-saml/index.d.ts +++ b/types/passport-saml/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bergie/passport-saml // Definitions by: Chris Barth // Damian Assennato +// Karol Samborski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/passport-saml/multiSamlStrategy.d.ts b/types/passport-saml/multiSamlStrategy.d.ts new file mode 100644 index 0000000000..405c7264dc --- /dev/null +++ b/types/passport-saml/multiSamlStrategy.d.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import { Strategy, SamlConfig, VerifyWithRequest, VerifyWithoutRequest } from './index'; + +export interface MultiSamlConfig extends SamlConfig { + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlConfig) => void): void; +} + +export class MultiSamlStrategy extends Strategy { + constructor(config: MultiSamlConfig, verify: VerifyWithRequest | VerifyWithoutRequest); +} diff --git a/types/passport-saml/passport-saml-tests.ts b/types/passport-saml/passport-saml-tests.ts index 615c1b7320..b22421fe81 100644 --- a/types/passport-saml/passport-saml-tests.ts +++ b/types/passport-saml/passport-saml-tests.ts @@ -1,6 +1,7 @@ import express = require('express'); import passport = require('passport'); import SamlStrategy = require('passport-saml'); +import MultiSamlStrategy = require('passport-saml/multiSamlStrategy'); import fs = require('fs'); const samlStrategy = new SamlStrategy.Strategy( @@ -33,3 +34,27 @@ passport.use(samlStrategy); passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); const metadata = samlStrategy.generateServiceProviderMetadata("decryptionCert"); + +const multiSamlStrategy = new MultiSamlStrategy.MultiSamlStrategy( + { + name: 'samlCustomName', + path: '/login/callback', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlStrategy.SamlConfig) => void) { + callback(null, { + name: 'samlCustomName', + path: '/login/callback2', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + }); + } + }, + (profile: {}, done: (err: Error | null, user: {}, info?: {}) => void) => { + const user = {}; + done(null, user); + } +); + +passport.use(multiSamlStrategy); +passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); diff --git a/types/passport-saml/tsconfig.json b/types/passport-saml/tsconfig.json index 0809dbbaf7..39283fa663 100644 --- a/types/passport-saml/tsconfig.json +++ b/types/passport-saml/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "multiSamlStrategy.d.ts", "passport-saml-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/physijs/test/collisions.ts b/types/physijs/test/collisions.ts index 20493189e0..41f09e351d 100644 --- a/types/physijs/test/collisions.ts +++ b/types/physijs/test/collisions.ts @@ -90,7 +90,7 @@ spawnBox = (function() { var box_geometry = new THREE.BoxGeometry( 4, 4, 4 ), handleCollision = function( collided_with ) { - var target = this; + var target = this as any; target.collisions = 0; switch (++target.collisions) { @@ -168,4 +168,4 @@ render = function() { render_stats.update(); }; -window.onload = initScene; \ No newline at end of file +window.onload = initScene; diff --git a/types/physijs/test/vehicle.ts b/types/physijs/test/vehicle.ts index b8643de3b0..37f32279a8 100644 --- a/types/physijs/test/vehicle.ts +++ b/types/physijs/test/vehicle.ts @@ -186,11 +186,11 @@ initScene = function() { ); } - input = { + input = { power: null, direction: null, steering: 0 - }; + } as any; document.addEventListener('keydown', function( ev ) { switch ( ev.keyCode ) { case 37: // left diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 79d0ebe0f9..8eaa6491bb 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for pigpio 0.4 +// Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan +// Definitions by: ManerFan , erikma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -424,3 +424,27 @@ export function configureClock(microseconds: number, peripheral: number): void; * @param port an unsigned integer specifying the pigpio socket port number */ export function configureSocketPort(port: number): void; + +/** + * Returns the Raspberry Pi hardware revision as an unsigned integer. Returns 0 + * if the hardware revision can not be determined. + */ +export function hardwareRevision(): number; + +/** + * Gets the current unsigned 32-bit integer value of the number of microseconds + * since system boot. This value wraps around the 32-bit space in just over an hour. + * Use tickDiff() to get the difference between two tick values, to + * ensure the correct JavaScript operations are used to account for the possibility + * of overflow. + */ +export function getTick(): number; + +/** + * Returns the difference in microseconds between the end and start tick counts. + * The tick counts can be retrieved using getTick(), or may be passed + * in a GPIO event callback. + * @param startTick The start of the measured interval. An unsigned integer tick value. + * @param endTick The end of the measured interval. An unsigned integer tick value. + */ +export function tickDiff(startTick: number, endTick: number): number; diff --git a/types/pigpio/pigpio-tests.ts b/types/pigpio/pigpio-tests.ts index 90e7d4485d..f756058b03 100644 --- a/types/pigpio/pigpio-tests.ts +++ b/types/pigpio/pigpio-tests.ts @@ -880,6 +880,15 @@ import * as assert from 'assert'; }, 2000); })(); +(function tickAndTickDiff(): void { + const startTick: number = pigpio.getTick(); + setTimeout(() => { + const endTick: number = pigpio.getTick(); + const diff: number = pigpio.tickDiff(startTick, endTick); + assert.ok(diff > 0, 'expected tick count to increase across a timer call'); + }, 50); +})(); + (function gpio_glitch_filter(): void { const Gpio = pigpio.Gpio; const input = new Gpio(7, { diff --git a/types/postcss-url/index.d.ts b/types/postcss-url/index.d.ts new file mode 100644 index 0000000000..361b69f1c7 --- /dev/null +++ b/types/postcss-url/index.d.ts @@ -0,0 +1,148 @@ +// Type definitions for postcss-url 8.0 +// Project: https://github.com/postcss/postcss-url +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { Plugin } from 'postcss'; + +declare namespace url { + type CustomTransformFunction = ( + asset: { + /** + * Original URL. + */ + url: string; + + /** + * URL pathname. + */ + pathname?: string; + + /** + * Absolute path to asset. + */ + absolutePath?: string; + + /** + * Current relative path to asset. + */ + relativePath?: string; + + /** + * Querystring from URL. + */ + search?: string; + + /** + * Hash from URL. + */ + hash?: string; + }, + dir: { + /** + * PostCSS from option. + */ + from?: string; + + /** + * PostCSS to option. + */ + to?: string; + + /** + * File path. + */ + file?: string; + }, + ) => string; + type CustomHashFunction = (file: Buffer) => string; + type CustomFilterFunction = (file: string) => boolean; + + interface Options { + /** + * URL rewriting mechanism. + * + * @default 'rebase' + */ + url?: 'copy' | 'inline' | 'rebase' | CustomTransformFunction; + + /** + * Specify the maximum file size to inline (in kilobytes). + */ + maxSize?: number; + + /** + * Do not warn when an SVG URL with a fragment is inlined. + * PostCSS-URL does not support partial inlining. + * The entire SVG file will be inlined. + * By default a warning will be issued when this occurs. + * + * @default false + */ + ignoreFragmentWarning?: boolean; + + /** + * Determine wether a file should be inlined. + */ + filter?: RegExp | CustomFilterFunction | string; + + /** + * Specifies whether the URL's fragment identifer value, if present, will be added to the inlined data URI. + * + * @default false + */ + includeUriFragment?: boolean; + + /** + * The fallback method to use if the maximum size is exceeded or the URL contains a hash. + */ + fallback?: CustomTransformFunction; + + /** + * Specify the base path or list of base paths where to search images from. + */ + basePath?: string | string[]; + + /** + * The assets files will be copied in that destination. + * + * @default false + */ + assetsPath?: boolean | string; + + /** + * Rename the path of the files by a hash name. + * + * @default false + */ + useHash?: boolean; + + /** + * Hash options + */ + hashOptions?: { + /** + * Hashing method or custom function. + */ + method?: 'xxhash32' | 'xxhash64' | CustomHashFunction; + + /** + * Shrink hast to certain length. + */ + shrink?: number; + + /** + * Append the original filename in resulting filename. + */ + append?: boolean; + }; + } + + type Url = Plugin; +} + +declare const url: url.Url; +export = url; diff --git a/types/postcss-url/package.json b/types/postcss-url/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-url/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-url/postcss-url-tests.ts b/types/postcss-url/postcss-url-tests.ts new file mode 100644 index 0000000000..a258b49be4 --- /dev/null +++ b/types/postcss-url/postcss-url-tests.ts @@ -0,0 +1,17 @@ +import * as postcss from 'postcss'; +import * as url from 'postcss-url'; + +const standard: postcss.Transformer = url(); + +const single: postcss.Transformer = url({ url: 'copy', assetsPath: 'img', useHash: true }); + +const multiple: postcss.Transformer = url([ + { filter: '**/assets/copy/*.png', url: 'copy', assetsPath: 'img', useHash: true }, + { filter: '**/assets/inline/*.svg', url: 'inline' }, + { filter: '**/assets/**/*.gif', url: 'rebase' }, + { filter: 'cdn/**/*', url: (asset) => `https://cdn.url/${asset.url}` }, +]); + +postcss().use(standard); +postcss().use(single); +postcss().use(multiple); diff --git a/types/postcss-url/tsconfig.json b/types/postcss-url/tsconfig.json new file mode 100644 index 0000000000..c7759ba2d3 --- /dev/null +++ b/types/postcss-url/tsconfig.json @@ -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", + "postcss-url-tests.ts" + ] +} diff --git a/types/postcss-url/tslint.json b/types/postcss-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/promised-ldap/index.d.ts b/types/promised-ldap/index.d.ts new file mode 100644 index 0000000000..8b0182bea6 --- /dev/null +++ b/types/promised-ldap/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for promised-ldap 0.3 +// Project: https://github.com/stewartml/promised-ldap +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { EventEmitter } from "events"; +import * as ldap from "ldapjs"; + +declare class Client extends EventEmitter { + constructor({ url }: { url: string }); + + search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[] + ): Promise<{ + entries: any[]; + references: any[]; + }>; + + authenticate(base: string, dn: string, password: string): Promise; + authenticateUser( + base: string, + dn: string, + password: string + ): Promise<{ name: string; email: string; groups: string[] } | null>; + + bind( + dn: string, + password: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + add( + name: string, + entry: object, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + compare( + name: string, + attr: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + del(name: string, controls?: ldap.Control | ldap.Control[]): Promise; + + exop( + name: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modify( + name: string, + change: ldap.Change | ldap.Change[], + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modifyDN( + name: string, + newName: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + _search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + _search( + base: string, + options: ldap.SearchOptions, + _bypass: boolean + ): Promise; + + starttls( + options: object, + controls: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + + unbind(): Promise; + + destroy(err?: any): void; +} + +declare namespace Client { + type SearchOptions = ldap.SearchOptions; +} + +export = Client; diff --git a/types/promised-ldap/promised-ldap-tests.ts b/types/promised-ldap/promised-ldap-tests.ts new file mode 100644 index 0000000000..b61f7ef6fc --- /dev/null +++ b/types/promised-ldap/promised-ldap-tests.ts @@ -0,0 +1,39 @@ +import ldap = require("promised-ldap"); +import ldapjs = require("ldapjs"); + +const client = new ldap({ + url: "ldap://127.0.0.1:1389" +}); + +client.authenticate("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.authenticateUser("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.bind("cn=root", "secret").catch((err: Error) => { + console.error(err); +}); + +const opts: ldap.SearchOptions = { + filter: "(&(l=Seattle)(email=*@foo.com))", + scope: "sub", + attributes: ["dn", "sn", "cn"] +}; + +client._search("o=example", opts).then((res: NodeJS.EventEmitter) => { + console.log(res); +}); + +const change = new ldapjs.Change({ + operation: "add", + modification: { + pets: ["cat", "dog"] + } +}); + +client.modify("cn=foo, o=example", change).catch((err: Error) => { + console.error(err); +}); diff --git a/types/promised-ldap/tsconfig.json b/types/promised-ldap/tsconfig.json new file mode 100644 index 0000000000..89b60715eb --- /dev/null +++ b/types/promised-ldap/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "promised-ldap-tests.ts"] +} diff --git a/types/promised-ldap/tslint.json b/types/promised-ldap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promised-ldap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 8337acfbe4..257ca3cd44 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -1,8 +1,9 @@ // Type definitions for pubnub 4.0 // Project: https://github.com/pubnub/javascript -// Definitions by: bitbankinc , rollymaduk , vitosamson +// Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration +// TypeScript Version: 2.2 declare class Pubnub { constructor(config: Pubnub.PubnubConfig); @@ -88,6 +89,18 @@ declare class Pubnub { setState( params: Pubnub.SetStateParameters ): Promise; + + encrypt( + data: string, + customCipherKey?: string, + options?: Pubnub.CryptoParameters, + ): any; + + decrypt( + data: object, + customCipherKey?: string, + options?: Pubnub.CryptoParameters + ): any; } declare namespace Pubnub { @@ -296,6 +309,14 @@ declare namespace Pubnub { }; } + // encrypt & decrypt + interface CryptoParameters { + encryptKey?: boolean; + keyEncoding?: string; + keyLength?: number; + mode?: string; + } + interface Categories { PNNetworkUpCategory: string; PNNetworkDownCategory: string; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 1d8b2bb1ca..50660bd942 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -86,3 +86,15 @@ pubnub.setState({ channels: [] }, (status, res) => { pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); + +const cryptoOptions = { + encryptKey: true, + keyEncoding: 'utf8', + keyLength: 256, + mode: 'cbc' +}; +const mySecret = { + message: 'Hi!', +}; +pubnub.decrypt(mySecret, undefined, cryptoOptions); +pubnub.encrypt('egrah5rwgrehwqh5eh3hwfwef', undefined, cryptoOptions); diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index cbb31f2fd0..d90f02f8b8 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -968,7 +968,7 @@ export interface Request { /** * @returns The `Frame` object that initiated the request, or `null` if navigating to error pages */ - frame(): Promise; + frame(): Frame | null; /** * An object with HTTP headers associated with the request. diff --git a/types/random-boolean/index.d.ts b/types/random-boolean/index.d.ts new file mode 100644 index 0000000000..3390da9317 --- /dev/null +++ b/types/random-boolean/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-boolean 1.0 +// Project: https://github.com/arthurvr/random-boolean#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomBoolean; + +declare function randomBoolean(): boolean; diff --git a/types/random-boolean/random-boolean-tests.ts b/types/random-boolean/random-boolean-tests.ts new file mode 100644 index 0000000000..8ac983e111 --- /dev/null +++ b/types/random-boolean/random-boolean-tests.ts @@ -0,0 +1,4 @@ +import randomBoolean = require('random-boolean'); + +// $ExpectType boolean +randomBoolean(); diff --git a/types/random-boolean/tsconfig.json b/types/random-boolean/tsconfig.json new file mode 100644 index 0000000000..7392190732 --- /dev/null +++ b/types/random-boolean/tsconfig.json @@ -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", + "random-boolean-tests.ts" + ] +} diff --git a/types/random-boolean/tslint.json b/types/random-boolean/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-boolean/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-float/index.d.ts b/types/random-float/index.d.ts new file mode 100644 index 0000000000..646d263128 --- /dev/null +++ b/types/random-float/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-float 1.0 +// Project: https://github.com/sindresorhus/random-float +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomFloat; + +declare function randomFloat(max: number): number; +declare function randomFloat(min: number, max: number): number; // tslint:disable-line unified-signatures diff --git a/types/random-float/random-float-tests.ts b/types/random-float/random-float-tests.ts new file mode 100644 index 0000000000..663190ce81 --- /dev/null +++ b/types/random-float/random-float-tests.ts @@ -0,0 +1,6 @@ +import randomFloat = require('random-float'); + +// $ExpectType number +randomFloat(5); +// $ExpectType number +randomFloat(10, 100); diff --git a/types/random-float/tsconfig.json b/types/random-float/tsconfig.json new file mode 100644 index 0000000000..faefa13645 --- /dev/null +++ b/types/random-float/tsconfig.json @@ -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", + "random-float-tests.ts" + ] +} diff --git a/types/random-float/tslint.json b/types/random-float/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-float/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-int/index.d.ts b/types/random-int/index.d.ts new file mode 100644 index 0000000000..6f7f421976 --- /dev/null +++ b/types/random-int/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-int 1.0 +// Project: https://github.com/sindresorhus/random-int +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomInt; + +declare function randomInt(max: number): number; +declare function randomInt(min: number, max: number): number; // tslint:disable-line unified-signatures diff --git a/types/random-int/random-int-tests.ts b/types/random-int/random-int-tests.ts new file mode 100644 index 0000000000..68165e9c5d --- /dev/null +++ b/types/random-int/random-int-tests.ts @@ -0,0 +1,6 @@ +import randomInt = require('random-int'); + +// $ExpectType number +randomInt(5); +// $ExpectType number +randomInt(10, 100); diff --git a/types/random-int/tsconfig.json b/types/random-int/tsconfig.json new file mode 100644 index 0000000000..e1a576d337 --- /dev/null +++ b/types/random-int/tsconfig.json @@ -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", + "random-int-tests.ts" + ] +} diff --git a/types/random-int/tslint.json b/types/random-int/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-int/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-item/index.d.ts b/types/random-item/index.d.ts new file mode 100644 index 0000000000..3fbbaca074 --- /dev/null +++ b/types/random-item/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-item 1.0 +// Project: https://github.com/sindresorhus/random-item +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomItem; + +declare function randomItem(input: T[]): T; diff --git a/types/random-item/random-item-tests.ts b/types/random-item/random-item-tests.ts new file mode 100644 index 0000000000..12185a0ad2 --- /dev/null +++ b/types/random-item/random-item-tests.ts @@ -0,0 +1,6 @@ +import randomItem = require('random-item'); + +// $ExpectType string +randomItem(['pony', 'unicorn', 'rainbow']); +// $ExpectType string | number +randomItem(['pony', 'unicorn', 'rainbow', 1]); diff --git a/types/random-item/tsconfig.json b/types/random-item/tsconfig.json new file mode 100644 index 0000000000..279aba16b5 --- /dev/null +++ b/types/random-item/tsconfig.json @@ -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", + "random-item-tests.ts" + ] +} diff --git a/types/random-item/tslint.json b/types/random-item/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-item/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-obj-key/index.d.ts b/types/random-obj-key/index.d.ts new file mode 100644 index 0000000000..dfe12ca6f6 --- /dev/null +++ b/types/random-obj-key/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-obj-key 1.0 +// Project: https://github.com/sindresorhus/random-obj-key +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = randomObjKey; + +declare function randomObjKey(input: TObj): keyof TObj; diff --git a/types/random-obj-key/random-obj-key-tests.ts b/types/random-obj-key/random-obj-key-tests.ts new file mode 100644 index 0000000000..b12cf282ea --- /dev/null +++ b/types/random-obj-key/random-obj-key-tests.ts @@ -0,0 +1,4 @@ +import randomObjKey = require('random-obj-key'); + +// $ExpectType "foo" | "bar" +randomObjKey({ foo: true, bar: true }); diff --git a/types/random-obj-key/tsconfig.json b/types/random-obj-key/tsconfig.json new file mode 100644 index 0000000000..aaaf33ba98 --- /dev/null +++ b/types/random-obj-key/tsconfig.json @@ -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", + "random-obj-key-tests.ts" + ] +} diff --git a/types/random-obj-key/tslint.json b/types/random-obj-key/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-obj-key/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-obj-prop/index.d.ts b/types/random-obj-prop/index.d.ts new file mode 100644 index 0000000000..f9aca5624f --- /dev/null +++ b/types/random-obj-prop/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-obj-prop 1.0 +// Project: https://github.com/sindresorhus/random-obj-prop +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomObjProp; + +declare function randomObjProp(input: { [key: string]: T }): T; diff --git a/types/random-obj-prop/random-obj-prop-tests.ts b/types/random-obj-prop/random-obj-prop-tests.ts new file mode 100644 index 0000000000..7dd2fcd67d --- /dev/null +++ b/types/random-obj-prop/random-obj-prop-tests.ts @@ -0,0 +1,4 @@ +import randomObjProp = require('random-obj-prop'); + +// $ExpectType string | number +randomObjProp({ foo: 'pony', bar: 1 }); diff --git a/types/random-obj-prop/tsconfig.json b/types/random-obj-prop/tsconfig.json new file mode 100644 index 0000000000..f155cfc211 --- /dev/null +++ b/types/random-obj-prop/tsconfig.json @@ -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", + "random-obj-prop-tests.ts" + ] +} diff --git a/types/random-obj-prop/tslint.json b/types/random-obj-prop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-obj-prop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index 4af6cae9b2..e727155520 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker 1.8 +// Type definitions for react-datepicker 2.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -8,11 +8,11 @@ // Koala Human // Sean Kelley // Justin Grant +// Jake Boone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -import * as moment from "moment"; import * as Popper from "popper.js"; export interface ReactDatePickerProps { @@ -21,59 +21,65 @@ export interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; calendarClassName?: string; + calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: string; customInput?: React.ReactNode; customInputRef?: string; dateFormat?: string | string[]; dateFormatCalendar?: string; - dayClassName?(date: moment.Moment): string | null; + dayClassName?(date: Date): string | null; disabled?: boolean; disabledKeyboardNavigation?: boolean; dropdownMode?: 'scroll' | 'select'; - endDate?: moment.Moment; - excludeDates?: moment.Moment[]; - excludeTimes?: moment.Moment[]; - filterDate?(date: moment.Moment): boolean; + endDate?: Date; + excludeDates?: Date[]; + excludeTimes?: Date[]; + filterDate?(date: Date): boolean; fixedHeight?: boolean; forceShowMonthNavigation?: boolean; - formatWeekNumber?(date: moment.Moment): string | number; - highlightDates?: moment.Moment[]; + formatWeekNumber?(date: Date): string | number; + highlightDates?: Date[]; id?: string; - includeDates?: moment.Moment[]; - includeTimes?: moment.Moment[]; + includeDates?: Date[]; + includeTimes?: Date[]; + injectTimes?: Date[]; inline?: boolean; isClearable?: boolean; locale?: string; - maxDate?: moment.Moment; - maxTime?: moment.Moment; - minDate?: moment.Moment; - minTime?: moment.Moment; + maxDate?: Date; + maxTime?: Date; + minDate?: Date; + minTime?: Date; monthsShown?: number; name?: string; onBlur?(event: React.FocusEvent): void; - onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): void; + onChange(date: Date | null, event: React.SyntheticEvent | undefined): void; onChangeRaw?(event: React.FocusEvent): void; onClickOutside?(event: React.MouseEvent): void; onFocus?(event: React.FocusEvent): void; onKeyDown?(event: React.KeyboardEvent): void; - onMonthChange?(date: moment.Moment): void; - onSelect?(date: moment.Moment, event: React.SyntheticEvent | undefined): void; - onWeekSelect?(firstDayOfWeek: moment.Moment, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; - onYearChange?(date: moment.Moment): void; - openToDate?: moment.Moment; + onMonthChange?(date: Date): void; + onSelect?(date: Date, event: React.SyntheticEvent | undefined): void; + onWeekSelect?(firstDayOfWeek: Date, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; + onInputClick?(): void; + onYearChange?(date: Date): void; + onInputError?(err: {code: number; msg: string}): void; + open?: boolean; + openToDate?: Date; peekNextMonth?: boolean; placeholderText?: string; popperClassName?: string; popperContainer?(props: { children: React.ReactNode[] }): React.ReactNode; popperModifiers?: Popper.Modifiers; popperPlacement?: string; + popperProps?: {}; preventOpenOnFocus?: boolean; readOnly?: boolean; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; - selected?: moment.Moment | null; + selected?: Date | null; selectsEnd?: boolean; selectsStart?: boolean; shouldCloseOnSelect?: boolean; @@ -84,21 +90,34 @@ export interface ReactDatePickerProps { showTimeSelectOnly?: boolean; showWeekNumbers?: boolean; showYearDropdown?: boolean; - startDate?: moment.Moment; + startDate?: Date; startOpen?: boolean; tabIndex?: number; timeCaption?: string; timeFormat?: string; timeIntervals?: number; title?: string; - todayButton?: string; + todayButton?: React.ReactNode; useShortMonthInDropdown?: boolean; useWeekdaysShort?: boolean; - utcOffset?: number; value?: string; weekLabel?: string; withPortal?: boolean; yearDropdownItemNumber?: number; + formatWeekDay?(date: Date): string; + clearButtonTitle?: string; + previousMonthButtonLabel?: string; + nextMonthButtonLabel?: string; + renderCustomHeader?(params: { + date: Date; + changeYear(year: number): void; + changeMonth(month: number): void; + decreaseMonth(): void; + increaseMonth(): void; + prevMonthButtonDisabled: boolean; + nextMonthButtonDisabled: boolean; + }): React.ReactNode; + renderDayContents?(dayOfMonth: number): React.ReactNode; } declare const ReactDatePicker: React.ClassicComponentClass; export default ReactDatePicker; diff --git a/types/react-datepicker/package.json b/types/react-datepicker/package.json index fc763e4d4b..245f69cd2c 100644 --- a/types/react-datepicker/package.json +++ b/types/react-datepicker/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "moment": ">=2.14.0", "popper.js": "^1.14.1" } } diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 1414672684..4a3fd93cac 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,17 +1,16 @@ import * as React from 'react'; -import * as moment from 'moment'; import DatePicker from 'react-datepicker'; {}} - onYearChange={(date: moment.Moment) => {}} + selected={new Date()} + onChange={(date: Date | null) => {}} + onYearChange={(date: Date) => {}} popperModifiers={{ flip: { enabled: false } }} - includeTimes={[moment()]} + includeTimes={[new Date()]} >
diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 05058b2ca9..9e96538f7d 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -55,6 +55,7 @@ declare namespace ReactDates { screenReaderInputMessage?: string, showClearDates?: boolean, showDefaultInputIcon?: boolean, + inputIconPosition?: IconPositionShape, customInputIcon?: string | JSX.Element, customArrowIcon?: string | JSX.Element, customCloseIcon?: string | JSX.Element, diff --git a/types/react-foundation/components/responsive.d.ts b/types/react-foundation/components/responsive.d.ts index 9b3a8361ed..94a915f2c8 100644 --- a/types/react-foundation/components/responsive.d.ts +++ b/types/react-foundation/components/responsive.d.ts @@ -24,6 +24,36 @@ export declare class ResponsiveNavigation extends Component; + alignX: PropTypes.Requireable; + alignY: PropTypes.Requireable; + selfAlignX: PropTypes.Requireable; + selfAlignY: PropTypes.Requireable; + centerAlign: PropTypes.Requireable; + flexContainer: PropTypes.Requireable; + flexDirRow: PropTypes.Requireable; + flexDirRowRev: PropTypes.Requireable; + flexDirCol: PropTypes.Requireable; + flexDirColRev: PropTypes.Requireable; + flexChild: PropTypes.Requireable; + flexOrder: PropTypes.Requireable; + flexOrderSmall: PropTypes.Requireable; + flexOrderMedium: PropTypes.Requireable; + flexOrderLarge: PropTypes.Requireable; + showFor: PropTypes.Requireable; + showOnlyFor: PropTypes.Requireable; + hideFor: PropTypes.Requireable; + hideOnlyFor: PropTypes.Requireable; + isHidden: PropTypes.Requireable; + isInvisible: PropTypes.Requireable; + showForLandscape: PropTypes.Requireable; + showForPortrait: PropTypes.Requireable; + showForSr: PropTypes.Requireable; + showOnFocus: PropTypes.Requireable; + isClearfix: PropTypes.Requireable; + float: PropTypes.Requireable; + }; static defaultProps: { breakpoint: number; }; diff --git a/types/react-gravatar/index.d.ts b/types/react-gravatar/index.d.ts index b2962edc8d..56e48b3b9b 100644 --- a/types/react-gravatar/index.d.ts +++ b/types/react-gravatar/index.d.ts @@ -25,7 +25,7 @@ declare namespace Gravatar { type DefaultImage = "404" | "mm" | "identicon" | "monsterid" | "wavatar" | "retro" | "blank"; type Rating = "g" | "pg" | "r" | "x"; - interface Props { + interface Props extends Partial { /** * The email address used to look up the Gravatar image. * If you wish to avoid sending an email address to the client, you can compute the md5 hash on the server and diff --git a/types/react-lottie/index.d.ts b/types/react-lottie/index.d.ts index 8e4f3b717b..a57da91307 100644 --- a/types/react-lottie/index.d.ts +++ b/types/react-lottie/index.d.ts @@ -7,7 +7,7 @@ import * as React from 'react'; -interface Options { +export interface Options { /** * Defines if the animation should play only once or repeatedly in an endless loop */ @@ -41,7 +41,7 @@ interface Options { }; } -interface EventListener { +export interface EventListener { /** * The event sent by Lottie */ @@ -61,7 +61,7 @@ interface EventListener { callback: () => void; } -interface LottieProps { +export interface LottieProps { /** * Object representing animation settings */ diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 6e54b6d7c9..24e4aee9dc 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3629,6 +3629,18 @@ interface ImagePropsAndroid { * Duration of fade in animation. */ fadeDuration?: number; + + /** + * Required if loading images via 'uri' from drawable folder on Android. + * Explanation: https://medium.com/@adamjacobb/react-native-performance-images-adf5843e120 + */ + width?: number; + + /** + * Required if loading images via 'uri' from drawable folder on Android + * Explanation: https://medium.com/@adamjacobb/react-native-performance-images-adf5843e120 + */ + height?: number; } /** @@ -9037,8 +9049,11 @@ export const PixelRatio: PixelRatioStatic; * * const View = requireNativeComponent('RCTView'); * + * The concrete return type of `requireNativeComponent` is a string, but the declared type is + * `any` because TypeScript assumes anonymous JSX intrinsics (`string` instead of `"div", for + * example) not to have any props. */ -export function requireNativeComponent(viewName: string): React.ReactType; +export function requireNativeComponent(viewName: string): any; export function findNodeHandle( componentOrHandle: null | number | React.Component | React.ComponentClass diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 62e3d93a1d..6a6a85c19e 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-places-autocomplete 6.1 +// Type definitions for react-places-autocomplete 7.2 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov @@ -15,13 +15,10 @@ export interface formattedSuggestionType { } export interface PropTypes { - inputProps: { - value: string; - onChange: (value: string) => void; + inputProps?: { type?: string; name?: string; placeholder?: string; - onBlur?: (event: React.FocusEvent) => void; disabled?: boolean; }; onError?: (status: string, clearSuggestion: () => void) => void; @@ -49,6 +46,9 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; + value?: string; + onChange?: (value: string) => void; + onBlur?: (event: React.FocusEvent) => void; debounce?: number; highlightFirstSuggestion?: boolean; diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx index 41e6ff37b4..a7a7816d99 100644 --- a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -45,7 +45,7 @@ class Test extends React.Component { return (
- + ); } diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts index 8c6e5fb6c8..387b538882 100644 --- a/types/react-select/lib/components/Menu.d.ts +++ b/types/react-select/lib/components/Menu.d.ts @@ -67,6 +67,9 @@ export type MenuProps = CommonProps & { export function menuCSS(state: MenuState): React.CSSProperties; export class Menu extends Component, MenuState> { + static contextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; getPlacement: (ref: ElementRef) => void; getState: () => MenuProps & MenuState; } @@ -143,6 +146,9 @@ interface PortalStyleArgs { export function menuPortalCSS(args: PortalStyleArgs): React.CSSProperties; export class MenuPortal extends Component, MenuPortalState> { + static childContextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; getChildContext(): { getPortalPlacement: (state: MenuState) => void; }; diff --git a/types/react-select/test/examples/CustomNoOptionsMessage.tsx b/types/react-select/test/examples/CustomNoOptionsMessage.tsx index 3896272d5b..6bea4cb47a 100644 --- a/types/react-select/test/examples/CustomNoOptionsMessage.tsx +++ b/types/react-select/test/examples/CustomNoOptionsMessage.tsx @@ -18,12 +18,7 @@ const NoOptionsMessage = (props: any) => { export default class CustomNoOptionsMessage extends React.Component { render() { return ( - // Without the type argument, `OptionType` is inferred as `never` from the - // `options` attribute of type `never[]`, and `Select.defaultProps` (of - // type `Props`) fails to be assignable to the instantiated props - // type, `Props`. This issue shouldn't come up in real code where - // the `options` attribute isn't a literal empty array. - +