├── .babelrc ├── .browserslistrc ├── .circleci └── config.yml ├── .commitlintrc.js ├── .coveralls.yml ├── .cz-config.js ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .npmrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── README.zh_CN.md ├── example ├── index.html └── index.js ├── package-lock.json ├── package.json ├── scripts ├── config.js └── rollup │ ├── rollup.config.base.js │ ├── rollup.config.dev.js │ └── rollup.config.prod.js ├── src ├── main.ts └── utils │ ├── check.ts │ └── is.ts ├── test ├── check.test.ts ├── config.test.ts └── mocha.opts ├── tsconfig.build.json ├── tsconfig.json └── typings └── .gitkeep /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["@babel/preset-env", { 4 | "modules": false 5 | }] 6 | ], 7 | "plugins": [ 8 | 9 | ] 10 | } -------------------------------------------------------------------------------- /.browserslistrc: -------------------------------------------------------------------------------- 1 | > 0.5% 2 | last 2 versions 3 | not ie <= 8 4 | not dead -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Javascript Node CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-javascript/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # specify the version you desire here 10 | - image: circleci/node:latest 11 | filters: 12 | branches: 13 | only: master 14 | 15 | # Specify service dependencies here if necessary 16 | # CircleCI maintains a library of pre-built images 17 | # documented at https://circleci.com/docs/2.0/circleci-images/ 18 | # - image: circleci/mongo:3.4.4 19 | 20 | working_directory: ~/repo 21 | 22 | steps: 23 | - checkout 24 | 25 | # Download and cache dependencies 26 | - restore_cache: 27 | keys: 28 | - v1-dependencies-{{ checksum "package.json" }} 29 | # fallback to using the latest cache if no exact match is found 30 | - v1-dependencies- 31 | 32 | - run: npm install 33 | 34 | - save_cache: 35 | paths: 36 | - node_modules 37 | key: v1-dependencies-{{ checksum "package.json" }} 38 | 39 | - run: npm run build 40 | # run tests! 41 | - run: npm run coveralls 42 | -------------------------------------------------------------------------------- /.commitlintrc.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | extends: [ 5 | 'cz' 6 | ], 7 | rules: { 8 | } 9 | }; -------------------------------------------------------------------------------- /.coveralls.yml: -------------------------------------------------------------------------------- 1 | repo_token: TFbUzLlEXxWMQbaJT5kQrWriw70K4RNcy -------------------------------------------------------------------------------- /.cz-config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | 5 | types: [ 6 | { 7 | value: ':construction: WIP', 8 | name : '💪 WIP: Work in progress' 9 | }, 10 | { 11 | value: ':sparkles: feat', 12 | name : '✨ feat: A new feature' 13 | }, 14 | { 15 | value: ':bug: fix', 16 | name : '🐛 fix: A bug fix' 17 | }, 18 | { 19 | value: ':hammer: refactor', 20 | name : '🔨 refactor: A code change that neither fixes a bug nor adds a feature' 21 | }, 22 | { 23 | value: ':pencil: docs', 24 | name : '📝 docs: Documentation only changes' 25 | }, 26 | { 27 | value: ':white_check_mark: test', 28 | name : '✅ test: Add missing tests or correcting existing tests' 29 | }, 30 | { 31 | value: ':thought_balloon: chore', 32 | name : '🗯 chore: Changes that don\'t modify src or test files. Such as updating build tasks, package manager' 33 | }, 34 | { 35 | value: ':lipstick: ui', 36 | name: '💄 Updating the UI and style files.', 37 | }, 38 | { 39 | value: ':art: style', 40 | name: 41 | '🎨 Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)', 42 | }, 43 | { 44 | value: 'revert', 45 | name : '⏪ revert: Revert to a commit' 46 | }, 47 | { 48 | value: ':package: dep_up', 49 | name: '📦 Updating compiled files or packages.', 50 | }, 51 | { 52 | value: ':green_heart: fixci', 53 | name: '💚 Fixing CI Build.', 54 | }, 55 | { 56 | value: ':truck: mv', 57 | name: '🚚 Moving or renaming files.', 58 | }, 59 | { 60 | value: ':fire: prune', 61 | name: '🔥 Removing code or files.', 62 | }, 63 | { 64 | value: ':bookmark: release', 65 | name: '🔖 Releasing / Version tags.', 66 | } 67 | ], 68 | 69 | scopes: [], 70 | 71 | allowCustomScopes: true, 72 | allowBreakingChanges: ["feat", "fix"] 73 | }; 74 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/*.js 2 | examples/*.js 3 | rollup.config.*.js 4 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", // 支持新的es7属性 4 | "parserOptions": { 5 | "ecmaVersion": 6, // 指定你使用的 ECMAScript 版本 6 | "sourceType": "module", // 代码是 ECMAScript 模块 7 | "ecmaFeatures": { // 额外的语言特性 8 | "experimentalObjectRestSpread": true // 支持新的es7属性 9 | }, 10 | "project": "./tsconfig.json" 11 | }, 12 | "env":{ 13 | "es6": true, // 启用除了 modules 以外的所有 ECMAScript 6 特性(该选项会自动设置 ecmaVersion 解析器选项为 6 14 | "browser": true, // 浏览器环境中的全局变量 15 | "node":true, 16 | "commonjs": true, 17 | "mocha": true 18 | }, 19 | "extends": [ 20 | "eslint:recommended", 21 | "plugin:@typescript-eslint/recommended" 22 | ], // 核心规则 23 | "globals": { // 全局变量 24 | 25 | }, 26 | "plugins": [ // 第三方插件 27 | "@typescript-eslint" 28 | ], 29 | "rules": { 30 | "prefer-const": "off", 31 | "no-unused-vars": "warn", 32 | "no-console": "off", 33 | "generator-star-spacing": "off", 34 | "@typescript-eslint/no-explicit-any": "off", 35 | "@typescript-eslint/explicit-function-return-type": "off", 36 | } 37 | }; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # General 2 | .DS_Store 3 | .AppleDouble 4 | .LSOverride 5 | 6 | # Thumbnails 7 | ._* 8 | 9 | # Files that might appear in the root of a volume 10 | .DocumentRevisions-V100 11 | .fseventsd 12 | .Spotlight-V100 13 | .TemporaryItems 14 | .Trashes 15 | .VolumeIcon.icns 16 | .com.apple.timemachine.donotpresent 17 | 18 | # Directories potentially created on remote AFP share 19 | .AppleDB 20 | .AppleDesktop 21 | Network Trash Folder 22 | Temporary Items 23 | .apdisk 24 | 25 | # Logs 26 | logs 27 | *.log 28 | npm-debug.log* 29 | 30 | # Runtime data 31 | pids 32 | *.pid 33 | *.seed 34 | 35 | # Editor directories and files 36 | .idea 37 | .vscode 38 | 39 | # Dependency directories 40 | node_modules 41 | 42 | # Optional 43 | .npm 44 | .node_repl_history 45 | 46 | # assets publish 47 | # you can ignore dist Folder if you publish your assets with CI to CDN 48 | 49 | # Project specific stuff 50 | .rpt2_cache 51 | .nyc_output 52 | lib 53 | dist 54 | .mocha_test 55 | coverage -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | //registry=https://registry.npm.taobao.org -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ### [1.0.3](https://github.com/wall-wxk/ping-url/compare/v1.0.2...v1.0.3) (2019-08-09) 6 | 7 | ### [1.0.2](https://github.com/wall-wxk/ping-url/compare/v1.0.1...v1.0.2) (2019-08-08) 8 | 9 | ### [1.0.1](https://github.com/wall-wxk/ping-url/compare/v1.0.0...v1.0.1) (2019-08-08) 10 | 11 | ## 1.0.0 (2019-08-08) 12 | 13 | 14 | ### Features 15 | 16 | * ping url first release! ([2382187](https://github.com/wall-wxk/ping-url/commit/2382187)) 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Leon Wang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [![CircleCI](https://img.shields.io/circleci/build/github/wall-wxk/ping-url/master)](https://circleci.com/gh/wall-wxk/ping-url/tree/master) [![Coverage Status](https://coveralls.io/repos/github/wall-wxk/ping-url/badge.svg?branch=master)](https://coveralls.io/github/wall-wxk/ping-url?branch=master) [![NPM version](https://img.shields.io/npm/v/ping-url.svg)](https://www.npmjs.com/package/ping-url) [![download](https://img.shields.io/npm/dm/ping-url)](https://www.npmjs.com/package/ping-url) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/wall-wxk/ping-url/blob/master/LICENSE) 2 | 3 | English | [中文简体](https://github.com/wall-wxk/ping-url/blob/master/README.zh_CN.md) 4 | 5 | ## :sparkles:Features 6 | 7 | - Check the url is normally accessible or not. 8 | - Check url network latency. 9 | 10 | ## :traffic_light:Environment Support 11 | 12 | | [IE / Edge](http://godban.github.io/browsers-support-badges/)
IE / Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | [Opera](http://godban.github.io/browsers-support-badges/)
Opera | 13 | | --- | --- | --- | --- | --- | 14 | | IE9, IE10, IE11, Edge | last 2 versions | last 2 versions | last 2 versions | last 2 versions | 15 | 16 | ## :rocket:Install 17 | 18 | Using npm, download and install the code. 19 | ```bash 20 | npm install --save ping-url 21 | ``` 22 | For node environment: 23 | ```js 24 | var base = require('ping-url'); 25 | ``` 26 | For webpack or similar environment: 27 | ```js 28 | import base from 'ping-url'; 29 | ``` 30 | For requirejs environment: 31 | ```js 32 | requirejs(['node_modules/ping-url/dist/ping-url.cjs.js'], function (base) { 33 | // do something... 34 | }) 35 | ``` 36 | For browser environment: 37 | ```html 38 | 39 | ``` 40 | 41 | ## :books:API 42 | 43 | ### `Ping.config` 44 | > Customize the protocol name 45 | 46 | The default protocol for Ping is `http`. If customization is required, use this method to set it up before use. 47 | 48 | - param {object} option 49 | - option.protocol {string} protocol `values:['http', 'https']` 50 | - return {string} The protocol name of the final setting 51 | 52 | #### example 53 | ```javascript 54 | import Ping from 'ping-url'; 55 | 56 | Ping.config({ 57 | protocol: 'https' 58 | }); 59 | ``` 60 | 61 | ### `Ping.check` 62 | > Checks the availability of the url and returns the check information. 63 | 64 | Check its accessibility and network latency by requesting the url. 65 | 66 | - param {string} url the url to detect 67 | - return {object} return `Promise` object 68 | - response(resolve status) 69 | - response.status {boolean} `true`: Can be accessed `false`: Can not be accessed 70 | - response.time {number} Network delay (millisecond), when inaccessible, the default is' -1 ' 71 | - response(reject status) 72 | - response.status {boolean} `false`: Can not be accessed 73 | - response.msg {string} Error message 74 | 75 | #### example 76 | ```javascript 77 | import Ping from 'ping-url'; 78 | 79 | Ping.check('https://wangxiaokai.vip').then(res => { 80 | console.log(`status: ${res.status} and time: ${res.time}`); 81 | }, res => { 82 | console.log(`error msg: ${res.msg}`); 83 | }); 84 | ``` 85 | 86 | 87 | ## :page_facing_up:LICENSE 88 | MIT 89 | 90 | -------------------------------------------------------------------------------- /README.zh_CN.md: -------------------------------------------------------------------------------- 1 | # [![CircleCI](https://img.shields.io/circleci/build/github/wall-wxk/ping-url/master)](https://circleci.com/gh/wall-wxk/ping-url/tree/master) [![Coverage Status](https://coveralls.io/repos/github/wall-wxk/ping-url/badge.svg?branch=master)](https://coveralls.io/github/wall-wxk/ping-url?branch=master) [![NPM version](https://img.shields.io/npm/v/ping-url.svg)](https://www.npmjs.com/package/ping-url) [![download](https://img.shields.io/npm/dm/ping-url)](https://www.npmjs.com/package/ping-url) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/wall-wxk/ping-url/blob/master/LICENSE) 2 | 3 | [English](https://github.com/wall-wxk/ping-url/blob/master/README.md) | 中文简体 4 | 5 | ## :sparkles:特性 6 | 7 | - 检测url是否可正常访问 8 | - 检测url网络延时 9 | 10 | ## :traffic_light:兼容性 11 | 12 | | [IE / Edge](http://godban.github.io/browsers-support-badges/)
IE / Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | [Opera](http://godban.github.io/browsers-support-badges/)
Opera | 13 | | --- | --- | --- | --- | --- | 14 | | IE9, IE10, IE11, Edge | last 2 versions | last 2 versions | last 2 versions | last 2 versions | 15 | 16 | ## :rocket:安装 17 | 18 | 通过npm安装 19 | ```bash 20 | npm install --save ping-url 21 | ``` 22 | node环境 23 | ```js 24 | var base = require('ping-url'); 25 | ``` 26 | webpack及其类似的环境 27 | ```js 28 | import base from 'ping-url'; 29 | ``` 30 | require.js环境 31 | ```js 32 | requirejs(['node_modules/ping-url/dist/ping-url.cjs.js'], function (base) { 33 | // do something... 34 | }) 35 | ``` 36 | 浏览器环境 37 | ```html 38 | 39 | ``` 40 | 41 | ## :books:文档 42 | 43 | ### `Ping.config` 44 | > 自定义协议名 45 | 46 | Ping的默认协议是`http`。如果需要自定义,在使用之前用该方法进行设置即可。 47 | 48 | - param {object} option 49 | - option.protocol {string} 协议 `取值:['http', 'https']` 50 | - return {string} 最终设置的协议名 51 | 52 | #### 例子 53 | ```javascript 54 | import Ping from 'ping-url'; 55 | 56 | Ping.config({ 57 | protocol: 'https' 58 | }); 59 | ``` 60 | 61 | ### `Ping.check` 62 | > 检测url的可用性,并返回检测信息 63 | 64 | 通过请求url,检测其可访问性和网络延时。 65 | 66 | - param {string} url 要检测的url 67 | - return {object} 返回`Promise`对象 68 | - response(resolve状态) 69 | - response.status {boolean} `true`:可访问 `false`:不可访问 70 | - response.time {number} 网络延时(毫秒),不可访问时,默认为`-1` 71 | - response(reject状态) 72 | - response.status {boolean} `false`:不可访问 73 | - response.msg {string} 错误信息 74 | 75 | #### 例子 76 | ```javascript 77 | import Ping from 'ping-url'; 78 | 79 | Ping.check('https://wangxiaokai.vip').then(res => { 80 | console.log(`status: ${res.status} and time: ${res.time}`); 81 | }, res => { 82 | console.log(`error msg: ${res.msg}`); 83 | }); 84 | ``` 85 | 86 | 87 | ## :page_facing_up:许可证 88 | MIT 89 | 90 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ping-url 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | var root = document.getElementById('root'); 2 | Ping.config({ 3 | protocol: 'https' 4 | }); 5 | Ping.check('google.com').then(function(res){ 6 | console.log('success', res); 7 | }, function(res){ 8 | console.log('error', res); 9 | }) 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ping-url", 3 | "version": "1.0.3", 4 | "description": "Check the url is normally accessible or not", 5 | "main": "main.js", 6 | "scripts": { 7 | "commit": "git-cz", 8 | "release": "standard-version", 9 | "clean": "rimraf dist && rimraf lib", 10 | "clean:example": "rimraf example/lib", 11 | "dev": "npm run clean:example && rollup --watch --config scripts/rollup/rollup.config.dev.js", 12 | "build": "npm run clean && tsc --project tsconfig.build.json && rollup --config scripts/rollup/rollup.config.prod.js", 13 | "eslint": "eslint src --fix --ext .ts", 14 | "push:publish": "npm run build && git push --follow-tags origin master && npm publish", 15 | "test": "cross-env NODE_ENV=test nyc mocha", 16 | "test:report": "./node_modules/http-server/bin/http-server ./coverage -p 8087 -o -c-1", 17 | "coveralls": "npm run test && nyc report --reporter=text-lcov | coveralls" 18 | }, 19 | "author": { 20 | "name": "leon", 21 | "email": "582104384@qq.com", 22 | "url": "https://wangxiaokai.vip" 23 | }, 24 | "license": "MIT", 25 | "devDependencies": { 26 | "@babel/cli": "^7.5.5", 27 | "@babel/core": "^7.5.5", 28 | "@babel/plugin-proposal-class-properties": "^7.5.5", 29 | "@babel/plugin-transform-runtime": "^7.5.5", 30 | "@babel/preset-env": "^7.5.5", 31 | "@babel/preset-typescript": "^7.3.3", 32 | "@babel/register": "^7.5.5", 33 | "@commitlint/cli": "^8.1.0", 34 | "@commitlint/config-conventional": "^8.1.0", 35 | "@types/expect": "^1.20.4", 36 | "@types/mocha": "^5.2.7", 37 | "@types/node": "^12.6.9", 38 | "@typescript-eslint/eslint-plugin": "^1.13.0", 39 | "@typescript-eslint/parser": "^1.13.0", 40 | "canvas": "^2.5.0", 41 | "chai": "^4.2.0", 42 | "commitizen": "^4.0.3", 43 | "commitlint-config-cz": "^0.12.1", 44 | "coveralls": "^3.0.5", 45 | "cross-env": "^5.2.0", 46 | "cz-customizable": "^6.2.0", 47 | "eslint": "^5.16.0", 48 | "esm": "^3.2.25", 49 | "http-server": "^0.11.1", 50 | "husky": "^3.0.2", 51 | "jsdom": "^15.1.1", 52 | "jsdom-global": "^3.0.2", 53 | "lint-staged": "^9.2.1", 54 | "mocha": "^6.2.0", 55 | "mocha-lcov-reporter": "^1.3.0", 56 | "nyc": "^14.1.1", 57 | "rimraf": "^2.6.3", 58 | "rollup": "^1.18.0", 59 | "rollup-plugin-alias": "^1.5.2", 60 | "rollup-plugin-babel": "^4.3.3", 61 | "rollup-plugin-commonjs": "^10.0.2", 62 | "rollup-plugin-eslint": "^7.0.0", 63 | "rollup-plugin-filesize": "^6.1.1", 64 | "rollup-plugin-json": "^4.0.0", 65 | "rollup-plugin-node-resolve": "^5.2.0", 66 | "rollup-plugin-replace": "^2.2.0", 67 | "rollup-plugin-serve": "^1.0.1", 68 | "rollup-plugin-typescript2": "^0.22.1", 69 | "rollup-plugin-uglify": "^6.0.2", 70 | "source-map-support": "^0.5.13", 71 | "standard-version": "^7.0.0", 72 | "ts-node": "^8.3.0", 73 | "typescript": "^3.5.3", 74 | "uglify-es": "^3.3.9" 75 | }, 76 | "files": [ 77 | "dist/*.js", 78 | "lib" 79 | ], 80 | "husky": { 81 | "hooks": { 82 | "pre-commit": "lint-staged", 83 | "commit-msg": "commitlint -e $GIT_PARAMS" 84 | } 85 | }, 86 | "lint-staged": { 87 | "src/**/*.ts": [ 88 | "eslint src --ext .ts", 89 | "git add" 90 | ] 91 | }, 92 | "config": { 93 | "commitizen": { 94 | "path": "node_modules/cz-customizable" 95 | } 96 | }, 97 | "types": "./lib/types/main.d.ts", 98 | "module": "dist/ping-url.esm.js", 99 | "unpkg": "dist/ping-url.min.js", 100 | "keywords": [ 101 | "ping url", 102 | "ping host", 103 | "ping" 104 | ], 105 | "homepage": "https://github.com/wall-wxk/ping-url", 106 | "repository": { 107 | "type": "git", 108 | "url": "https://github.com/wall-wxk/ping-url.git" 109 | }, 110 | "dependencies": {}, 111 | "nyc": { 112 | "include": [ 113 | "src/**/*.ts", 114 | "test/**/*.ts" 115 | ], 116 | "extension": [ 117 | ".ts", 118 | ".tsx" 119 | ], 120 | "require": [ 121 | "ts-node/register" 122 | ], 123 | "reporter": [ 124 | "text-summary", 125 | "html" 126 | ], 127 | "sourceMap": true, 128 | "instrument": true, 129 | "all": true 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /scripts/config.js: -------------------------------------------------------------------------------- 1 | export const libraryName = "Ping"; -------------------------------------------------------------------------------- /scripts/rollup/rollup.config.base.js: -------------------------------------------------------------------------------- 1 | import json from 'rollup-plugin-json'; 2 | import alias from 'rollup-plugin-alias'; 3 | import babel from 'rollup-plugin-babel'; 4 | import resolve from 'rollup-plugin-node-resolve'; 5 | import commonjs from 'rollup-plugin-commonjs'; 6 | import {eslint} from 'rollup-plugin-eslint'; 7 | 8 | export default { 9 | input: 'src/main.ts', 10 | plugins: [ 11 | resolve(), 12 | json(), 13 | alias({ 14 | resolve: ['.js', '.ts'] 15 | }), 16 | babel({ 17 | exclude: 'node_modules/**', // 只编译我们的源代码 18 | runtimeHelpers: true, 19 | babelrc: false, 20 | comments: false, 21 | presets: [ 22 | ["@babel/preset-env", { 23 | "modules": false, 24 | "useBuiltIns": false 25 | }], 26 | ["@babel/preset-typescript"] 27 | ], 28 | plugins: [ 29 | "@babel/plugin-transform-runtime" 30 | ] 31 | }), 32 | commonjs({ 33 | include: 'node_modules/**' 34 | }), 35 | eslint({ 36 | include: ['src/**/*.js'] 37 | }) 38 | ] 39 | }; -------------------------------------------------------------------------------- /scripts/rollup/rollup.config.dev.js: -------------------------------------------------------------------------------- 1 | import serve from 'rollup-plugin-serve'; 2 | import typescript from 'rollup-plugin-typescript2'; 3 | 4 | import baseConfig from './rollup.config.base'; 5 | 6 | import { 7 | name 8 | } from '../../package.json'; 9 | import { 10 | libraryName 11 | } from '../config.js'; 12 | 13 | 14 | const override = { 15 | compilerOptions: { 16 | "declaration": false, 17 | } 18 | }; 19 | 20 | export default { 21 | ...baseConfig, 22 | output: [ 23 | // example 24 | { 25 | file: `example/lib/${name}.js`, 26 | format: 'umd', 27 | name: libraryName, 28 | sourcemap: true 29 | }, 30 | { 31 | file: `example/lib/${name}.cjs.js`, 32 | format: 'cjs', 33 | name: libraryName, 34 | sourcemap: 'inline' 35 | } 36 | ], 37 | plugins: [ 38 | ...baseConfig.plugins, 39 | typescript({ 40 | exclude: ['node_modules/**', "test"], 41 | "tsconfig": "tsconfig.build.json", 42 | "tsconfigOverride": override 43 | }), 44 | serve({ 45 | port: 8080, 46 | contentBase: ['example'] 47 | }) 48 | ] 49 | } -------------------------------------------------------------------------------- /scripts/rollup/rollup.config.prod.js: -------------------------------------------------------------------------------- 1 | import filesize from 'rollup-plugin-filesize'; 2 | import {uglify} from 'rollup-plugin-uglify'; 3 | import { minify } from 'uglify-es'; 4 | import typescript from 'rollup-plugin-typescript2'; 5 | import replace from 'rollup-plugin-replace'; 6 | 7 | import baseConfig from './rollup.config.base'; 8 | import { 9 | name, 10 | version, 11 | author, 12 | license 13 | } from '../../package.json'; 14 | import { 15 | libraryName 16 | } from '../config.js'; 17 | 18 | const banner = ` 19 | /*! 20 | * ${name}.js v${version} 21 | * (c) 2019-${new Date().getFullYear()} ${author.name} 22 | * Released under the ${license} License. 23 | */ 24 | `; 25 | 26 | const override = { 27 | compilerOptions: { 28 | "declaration": false, 29 | } 30 | }; 31 | 32 | const typescriptConfig = { 33 | exclude: ['node_modules/**', 'test'], 34 | "tsconfig": "tsconfig.build.json", 35 | "tsconfigOverride": override 36 | } 37 | 38 | export default [ 39 | { 40 | ...baseConfig, 41 | output: [ 42 | // umd development version with sourcemap 43 | { 44 | file: `dist/${name}.js`, 45 | format: 'umd', 46 | name: libraryName, 47 | banner, 48 | sourcemap: true 49 | }, 50 | // cjs and esm version 51 | { 52 | file: `dist/${name}.cjs.js`, 53 | format: 'cjs', 54 | banner 55 | }, 56 | // cjs and esm version 57 | { 58 | file: `dist/${name}.esm.js`, 59 | format: 'es', 60 | banner 61 | } 62 | ], 63 | plugins: [ 64 | ...baseConfig.plugins, 65 | replace({ 66 | 'process.env.NODE_ENV': JSON.stringify('production') 67 | }), 68 | typescript(typescriptConfig), 69 | filesize() 70 | ] 71 | }, 72 | { 73 | ...baseConfig, 74 | output: [ 75 | // umd with compress version 76 | { 77 | file: `dist/${name}.min.js`, 78 | format: 'umd', 79 | name, 80 | banner 81 | } 82 | ], 83 | plugins: [ 84 | ...baseConfig.plugins, 85 | replace({ 86 | 'process.env.NODE_ENV': JSON.stringify('production') 87 | }), 88 | typescript(typescriptConfig), 89 | uglify({ 90 | compress: { 91 | drop_console: true 92 | } 93 | }, minify), 94 | filesize() 95 | ] 96 | } 97 | ]; -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { 2 | getLoadTime, 3 | getStatus, 4 | } from './utils/check'; 5 | import { 6 | isUrl 7 | } from './utils/is' 8 | interface Tresult{ 9 | status: boolean; 10 | time: number; 11 | } 12 | 13 | let protocol = 'http'; // 默认协议 14 | const protocolList: string[] = ['http', 'https']; 15 | interface TconfigOption{ 16 | protocol: string; 17 | } 18 | /** 19 | * 设置默认协议 20 | * @param prot 协议名 21 | */ 22 | function config({ 23 | protocol: prot 24 | }: TconfigOption){ 25 | if(!protocolList.includes(prot)){ 26 | throw new Error(`protocolList not includes ${prot}`); 27 | } 28 | protocol = prot; 29 | return protocol; 30 | } 31 | /** 32 | * 检查url是否能访问,并返回检测数据 33 | * @param url 检测的url 34 | */ 35 | function check(url){ 36 | return new Promise(async (resolve, reject) => { 37 | if(!isUrl(url)){ 38 | reject({ 39 | status: false, 40 | msg: `url is not correct!` 41 | }); 42 | return; 43 | } 44 | if(!url.includes('http://') && !url.includes('https://')){ 45 | url = `${protocol}://${url}`; 46 | } 47 | 48 | let result: Tresult = { 49 | status: false, 50 | time: -1 51 | }; 52 | const status = await getStatus(url) as boolean; 53 | const time = await getLoadTime(url) as number; 54 | 55 | result.status = status; 56 | result.time = time; 57 | 58 | resolve(result); 59 | }); 60 | } 61 | export default { 62 | /** 63 | * 检查url是否能访问,并返回检测数据 64 | * @param url 检测的url 65 | */ 66 | check: (url: string) => check(url), 67 | /** 68 | * 设置默认协议 69 | * @param option 70 | * option.protocol 协议名 71 | */ 72 | config: (option: TconfigOption) => config(option) 73 | }; -------------------------------------------------------------------------------- /src/utils/check.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 检测网址访问延时时长 3 | * 4 | * @param url 网址 5 | */ 6 | export function getLoadTime(url: string){ 7 | return new Promise(resolve => { 8 | let img = document.createElement('img'); 9 | img.style.display = "none"; 10 | img.src=`${url}/?v=${Math.random()}`; 11 | const timeStart = new Date(); 12 | 13 | img.onerror = function(){ 14 | const timeEnd = new Date(); 15 | resolve(timeEnd.getTime() - timeStart.getTime()); 16 | } 17 | img.onload = function(){ 18 | const timeEnd = new Date(); 19 | resolve(timeEnd.getTime() - timeStart.getTime()); 20 | } 21 | 22 | document.body.appendChild(img); 23 | }); 24 | } 25 | 26 | /** 27 | * 检测网址是否有效 28 | * 29 | * @param url 网址 30 | */ 31 | export function getStatus(url: string){ 32 | return new Promise((resolve, reject) => { 33 | let link = document.createElement('link'); 34 | link.rel="stylesheet"; 35 | link.type="text/css" 36 | link.href = url; 37 | 38 | link.onload = function(){ 39 | resolve(true); 40 | } 41 | link.onerror = function(){ 42 | resolve(false); 43 | } 44 | 45 | document.body.appendChild(link); 46 | }) 47 | } -------------------------------------------------------------------------------- /src/utils/is.ts: -------------------------------------------------------------------------------- 1 | const strRegex = "^((https|http)://)?" + "(([0-9a-z]+\\.)*" + "([0-9a-z][0-9a-z-]{0,20})?[0-9a-z]\\." + "[a-z]{2,6})" + "(:[0-9]{1,4})?" + "((/?)|" + "(/[0-9a-z_!~*().;?:@&=+$,%#-]+)+/?)$"; 2 | 3 | /** 4 | * 检测是否为合法的url 5 | * @param strUrl 6 | */ 7 | export function isUrl(strUrl) { 8 | const re = new RegExp(strRegex, "g"); 9 | if (re.test(strUrl)) { 10 | return true; 11 | } 12 | 13 | return false; 14 | } -------------------------------------------------------------------------------- /test/check.test.ts: -------------------------------------------------------------------------------- 1 | import Ping from '../src/main' 2 | import { 3 | getLoadTime 4 | } from '../src/utils/check' 5 | import { 6 | expect 7 | } from 'chai'; 8 | 9 | import { JSDOM } from 'jsdom'; 10 | const window = (new JSDOM(``, { resources: "usable" })).window; 11 | (global as any).document = window.document;; 12 | (global as any).window = window; 13 | 14 | describe('ping-url check', function(){ 15 | it('check m.baidu.com', function(){ 16 | Ping.check('m.baidu.com').then(result => { 17 | expect(result).to.have.property('status'); 18 | expect(result).to.have.property('time'); 19 | }); 20 | }) 21 | it('check not url', function(){ 22 | Ping.check('666').then(result => { 23 | }, result => { 24 | expect(result.status).to.equal(false); 25 | expect(result.msg).to.equal('url is not correct!'); 26 | }); 27 | }) 28 | it('getStatus true', function(){ 29 | Ping.check('http://m.baidu.com').then(result => { 30 | expect(result.status).to.equal(true); 31 | }); 32 | }) 33 | it('getStatus false', function(){ 34 | Ping.check('http://ertfffferer.notexist.com').then(result => { 35 | expect(result.status).to.equal(false); 36 | }); 37 | }) 38 | it('getLoadTime has time', function(){ 39 | Ping.check('http://m.baidu.com').then(result => { 40 | expect(result.time).to.not.equal(-1); 41 | }); 42 | }) 43 | it('getLoadTime has no time', function(){ 44 | Ping.check('http://ertfffferer.notexist.com').then(result => { 45 | expect(result.time).to.equal(-1); 46 | }); 47 | }) 48 | it('getLoadTime img onload', function(){ 49 | getLoadTime('https://timgsa.baidu.com/timg?test=0.8224775295479003image&quality=80&size=b9999_10000&sec=1564057772998&di=708714cd53be9a59b468d1472778a34f&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201608%2F06%2F20160806232840_WZCjT.jpeg').then((result:any) => { 50 | expect(result.time).to.not.equal(-1); 51 | }); 52 | }) 53 | }) -------------------------------------------------------------------------------- /test/config.test.ts: -------------------------------------------------------------------------------- 1 | import Ping from '../src/main'; 2 | import { 3 | expect 4 | } from 'chai'; 5 | 6 | describe('ping-url config', function(){ 7 | it('config default', function(){ 8 | const result = Ping.config({ 9 | protocol: 'https' 10 | }); 11 | expect(result).to.equal('https'); 12 | }) 13 | it('config error protocol', function(){ 14 | const protocol = 'tcp'; 15 | expect(function(){ 16 | Ping.config({ 17 | protocol: protocol 18 | }); 19 | }).to.throw(`protocolList not includes ${protocol}`); 20 | }) 21 | }) -------------------------------------------------------------------------------- /test/mocha.opts: -------------------------------------------------------------------------------- 1 | --require esm 2 | --require jsdom-global/register 3 | --require ts-node/register 4 | --require source-map-support/register 5 | --recursive 6 | ./test/**/*.test.ts -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "outDir": "lib", 5 | "module": "es2015", 6 | "target": "es5", 7 | "lib": ["es6", "dom"], 8 | "sourceMap": true, 9 | "moduleResolution": "node", 10 | "rootDir": "src", 11 | "forceConsistentCasingInFileNames": true, 12 | "noImplicitReturns": true, 13 | "noImplicitThis": true, 14 | "noImplicitAny": false, 15 | "importHelpers": true, 16 | "strictNullChecks": true, 17 | "suppressImplicitAnyIndexErrors": true, 18 | "noUnusedLocals": true, 19 | "allowSyntheticDefaultImports": true, 20 | "experimentalDecorators": true, 21 | "resolveJsonModule": true, 22 | "esModuleInterop": true, 23 | "declaration": true, 24 | "declarationDir": "lib/types", 25 | "removeComments": true 26 | }, 27 | "exclude": [ 28 | "node_modules", 29 | "scripts", 30 | "lib", 31 | "dist", 32 | "test" 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "outDir": ".mocha_test", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "lib": ["es6", "dom"], 8 | "sourceMap": true, 9 | "moduleResolution": "node", 10 | "rootDir": "test", 11 | "forceConsistentCasingInFileNames": true, 12 | "noImplicitReturns": true, 13 | "noImplicitThis": true, 14 | "noImplicitAny": false, 15 | "importHelpers": true, 16 | "strictNullChecks": true, 17 | "suppressImplicitAnyIndexErrors": true, 18 | "noUnusedLocals": true, 19 | "allowSyntheticDefaultImports": true, 20 | "experimentalDecorators": true, 21 | "resolveJsonModule": true, 22 | "esModuleInterop": true 23 | }, 24 | "exclude": [ 25 | "node_modules", 26 | "scripts", 27 | "lib", 28 | "dist" 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /typings/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wall-wxk/ping-url/d937726584562b56793bd38f9291f9d1029640ed/typings/.gitkeep --------------------------------------------------------------------------------