├── sample
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── layout
│ │ │ └── activity_main.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── me
│ │ └── wcy
│ │ └── mockhttp
│ │ └── sample
│ │ └── MainActivity.kt
├── proguard-rules.pro
└── build.gradle
├── mock-http
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ ├── assets
│ │ └── mock-http
│ │ │ ├── addon
│ │ │ └── lint
│ │ │ │ ├── json-lint.js
│ │ │ │ ├── lint.css
│ │ │ │ └── lint.js
│ │ │ ├── lib
│ │ │ ├── codemirror.css
│ │ │ └── jsonlint.js
│ │ │ ├── index.html
│ │ │ ├── request.html
│ │ │ └── mode
│ │ │ └── javascript
│ │ │ └── javascript.js
│ │ └── java
│ │ └── me
│ │ └── wcy
│ │ └── mockhttp
│ │ ├── MockHttpEntity.kt
│ │ ├── MockHttpOptions.kt
│ │ ├── MockHttpUtils.kt
│ │ ├── Logger.kt
│ │ ├── MockHttpServer.kt
│ │ ├── MockHttpInterceptor.kt
│ │ └── MockHttp.kt
├── proguard-rules.pro
└── build.gradle
├── mock-http-release
├── consumer-rules.pro
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── me
│ │ └── wcy
│ │ └── mockhttp
│ │ ├── MockHttpInterceptor.kt
│ │ ├── MockHttp.kt
│ │ └── MockHttpOptions.kt
├── proguard-rules.pro
└── build.gradle
├── art
├── demo.jpg
└── architecture.jpg
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/mock-http/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/mock-http-release/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/mock-http-release/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/art/demo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/art/demo.jpg
--------------------------------------------------------------------------------
/art/architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/art/architecture.jpg
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':mock-http'
2 | include ':mock-http-release'
3 | include ':sample'
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | mock-http
3 |
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/mock-http-release/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangchenyan/mock-http/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 14 15:29:02 CST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/mock-http/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/mock-http-release/src/main/java/me/wcy/mockhttp/MockHttpInterceptor.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import okhttp3.Interceptor
4 | import okhttp3.Response
5 |
6 | /**
7 | * Created by wcy on 2019/5/23.
8 | */
9 | class MockHttpInterceptor : Interceptor {
10 |
11 | override fun intercept(chain: Interceptor.Chain): Response {
12 | return chain.proceed(chain.request())
13 | }
14 | }
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | android.enableJetifier=true
10 | android.useAndroidX=true
11 | org.gradle.jvmargs=-Xmx1536m
12 | # When configured, Gradle will run in incubating parallel mode.
13 | # This option should only be used with decoupled projects. More details, visit
14 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
15 | # org.gradle.parallel=true
16 | VERSION_NAME=1.7
--------------------------------------------------------------------------------
/mock-http/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/mock-http-release/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 28
7 | buildToolsVersion "28.0.3"
8 |
9 | defaultConfig {
10 | applicationId "me.wcy.mockhttp.sample"
11 | minSdkVersion 15
12 | targetSdkVersion 28
13 | versionCode 1
14 | versionName VERSION_NAME
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | compileOptions {
25 | sourceCompatibility JavaVersion.VERSION_1_8
26 | targetCompatibility JavaVersion.VERSION_1_8
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(include: ['*.jar'], dir: 'libs')
32 | implementation project(':mock-http')
33 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
34 | implementation 'androidx.appcompat:appcompat:1.2.0'
35 | implementation 'com.squareup.okhttp3:okhttp:3.14.2'
36 | }
37 |
--------------------------------------------------------------------------------
/mock-http/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | mavenCentral()
4 | }
5 |
6 | dependencies {
7 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
8 | }
9 | }
10 |
11 | apply plugin: 'com.android.library'
12 | apply plugin: 'kotlin-android'
13 | apply plugin: 'com.github.dcendents.android-maven'
14 |
15 | group = 'com.github.wangchenyan'
16 |
17 | android {
18 | compileSdkVersion 28
19 | buildToolsVersion "28.0.3"
20 |
21 | defaultConfig {
22 | minSdkVersion 9
23 | targetSdkVersion 28
24 | versionCode 1
25 | versionName VERSION_NAME
26 |
27 | consumerProguardFiles 'proguard-rules.pro'
28 | }
29 |
30 | compileOptions {
31 | sourceCompatibility JavaVersion.VERSION_1_8
32 | targetCompatibility JavaVersion.VERSION_1_8
33 | }
34 | }
35 |
36 | dependencies {
37 | implementation fileTree(include: ['*.jar'], dir: 'libs')
38 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
39 | implementation 'com.koushikdutta.async:androidasync:2.2.1'
40 | compileOnly 'com.squareup.okhttp3:okhttp:3.14.2'
41 | }
42 |
--------------------------------------------------------------------------------
/mock-http-release/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | mavenCentral()
4 | }
5 |
6 | dependencies {
7 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
8 | }
9 | }
10 |
11 | apply plugin: 'com.android.library'
12 | apply plugin: 'kotlin-android'
13 | apply plugin: 'com.github.dcendents.android-maven'
14 |
15 | group = 'com.github.wangchenyan'
16 |
17 | android {
18 | compileSdkVersion 28
19 | buildToolsVersion "28.0.3"
20 |
21 | defaultConfig {
22 | minSdkVersion 9
23 | targetSdkVersion 28
24 | versionCode 1
25 | versionName VERSION_NAME
26 |
27 | consumerProguardFiles 'consumer-rules.pro'
28 | }
29 |
30 | compileOptions {
31 | sourceCompatibility JavaVersion.VERSION_1_8
32 | targetCompatibility JavaVersion.VERSION_1_8
33 | }
34 | }
35 |
36 | dependencies {
37 | implementation fileTree(dir: 'libs', include: ['*.jar'])
38 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
39 | implementation 'androidx.appcompat:appcompat:1.2.0'
40 | compileOnly 'com.squareup.okhttp3:okhttp:3.14.2'
41 | }
42 |
--------------------------------------------------------------------------------
/mock-http-release/src/main/java/me/wcy/mockhttp/MockHttp.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.Context
5 |
6 | /**
7 | * MOCK HTTP
8 | * Created by wcy on 2019/5/23.
9 | */
10 | class MockHttp private constructor() {
11 |
12 | companion object {
13 | fun get(): MockHttp {
14 | return SingletonHolder.instance
15 | }
16 | }
17 |
18 | private object SingletonHolder {
19 | @SuppressLint("StaticFieldLeak")
20 | val instance = MockHttp()
21 | }
22 |
23 | /**
24 | * 获取 MOCK HTTP 配置项
25 | */
26 | fun getMockHttpOptions(): MockHttpOptions? {
27 | return null
28 | }
29 |
30 | /**
31 | * 设置 MOCK HTTP 配置项
32 | * 需要在 [start] 之前调用,否则将使用默认配置
33 | *
34 | * @param options MOCK HTTP 配置项
35 | * @see MockHttpOptions
36 | */
37 | fun setMockHttpOptions(options: MockHttpOptions) {
38 | }
39 |
40 | /**
41 | * 启动 MOCK 服务,开始 MOCK
42 | * 如果是多进程应用,只需要在主进程中初始化
43 | *
44 | * @param ctx 上下文
45 | */
46 | fun start(ctx: Context) {
47 | }
48 |
49 | /**
50 | * 停止 MOCK 服务,释放资源
51 | */
52 | fun stop() {
53 | }
54 |
55 | /**
56 | * 是否已经启动
57 | */
58 | fun hasStart(): Boolean {
59 | return false
60 | }
61 |
62 | /**
63 | * 获取 MOCK 服务器地址
64 | */
65 | fun getMockAddress(): String {
66 | return ""
67 | }
68 | }
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/addon/lint/json-lint.js:
--------------------------------------------------------------------------------
1 | // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 | // Distributed under an MIT license: https://codemirror.net/LICENSE
3 |
4 | // Depends on jsonlint.js from https://github.com/zaach/jsonlint
5 |
6 | // declare global: jsonlint
7 |
8 | (function(mod) {
9 | if (typeof exports == "object" && typeof module == "object") // CommonJS
10 | mod(require("../../lib/codemirror"));
11 | else if (typeof define == "function" && define.amd) // AMD
12 | define(["../../lib/codemirror"], mod);
13 | else // Plain browser env
14 | mod(CodeMirror);
15 | })(function(CodeMirror) {
16 | "use strict";
17 |
18 | CodeMirror.registerHelper("lint", "json", function(text) {
19 | var found = [];
20 | if (!window.jsonlint) {
21 | if (window.console) {
22 | window.console.error("Error: window.jsonlint not defined, CodeMirror JSON linting cannot run.");
23 | }
24 | return found;
25 | }
26 | // for jsonlint's web dist jsonlint is exported as an object with a single property parser, of which parseError
27 | // is a subproperty
28 | var jsonlint = window.jsonlint.parser || window.jsonlint
29 | jsonlint.parseError = function(str, hash) {
30 | var loc = hash.loc;
31 | found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column),
32 | to: CodeMirror.Pos(loc.last_line - 1, loc.last_column),
33 | message: str});
34 | };
35 | try { jsonlint.parse(text); }
36 | catch(e) {}
37 | return found;
38 | });
39 |
40 | });
41 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/mock-http-release/src/main/java/me/wcy/mockhttp/MockHttpOptions.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import android.util.Log
4 |
5 | /**
6 | * MockHttp 配置项
7 | * Created by wcy on 2019/5/26.
8 | */
9 | class MockHttpOptions private constructor() {
10 |
11 | /**
12 | * MOCK 服务端口,如果已经启动服务,则端口设置不会生效
13 | */
14 | fun getMockServerPort(): Int {
15 | return 0
16 | }
17 |
18 | /**
19 | * 获取 MOCK HTTP 等待时间
20 | */
21 | fun getMockSleepTime(): Long {
22 | return 0
23 | }
24 |
25 | /**
26 | * 是否打印日志
27 | */
28 | fun isLogEnable(): Boolean {
29 | return false
30 | }
31 |
32 | /**
33 | * 日志标签
34 | */
35 | fun getLogTag(): String {
36 | return ""
37 | }
38 |
39 | /**
40 | * 日志级别
41 | */
42 | fun getLogLevel(): Int {
43 | return 0
44 | }
45 |
46 | class Builder {
47 | private val options = MockHttpOptions()
48 |
49 | /**
50 | * 设置 MOCK 服务端口
51 | *
52 | * @param port 端口
53 | */
54 | fun setMockServerPort(port: Int): Builder {
55 | return this
56 | }
57 |
58 | /**
59 | * 设置 MOCK HTTP 等待时间
60 | *
61 | * @param milli 毫秒,默认为 0
62 | */
63 | fun setMockSleepTime(milli: Long): Builder {
64 | return this
65 | }
66 |
67 | /**
68 | * 设置是否打印日志,开启 Mock 后才能打印日志
69 | *
70 | * @param enable 是否打印日志
71 | */
72 | fun setLogEnable(enable: Boolean): Builder {
73 | return this
74 | }
75 |
76 | /**
77 | * 设置日志标签
78 | *
79 | * @param tag 日志标签
80 | */
81 | fun setLogTag(tag: String): Builder {
82 | return this
83 | }
84 |
85 | /**
86 | * 设置日志级别,参考 [Log]
87 | *
88 | * @param level 日志级别,支持 [Log.VERBOSE] [Log.DEBUG] [Log.INFO] [Log.WARN] [Log.ERROR]
89 | */
90 | fun setLogLevel(level: Int): Builder {
91 | return this
92 | }
93 |
94 | fun build(): MockHttpOptions {
95 | return options
96 | }
97 | }
98 | }
--------------------------------------------------------------------------------
/mock-http/src/main/java/me/wcy/mockhttp/MockHttpEntity.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import org.json.JSONObject
4 |
5 | /**
6 | * Created by wcy on 2019/5/23.
7 | */
8 | internal data class MockHttpEntity(
9 | var path: String = "",
10 | var requestUrl: String = "",
11 | var requestMethod: String = "",
12 | var statusCode: Int = 0,
13 | var requestHeader: String = "",
14 | var queryParameter: String = "",
15 | var requestBody: String = "",
16 | var responseHeader: String = "",
17 | var responseBody: String = "") {
18 |
19 | companion object {
20 | fun fromJson(json: String?): MockHttpEntity? {
21 | if (json == null) {
22 | return null
23 | }
24 |
25 | try {
26 | val jsonObject = JSONObject(json)
27 | val entity = MockHttpEntity()
28 | entity.path = jsonObject.optString("path")
29 | entity.requestUrl = jsonObject.optString("requestUrl")
30 | entity.requestMethod = jsonObject.optString("requestMethod")
31 | entity.statusCode = jsonObject.optInt("statusCode")
32 | entity.requestHeader = jsonObject.optString("requestHeader")
33 | entity.queryParameter = jsonObject.optString("queryParameter")
34 | entity.requestBody = jsonObject.optString("requestBody")
35 | entity.responseHeader = jsonObject.optString("responseHeader")
36 | entity.responseBody = jsonObject.getString("responseBody")
37 | return entity
38 | } catch (e: Exception) {
39 | e.printStackTrace()
40 | }
41 |
42 | return null
43 | }
44 | }
45 |
46 | fun toJson(): String {
47 | val map = mutableMapOf()
48 | map["path"] = path
49 | map["requestUrl"] = requestUrl
50 | map["requestMethod"] = requestMethod
51 | map["statusCode"] = statusCode
52 | map["requestHeader"] = requestHeader
53 | map["queryParameter"] = queryParameter
54 | map["requestBody"] = requestBody
55 | map["responseHeader"] = responseHeader
56 | map["responseBody"] = responseBody
57 | return JSONObject(map).toString(2)
58 | }
59 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
19 |
20 |
27 |
28 |
29 |
33 |
34 |
41 |
42 |
49 |
50 |
51 |
56 |
57 |
65 |
66 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/mock-http/src/main/java/me/wcy/mockhttp/MockHttpOptions.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import android.util.Log
4 |
5 | /**
6 | * MockHttp 配置项
7 | * Created by wcy on 2019/5/26.
8 | */
9 | class MockHttpOptions private constructor() {
10 | private var mockServerPort = 8000
11 | private var mockSleepTime = 0L
12 | private var logEnable = false
13 | private var logTag = "MOCK-HTTP-LOGGER"
14 | private var logLevel = Log.DEBUG
15 |
16 | /**
17 | * MOCK 服务端口,如果已经启动服务,则端口设置不会生效
18 | */
19 | fun getMockServerPort(): Int {
20 | return mockServerPort
21 | }
22 |
23 | /**
24 | * 获取 MOCK HTTP 等待时间
25 | */
26 | fun getMockSleepTime(): Long {
27 | return mockSleepTime
28 | }
29 |
30 | /**
31 | * 是否打印日志
32 | */
33 | fun isLogEnable(): Boolean {
34 | return logEnable
35 | }
36 |
37 | /**
38 | * 日志标签
39 | */
40 | fun getLogTag(): String {
41 | return logTag
42 | }
43 |
44 | /**
45 | * 日志级别
46 | */
47 | fun getLogLevel(): Int {
48 | return logLevel
49 | }
50 |
51 | class Builder {
52 | private val options = MockHttpOptions()
53 |
54 | /**
55 | * 设置 MOCK 服务端口
56 | *
57 | * @param port 端口
58 | */
59 | fun setMockServerPort(port: Int): Builder {
60 | options.mockServerPort = port
61 | return this
62 | }
63 |
64 | /**
65 | * 设置 MOCK HTTP 等待时间
66 | *
67 | * @param milli 毫秒,默认为 0
68 | */
69 | fun setMockSleepTime(milli: Long): Builder {
70 | options.mockSleepTime = milli
71 | return this
72 | }
73 |
74 | /**
75 | * 设置是否打印日志,开启 Mock 后才能打印日志
76 | *
77 | * @param enable 是否打印日志
78 | */
79 | fun setLogEnable(enable: Boolean): Builder {
80 | options.logEnable = enable
81 | return this
82 | }
83 |
84 | /**
85 | * 设置日志标签
86 | *
87 | * @param tag 日志标签
88 | */
89 | fun setLogTag(tag: String): Builder {
90 | options.logTag = tag
91 | return this
92 | }
93 |
94 | /**
95 | * 设置日志级别,参考 [Log]
96 | *
97 | * @param level 日志级别,支持 [Log.VERBOSE] [Log.DEBUG] [Log.INFO] [Log.WARN] [Log.ERROR]
98 | */
99 | fun setLogLevel(level: Int): Builder {
100 | options.logLevel = level
101 | return this
102 | }
103 |
104 | fun build(): MockHttpOptions {
105 | return options
106 | }
107 | }
108 | }
--------------------------------------------------------------------------------
/mock-http/src/main/java/me/wcy/mockhttp/MockHttpUtils.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import android.content.Context
4 | import android.os.Handler
5 | import android.os.Looper
6 | import com.koushikdutta.async.http.server.AsyncHttpServer
7 | import java.io.IOException
8 | import java.io.InputStream
9 | import java.io.StringBufferInputStream
10 |
11 | /**
12 | * Created by wcy on 2020-01-16.
13 | */
14 | internal object MockHttpUtils {
15 | private val uiHandler: Handler by lazy {
16 | Handler(Looper.getMainLooper())
17 | }
18 |
19 | fun initThirdParty(context: Context, asyncHttpServer: AsyncHttpServer) {
20 | asyncHttpServer.get("/lib/codemirror.css") { request, response ->
21 | val stream = getAssetsStream(context, "/lib/codemirror.css")
22 | response.setContentType("text/css")
23 | response.sendStream(stream, stream.available().toLong())
24 | }
25 |
26 | asyncHttpServer.get("/addon/lint/lint.css") { request, response ->
27 | val stream = getAssetsStream(context, "/addon/lint/lint.css")
28 | response.setContentType("text/css")
29 | response.sendStream(stream, stream.available().toLong())
30 | }
31 |
32 | asyncHttpServer.get("/lib/codemirror.js") { request, response ->
33 | val stream = getAssetsStream(context, "/lib/codemirror.js")
34 | response.setContentType("application/javascript")
35 | response.sendStream(stream, stream.available().toLong())
36 | }
37 |
38 | asyncHttpServer.get("/lib/jsonlint.js") { request, response ->
39 | val stream = getAssetsStream(context, "/lib/jsonlint.js")
40 | response.setContentType("application/javascript")
41 | response.sendStream(stream, stream.available().toLong())
42 | }
43 |
44 | asyncHttpServer.get("/mode/javascript/javascript.js") { request, response ->
45 | val stream = getAssetsStream(context, "/mode/javascript/javascript.js")
46 | response.setContentType("application/javascript")
47 | response.sendStream(stream, stream.available().toLong())
48 | }
49 |
50 | asyncHttpServer.get("/addon/lint/lint.js") { request, response ->
51 | val stream = getAssetsStream(context, "/addon/lint/lint.js")
52 | response.setContentType("application/javascript")
53 | response.sendStream(stream, stream.available().toLong())
54 | }
55 |
56 | asyncHttpServer.get("/addon/lint/json-lint.js") { request, response ->
57 | val stream = getAssetsStream(context, "/addon/lint/json-lint.js")
58 | response.setContentType("application/javascript")
59 | response.sendStream(stream, stream.available().toLong())
60 | }
61 | }
62 |
63 | fun getAssetsStream(context: Context, name: String): InputStream {
64 | try {
65 | return context.assets.open("mock-http$name")
66 | } catch (e: IOException) {
67 | e.printStackTrace()
68 | return StringBufferInputStream(e.message)
69 | }
70 | }
71 |
72 | fun runOnUi(r: Runnable) {
73 | uiHandler.post(r)
74 | }
75 | }
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/addon/lint/lint.css:
--------------------------------------------------------------------------------
1 | /* The lint marker gutter */
2 | .CodeMirror-lint-markers {
3 | width: 16px;
4 | }
5 |
6 | .CodeMirror-lint-tooltip {
7 | background-color: #ffd;
8 | border: 1px solid black;
9 | border-radius: 4px 4px 4px 4px;
10 | color: black;
11 | font-family: monospace;
12 | font-size: 10pt;
13 | overflow: hidden;
14 | padding: 2px 5px;
15 | position: fixed;
16 | white-space: pre;
17 | white-space: pre-wrap;
18 | z-index: 100;
19 | max-width: 600px;
20 | opacity: 0;
21 | transition: opacity .4s;
22 | -moz-transition: opacity .4s;
23 | -webkit-transition: opacity .4s;
24 | -o-transition: opacity .4s;
25 | -ms-transition: opacity .4s;
26 | }
27 |
28 | .CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {
29 | background-position: left bottom;
30 | background-repeat: repeat-x;
31 | }
32 |
33 | .CodeMirror-lint-mark-error {
34 | background-image:
35 | url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==")
36 | ;
37 | }
38 |
39 | .CodeMirror-lint-mark-warning {
40 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=");
41 | }
42 |
43 | .CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {
44 | background-position: center center;
45 | background-repeat: no-repeat;
46 | cursor: pointer;
47 | display: inline-block;
48 | height: 16px;
49 | width: 16px;
50 | vertical-align: middle;
51 | position: relative;
52 | }
53 |
54 | .CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {
55 | padding-left: 18px;
56 | background-position: top left;
57 | background-repeat: no-repeat;
58 | }
59 |
60 | .CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {
61 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=");
62 | }
63 |
64 | .CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {
65 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=");
66 | }
67 |
68 | .CodeMirror-lint-marker-multiple {
69 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC");
70 | background-repeat: no-repeat;
71 | background-position: right bottom;
72 | width: 100%; height: 100%;
73 | }
74 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android MOCK HTTP 接口新方式
2 |
3 | [](https://jitpack.io/#wangchenyan/mock-http)
4 | 
5 |
6 | MOCK-HTTP 是一个方便、易用的查看和模拟 HTTP 请求的工具,可以代替 Charles,支持打印网络日志。
7 |
8 | release 模式下仅依赖空壳,mock 功能自动失效,对包大小几乎无影响。
9 |
10 | 目前仅支持查看和模拟 OkHttp 发送的请求。
11 |
12 | 视频演示:
13 |
14 | [](https://v.youku.com/v_show/id_XNDUzNzE5MTM4NA==.html)
15 |
16 | 架构设计:
17 |
18 | 
19 |
20 | 原理解析:https://juejin.im/post/6844903855151382535
21 |
22 | ## 更新记录
23 |
24 | `v 1.6`
25 | - 增加 release 模式下的空壳依赖
26 |
27 | `v 1.5.1`
28 | - 不处理非文本请求
29 |
30 | `v 1.5`
31 | - 优化公开方法
32 |
33 | `v 1.4`
34 | - MOCK 页面支持 JSON 校验
35 |
36 | ## 使用方法
37 |
38 | ### Gradle
39 |
40 | **Step 1.** Add the JitPack repository to your build file
41 |
42 | Add it in your root build.gradle at the end of repositories:
43 |
44 | ```
45 | allprojects {
46 | repositories {
47 | ...
48 | maven { url 'https://jitpack.io' }
49 | }
50 | }
51 | ```
52 |
53 | **Step 2.** Add the dependency
54 |
55 | ```
56 | dependencies {
57 | debugImplementation 'com.github.wangchenyan.mock-http:mock-http:+'
58 | releaseImplementation 'com.github.wangchenyan.mock-http:mock-http-release:+'
59 | }
60 | ```
61 |
62 | **Step 3.** 启用 MOCK-HTTP
63 |
64 | ```
65 | // 配置项
66 | val options = MockHttpOptions.Builder()
67 | .setMockServerPort(5000)
68 | .setMockSleepTime(500)
69 | .setLogEnable(true)
70 | .setLogTag("MAIN-TAG")
71 | .setLogLevel(Log.ERROR)
72 | .build()
73 | MockHttp.get().setMockHttpOptions(options)
74 | // 启动 MOCK 服务
75 | MockHttp.get().start(applicationContext)
76 | // 停止 MOCK 服务
77 | MockHttp.get().stop()
78 |
79 | // 添加 OKHTTP 拦截器
80 | val okHttpClient = OkHttpClient()
81 | .newBuilder()
82 | .addInterceptor(MockHttpInterceptor())
83 | .build()
84 | ```
85 |
86 | ## 方法
87 |
88 | | 方法 | 描述 | 备注 |
89 | | ---- | ---- | ---- |
90 | | setMockHttpOptions(MockHttpOptions) | 设置 MOCK HTTP 配置项 | 需要在 start(Context) 方法之前调用,否则将使用默认配置 |
91 | | start(Context) | 启动 MOCK 服务,开始 MOCK | 如果是多进程应用,只需要在主进程中初始化 |
92 | | stop() | 停止 MOCK 服务,释放资源 | |
93 | | getMockAddress() | 获取 MOCK 服务器地址 | |
94 | | hasStart() | 是否已经启动 | |
95 | | MockHttpOptions.Builder().setMockServerPort(Int) | 设置 MOCK 端口 | |
96 | | MockHttpOptions.Builder().setMockSleepTime(Long) | 设置 MOCK 接口等待时长 | 单位毫秒,默认为0 |
97 | | MockHttpOptions.Builder().setLogEnable(Boolean) | 设置是否打印日志 | 开启 Mock 后才能打印日志 |
98 | | MockHttpOptions.Builder().setLogTag(String) | 设置日志标签 | |
99 | | MockHttpOptions.Builder().setLogLevel(Int) | 设置日志级别,参考 android.util.Log | 支持 VERBOSE DEBUG INFO WARN ERROR |
100 |
101 | ## 致谢
102 |
103 | - [AndroidAsync](https://github.com/koush/AndroidAsync)
104 |
105 | ## 关于作者
106 |
107 | 掘金:https://juejin.im/user/2313028193754168
108 |
109 | 微博:https://weibo.com/wangchenyan1993
110 |
111 | ## License
112 |
113 | Copyright 2019 wangchenyan
114 |
115 | Licensed under the Apache License, Version 2.0 (the "License");
116 | you may not use this file except in compliance with the License.
117 | You may obtain a copy of the License at
118 |
119 | http://www.apache.org/licenses/LICENSE-2.0
120 |
121 | Unless required by applicable law or agreed to in writing, software
122 | distributed under the License is distributed on an "AS IS" BASIS,
123 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
124 | See the License for the specific language governing permissions and
125 | limitations under the License.
126 |
--------------------------------------------------------------------------------
/mock-http/src/main/java/me/wcy/mockhttp/Logger.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import android.text.TextUtils
4 | import android.util.Log
5 | import java.util.*
6 |
7 | /**
8 | * Created by wcy on 2019-09-10.
9 | */
10 | internal object Logger {
11 | private val lock = Any()
12 |
13 | fun logRequest(url: String, method: String, headers: String, params: String, body: String) {
14 | val options = MockHttp.get().getMockHttpOptions()
15 | if (options == null || !options.isLogEnable()) {
16 | return
17 | }
18 |
19 | val log = "┌────── Mock Http Request ──────────────────────────────────────────────────────────────" +
20 | "\n│ URL: $url" +
21 | "\n│ " +
22 | "\n│ Method: $method" +
23 | "\n│ " +
24 | "\n│ Headers: ${prettyHeaders(headers)}" +
25 | "\n│ " +
26 | "\n│ Parameter: $params" +
27 | "\n│ " +
28 | "\n│ Body:" +
29 | "\n│ ${prettyBody(body)}" +
30 | "\n└───────────────────────────────────────────────────────────────────────────────────────"
31 |
32 | printLog(log, options)
33 | }
34 |
35 | fun logResponse(url: String, status: Int, headers: String, body: String) {
36 | val options = MockHttp.get().getMockHttpOptions()
37 | if (options == null || !options.isLogEnable()) {
38 | return
39 | }
40 |
41 | val log = "┌────── Mock Http Response ─────────────────────────────────────────────────────────────" +
42 | "\n│ URL: $url" +
43 | "\n│ " +
44 | "\n│ Status: $status" +
45 | "\n│ " +
46 | "\n│ Headers: ${prettyHeaders(headers)}" +
47 | "\n│ " +
48 | "\n│ Body:" +
49 | "\n│ ${prettyBody(body)}" +
50 | "\n└───────────────────────────────────────────────────────────────────────────────────────"
51 |
52 | printLog(log, options)
53 | }
54 |
55 | private fun printLog(log: String, options: MockHttpOptions) {
56 | synchronized(lock) {
57 | val tag = options.getLogTag()
58 | val level = options.getLogLevel()
59 | val logs = log.split("\n")
60 | for (line in logs) {
61 | when (level) {
62 | Log.VERBOSE -> Log.v(tag, line)
63 | Log.DEBUG -> Log.d(tag, line)
64 | Log.INFO -> Log.i(tag, line)
65 | Log.WARN -> Log.w(tag, line)
66 | Log.ERROR -> Log.e(tag, line)
67 | }
68 | }
69 | }
70 | }
71 |
72 | private fun prettyHeaders(headers: String): String {
73 | val list = ArrayList(headers.split("\n"))
74 | val size = list.size
75 | for (i in size - 1 downTo 0) {
76 | if (TextUtils.isEmpty(list[i])) {
77 | list.removeAt(i)
78 | }
79 | }
80 |
81 | val sb = StringBuilder()
82 | for (i in list.indices) {
83 | val symbol = if (i == 0) {
84 | "┌"
85 | } else if (i == list.size - 1) {
86 | "└"
87 | } else {
88 | "├"
89 | }
90 | sb.append("\n│ $symbol ").append(list[i])
91 | }
92 | return sb.toString()
93 | }
94 |
95 | private fun prettyBody(body: String): String {
96 | val list = body.split("\n")
97 | val sb = StringBuilder()
98 | for (line in list) {
99 | sb.append("\n│ $line")
100 | }
101 | return sb.toString()
102 | }
103 | }
--------------------------------------------------------------------------------
/mock-http/src/main/java/me/wcy/mockhttp/MockHttpServer.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import android.content.Context
4 | import android.util.Log
5 | import android.widget.Toast
6 | import com.koushikdutta.async.AsyncServer
7 | import com.koushikdutta.async.callback.CompletedCallback
8 | import com.koushikdutta.async.http.server.AsyncHttpServer
9 | import org.json.JSONArray
10 | import org.json.JSONObject
11 | import java.net.URLDecoder
12 |
13 | /**
14 | * Created by wcy on 2019/5/24.
15 | */
16 | internal class MockHttpServer {
17 | private var asyncHttpServer: AsyncHttpServer? = null
18 | private var asyncServer: AsyncServer? = null
19 |
20 | companion object {
21 | private const val TAG = "MockHttpServer"
22 | }
23 |
24 | fun startServer(context: Context) {
25 | asyncHttpServer = AsyncHttpServer()
26 | asyncServer = AsyncServer()
27 |
28 | MockHttpUtils.initThirdParty(context, asyncHttpServer!!)
29 |
30 | asyncHttpServer!!.get("/") { request, response ->
31 | val stream = MockHttpUtils.getAssetsStream(context, "/index.html")
32 | response.setContentType("text/html")
33 | response.sendStream(stream, stream.available().toLong())
34 | }
35 |
36 | asyncHttpServer!!.get("/request") { request, response ->
37 | val stream = MockHttpUtils.getAssetsStream(context, "/request.html")
38 | response.setContentType("text/html")
39 | response.sendStream(stream, stream.available().toLong())
40 | }
41 |
42 | asyncHttpServer!!.post("/getRequestList") { request, response ->
43 | try {
44 | val requestBody = request.body.get() as JSONObject
45 | val mock = requestBody.getInt("mock") == 1
46 | val requestList = MockHttp.get().getRequestList(mock)
47 | response.setContentType("application/json")
48 | response.send(JSONArray(requestList).toString())
49 | } catch (e: Exception) {
50 | e.printStackTrace()
51 | response.code(500).send(e.message)
52 | }
53 | }
54 |
55 | asyncHttpServer!!.post("/getRequest") { request, response ->
56 | try {
57 | val requestBody = request.body.get() as JSONObject
58 | val path = requestBody.getString("path")
59 | val httpEntity = MockHttp.get().getRequest(path)
60 | response.setContentType("application/json")
61 | response.send(httpEntity?.toJson() ?: "{}")
62 | } catch (e: Exception) {
63 | e.printStackTrace()
64 | response.code(500).send(e.message)
65 | }
66 | }
67 |
68 | asyncHttpServer!!.post("/mock") { request, response ->
69 | try {
70 | val requestBody = request.body.get() as JSONObject
71 | val path = requestBody.getString("path")
72 | val responseBody = URLDecoder.decode(requestBody.getString("responseBody"), Charsets.UTF_8.name())
73 | MockHttp.get().mock(path, responseBody)
74 | response.send("success")
75 | } catch (e: Exception) {
76 | e.printStackTrace()
77 | response.code(500).send(e.message)
78 | }
79 | }
80 |
81 | asyncHttpServer!!.post("/unmock") { request, response ->
82 | try {
83 | val requestBody = request.body.get() as JSONObject
84 | val path = requestBody.getString("path")
85 | MockHttp.get().unmock(path)
86 | response.send("success")
87 | } catch (e: Exception) {
88 | e.printStackTrace()
89 | response.code(500).send(e.message)
90 | }
91 | }
92 |
93 | val options = MockHttp.get().getMockHttpOptions()!!
94 | asyncHttpServer!!.errorCallback = CompletedCallback {
95 | Log.e(TAG, "mock http server error", it)
96 | MockHttpUtils.runOnUi(Runnable {
97 | Toast.makeText(context, it.message, Toast.LENGTH_SHORT).show()
98 | })
99 | }
100 | asyncHttpServer!!.listen(asyncServer, options.getMockServerPort())
101 | }
102 |
103 | fun stopServer() {
104 | asyncHttpServer?.stop()
105 | asyncServer?.stop()
106 | asyncHttpServer = null
107 | asyncServer = null
108 | }
109 | }
--------------------------------------------------------------------------------
/sample/src/main/java/me/wcy/mockhttp/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp.sample
2 |
3 | import android.os.Bundle
4 | import android.util.Log
5 | import android.view.View
6 | import android.widget.ScrollView
7 | import androidx.appcompat.app.AppCompatActivity
8 | import kotlinx.android.synthetic.main.activity_main.*
9 | import me.wcy.mockhttp.MockHttp
10 | import me.wcy.mockhttp.MockHttpInterceptor
11 | import me.wcy.mockhttp.MockHttpOptions
12 | import okhttp3.OkHttpClient
13 | import okhttp3.Request
14 | import org.json.JSONArray
15 | import org.json.JSONException
16 | import org.json.JSONObject
17 | import java.util.concurrent.Executors
18 |
19 | class MainActivity : AppCompatActivity(), View.OnClickListener {
20 | private val okHttpClient = OkHttpClient()
21 | .newBuilder()
22 | .addInterceptor(MockHttpInterceptor())
23 | .build()
24 | private val executor = Executors.newFixedThreadPool(5)
25 |
26 | override fun onCreate(savedInstanceState: Bundle?) {
27 | super.onCreate(savedInstanceState)
28 | setContentView(R.layout.activity_main)
29 |
30 | val options = MockHttpOptions.Builder()
31 | .setMockServerPort(5000)
32 | .setMockSleepTime(500)
33 | .setLogEnable(true)
34 | .setLogTag("MAIN-TAG")
35 | .setLogLevel(Log.ERROR)
36 | .build()
37 | MockHttp.get().setMockHttpOptions(options)
38 | }
39 |
40 | override fun onDestroy() {
41 | super.onDestroy()
42 | MockHttp.get().stop()
43 | }
44 |
45 | override fun onClick(v: View?) {
46 | when (v) {
47 | btn_start_mock -> {
48 | MockHttp.get().start(applicationContext)
49 | log("\nMock 服务启动\nMock 后台地址:\n${MockHttp.get().getMockAddress()}")
50 | }
51 | btn_stop_mock -> {
52 | MockHttp.get().stop()
53 | log("\nMock 服务停止")
54 | }
55 | btn_request_1 -> {
56 | request("https://www.wanandroid.com/article/top/json")
57 | }
58 | btn_request_2 -> {
59 | request("https://www.wanandroid.com/hotkey/json")
60 | }
61 | }
62 | }
63 |
64 | private fun request(url: String) {
65 | executor.execute {
66 | val request = Request.Builder()
67 | .url(url)
68 | .header("MOCK-HTTP-HEADER", "TEST")
69 | .build()
70 |
71 | log("\n开始请求:\n$url")
72 |
73 | var responseText: String
74 | try {
75 | val response = okHttpClient.newCall(request).execute()
76 | val responseBody = response.body()
77 | val subtype = responseBody?.contentType()?.subtype()
78 | if (responseBody != null && isNotFileRequest(subtype)) {
79 | responseText = responseBody.string()
80 | } else {
81 | responseText = "response body is not text"
82 | }
83 | } catch (e: Exception) {
84 | responseText = e.message ?: "request fail"
85 | }
86 |
87 | log("\n请求结果:\n${formatJson(responseText)}")
88 | }
89 | }
90 |
91 | private fun log(log: String) {
92 | runOnUiThread {
93 | tv_network_log.append("\n$log")
94 | scroll_view.post {
95 | scroll_view.fullScroll(ScrollView.FOCUS_DOWN)
96 | }
97 | }
98 | }
99 |
100 | private fun isNotFileRequest(subtype: String?): Boolean {
101 | return subtype != null && (subtype.contains("json")
102 | || subtype.contains("xml")
103 | || subtype.contains("plain")
104 | || subtype.contains("html"))
105 | }
106 |
107 | private fun formatJson(json: String): String {
108 | var string: String
109 | try {
110 | if (json.startsWith("{")) {
111 | string = JSONObject(json).toString(2)
112 | } else if (json.startsWith("[")) {
113 | string = JSONArray(json).toString(2)
114 | } else {
115 | string = json
116 | }
117 | } catch (e: JSONException) {
118 | string = json
119 | } catch (e1: OutOfMemoryError) {
120 | string = "Output omitted because of Object size."
121 | }
122 |
123 | return string
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/mock-http/src/main/java/me/wcy/mockhttp/MockHttpInterceptor.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import okhttp3.*
4 | import okio.Buffer
5 | import org.json.JSONArray
6 | import org.json.JSONException
7 | import org.json.JSONObject
8 | import java.io.IOException
9 | import java.util.concurrent.TimeUnit
10 |
11 | /**
12 | * Created by wcy on 2019/5/23.
13 | */
14 | class MockHttpInterceptor : Interceptor {
15 |
16 | override fun intercept(chain: Interceptor.Chain): Response {
17 | val request = chain.request()
18 |
19 | if (!MockHttp.get().hasStart()) {
20 | return chain.proceed(request)
21 | }
22 |
23 | val requestCopy = request.newBuilder().build()
24 |
25 | val path = requestCopy.url().encodedPath()
26 | val requestUrl = requestCopy.url().toString()
27 | val requestMethod = requestCopy.method()
28 | val requestHeader = requestCopy.headers().toString()
29 | val sb = StringBuilder()
30 | for (name in requestCopy.url().queryParameterNames()) {
31 | if (sb.isNotEmpty()) {
32 | sb.append("\n")
33 | }
34 | sb.append("$name: ${requestCopy.url().queryParameter(name)}")
35 | }
36 | val queryParameter = sb.toString()
37 |
38 | val requestBody = bodyToString(requestCopy.body())
39 |
40 | Logger.logRequest(requestUrl, requestMethod, requestHeader, queryParameter, requestBody)
41 |
42 | val response: Response
43 | val mockResponseBody = MockHttp.get().getMockResponseBody(path)
44 | if (mockResponseBody != null) {
45 | val options = MockHttp.get().getMockHttpOptions()!!
46 | try {
47 | TimeUnit.MILLISECONDS.sleep(options.getMockSleepTime())
48 | } catch (e: InterruptedException) {
49 | e.printStackTrace()
50 | }
51 |
52 | response = Response.Builder()
53 | .body(ResponseBody.create(MediaType.parse("application/json"), mockResponseBody))
54 | .request(chain.request())
55 | .protocol(Protocol.HTTP_2)
56 | .message("Mock")
57 | .code(200)
58 | .build()
59 | } else {
60 | response = chain.proceed(request)
61 | }
62 |
63 | val responseHeader = response.headers().toString()
64 | val statusCode = response.code()
65 | val isSuccessful = response.isSuccessful
66 | val message = response.message()
67 | val responseBody = response.body()
68 | val contentType = responseBody?.contentType()
69 | val subtype = contentType?.subtype()
70 |
71 | /**
72 | * 仅处理非文件类型
73 | */
74 | if (responseBody != null && isNotFileRequest(subtype)) {
75 | val responseBodyString = responseBody.string()
76 | val responseBodyStringFormat = formatJson(responseBodyString)
77 | val httpEntity = MockHttpEntity(path, requestUrl, requestMethod, statusCode, requestHeader,
78 | queryParameter, requestBody, responseHeader, responseBodyStringFormat)
79 | MockHttp.get().request(path, httpEntity)
80 |
81 | Logger.logResponse(requestUrl, statusCode, responseHeader, responseBodyStringFormat)
82 |
83 | val newResponseBody = ResponseBody.create(contentType, responseBodyString)
84 | return response.newBuilder().body(newResponseBody).build()
85 | } else {
86 | Logger.logResponse(requestUrl, statusCode, responseHeader, "response body is not text, can not mock")
87 | return response
88 | }
89 | }
90 |
91 | private fun isNotFileRequest(subtype: String?): Boolean {
92 | return subtype != null && (subtype.contains("json")
93 | || subtype.contains("xml")
94 | || subtype.contains("plain")
95 | || subtype.contains("html"))
96 | }
97 |
98 | private fun bodyToString(body: RequestBody?): String {
99 | try {
100 | val buffer = Buffer()
101 | body?.writeTo(buffer)
102 | return formatJson(buffer.readUtf8())
103 | } catch (e: IOException) {
104 | return "{\"err\": \"" + e.message + "\"}"
105 | }
106 |
107 | }
108 |
109 | private fun formatJson(json: String): String {
110 | var string: String
111 | try {
112 | if (json.startsWith("{")) {
113 | string = JSONObject(json).toString(2)
114 | } else if (json.startsWith("[")) {
115 | string = JSONArray(json).toString(2)
116 | } else {
117 | string = json
118 | }
119 | } catch (e: JSONException) {
120 | string = json
121 | } catch (e1: OutOfMemoryError) {
122 | string = "Output omitted because of Object size."
123 | }
124 |
125 | return string
126 | }
127 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/mock-http/src/main/java/me/wcy/mockhttp/MockHttp.kt:
--------------------------------------------------------------------------------
1 | package me.wcy.mockhttp
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.Context
5 | import android.content.SharedPreferences
6 | import android.net.wifi.WifiManager
7 | import android.util.Log
8 |
9 | /**
10 | * MOCK HTTP
11 | * Created by wcy on 2019/5/23.
12 | */
13 | class MockHttp private constructor() {
14 | private var context: Context? = null
15 | private var mockHttpServer: MockHttpServer? = null
16 | private var mockHttpOptions: MockHttpOptions? = null
17 | private var mockPreference: SharedPreferences? = null
18 | private var httpEntityMap: MutableMap? = null
19 | private var hasStart = false
20 |
21 | companion object {
22 | fun get(): MockHttp {
23 | return SingletonHolder.instance
24 | }
25 | }
26 |
27 | private object SingletonHolder {
28 | @SuppressLint("StaticFieldLeak")
29 | val instance = MockHttp()
30 | }
31 |
32 | /**
33 | * 获取 MOCK HTTP 配置项
34 | */
35 | fun getMockHttpOptions(): MockHttpOptions? {
36 | return mockHttpOptions
37 | }
38 |
39 | /**
40 | * 设置 MOCK HTTP 配置项
41 | * 需要在 [start] 之前调用,否则将使用默认配置
42 | *
43 | * @param options MOCK HTTP 配置项
44 | * @see MockHttpOptions
45 | */
46 | fun setMockHttpOptions(options: MockHttpOptions) {
47 | this.mockHttpOptions = options
48 | }
49 |
50 | /**
51 | * 启动 MOCK 服务,开始 MOCK
52 | * 如果是多进程应用,只需要在主进程中初始化
53 | *
54 | * @param ctx 上下文
55 | */
56 | fun start(ctx: Context) {
57 | if (hasStart()) {
58 | Log.w("MOCK-HTTP", "mock-http has start, stop it first")
59 | stop()
60 | }
61 |
62 | Log.d("MOCK-HTTP", "start")
63 |
64 | if (mockHttpOptions == null) {
65 | mockHttpOptions = MockHttpOptions.Builder().build()
66 | }
67 |
68 | context = ctx.applicationContext
69 | mockPreference = context!!.getSharedPreferences(context!!.packageName + ".com.github.wangchenyan.mock-http", Context.MODE_PRIVATE)
70 | httpEntityMap = mutableMapOf()
71 | mockHttpServer = MockHttpServer()
72 | mockHttpServer?.startServer(context!!)
73 |
74 | hasStart = true
75 | }
76 |
77 | /**
78 | * 停止 MOCK 服务,释放资源
79 | */
80 | fun stop() {
81 | Log.d("MOCK-HTTP", "stop")
82 |
83 | context = null
84 | mockPreference = null
85 | httpEntityMap?.clear()
86 | httpEntityMap = null
87 | mockHttpServer?.stopServer()
88 | mockHttpServer = null
89 |
90 | hasStart = false
91 | }
92 |
93 | /**
94 | * 是否已经启动
95 | */
96 | fun hasStart(): Boolean {
97 | return hasStart
98 | }
99 |
100 | /**
101 | * 获取 MOCK 服务器地址
102 | */
103 | fun getMockAddress(): String {
104 | val port = mockHttpOptions?.getMockServerPort() ?: 0
105 |
106 | val wifiManager = context!!.getSystemService(Context.WIFI_SERVICE) as WifiManager
107 | val ipAddress = wifiManager.connectionInfo.ipAddress
108 | val ip = (ipAddress and 0xFF).toString() + "." +
109 | (ipAddress shr 8 and 0xFF) + "." +
110 | (ipAddress shr 16 and 0xFF) + "." +
111 | (ipAddress shr 24 and 0xFF)
112 | return "$ip:${port}"
113 | }
114 |
115 | /**
116 | * 获取 MOCK 响应结果
117 | *
118 | * @param path 路径
119 | */
120 | internal fun getMockResponseBody(path: String): String? {
121 | checkStart()
122 |
123 | if (mockPreference!!.contains(path)) {
124 | val json = mockPreference!!.getString(path, null)
125 | val entity = MockHttpEntity.fromJson(json)
126 | return entity?.responseBody
127 | }
128 |
129 | return null
130 | }
131 |
132 | /**
133 | * 记录 HTTP 请求
134 | *
135 | * @param path 路径
136 | * @param entity 请求实体
137 | */
138 | internal fun request(path: String, entity: MockHttpEntity) {
139 | checkStart()
140 |
141 | httpEntityMap!![path] = entity
142 | }
143 |
144 | /**
145 | * 获取 HTTP 请求信息集合
146 | *
147 | * @param mock true: 已 MOCK 请求, false: 未 MOCK 请求
148 | */
149 | internal fun getRequestList(mock: Boolean): List {
150 | checkStart()
151 |
152 | val mockList = mockPreference!!.all.keys
153 | if (mock) {
154 | return mockList.toList()
155 | }
156 |
157 | val unmockList = mutableListOf()
158 | for (path in httpEntityMap!!.keys) {
159 | if (!mockList.contains(path)) {
160 | unmockList.add(path)
161 | }
162 | }
163 |
164 | return unmockList
165 | }
166 |
167 | /**
168 | * 获取 HTTP 请求信息
169 | *
170 | * @param path 路径
171 | */
172 | internal fun getRequest(path: String): MockHttpEntity? {
173 | checkStart()
174 |
175 | if (mockPreference!!.contains(path)) {
176 | return MockHttpEntity.fromJson(mockPreference!!.getString(path, null))
177 | } else {
178 | return httpEntityMap!![path]
179 | }
180 | }
181 |
182 | /**
183 | * MOCK HTTP 请求
184 | *
185 | * @param path 路径
186 | * @param responseBody 响应体
187 | */
188 | internal fun mock(path: String, responseBody: String) {
189 | checkStart()
190 |
191 | var entity: MockHttpEntity?
192 | if (httpEntityMap!!.containsKey(path)) {
193 | entity = httpEntityMap!![path]
194 | } else if (mockPreference!!.contains(path)) {
195 | entity = MockHttpEntity.fromJson(mockPreference!!.getString(path, null))
196 | } else {
197 | entity = MockHttpEntity(path)
198 | }
199 |
200 | if (entity == null) {
201 | entity = MockHttpEntity(path)
202 | }
203 |
204 | entity.responseBody = responseBody
205 | mockPreference!!.edit().putString(path, entity.toJson()).apply()
206 | }
207 |
208 | /**
209 | * 取消 MOCK HTTP 请求
210 | *
211 | * @param path 路径
212 | */
213 | internal fun unmock(path: String) {
214 | checkStart()
215 |
216 | mockPreference!!.edit().remove(path).apply()
217 | }
218 |
219 | /**
220 | * 检查是否初始化
221 | */
222 | private fun checkStart() {
223 | if (!hasStart()) {
224 | throw IllegalStateException("mock-http not start, please start first.")
225 | }
226 | }
227 | }
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/addon/lint/lint.js:
--------------------------------------------------------------------------------
1 | // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 | // Distributed under an MIT license: https://codemirror.net/LICENSE
3 |
4 | (function(mod) {
5 | if (typeof exports == "object" && typeof module == "object") // CommonJS
6 | mod(require("../../lib/codemirror"));
7 | else if (typeof define == "function" && define.amd) // AMD
8 | define(["../../lib/codemirror"], mod);
9 | else // Plain browser env
10 | mod(CodeMirror);
11 | })(function(CodeMirror) {
12 | "use strict";
13 | var GUTTER_ID = "CodeMirror-lint-markers";
14 |
15 | function showTooltip(e, content) {
16 | var tt = document.createElement("div");
17 | tt.className = "CodeMirror-lint-tooltip";
18 | tt.appendChild(content.cloneNode(true));
19 | document.body.appendChild(tt);
20 |
21 | function position(e) {
22 | if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
23 | tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
24 | tt.style.left = (e.clientX + 5) + "px";
25 | }
26 | CodeMirror.on(document, "mousemove", position);
27 | position(e);
28 | if (tt.style.opacity != null) tt.style.opacity = 1;
29 | return tt;
30 | }
31 | function rm(elt) {
32 | if (elt.parentNode) elt.parentNode.removeChild(elt);
33 | }
34 | function hideTooltip(tt) {
35 | if (!tt.parentNode) return;
36 | if (tt.style.opacity == null) rm(tt);
37 | tt.style.opacity = 0;
38 | setTimeout(function() { rm(tt); }, 600);
39 | }
40 |
41 | function showTooltipFor(e, content, node) {
42 | var tooltip = showTooltip(e, content);
43 | function hide() {
44 | CodeMirror.off(node, "mouseout", hide);
45 | if (tooltip) { hideTooltip(tooltip); tooltip = null; }
46 | }
47 | var poll = setInterval(function() {
48 | if (tooltip) for (var n = node;; n = n.parentNode) {
49 | if (n && n.nodeType == 11) n = n.host;
50 | if (n == document.body) return;
51 | if (!n) { hide(); break; }
52 | }
53 | if (!tooltip) return clearInterval(poll);
54 | }, 400);
55 | CodeMirror.on(node, "mouseout", hide);
56 | }
57 |
58 | function LintState(cm, options, hasGutter) {
59 | this.marked = [];
60 | this.options = options;
61 | this.timeout = null;
62 | this.hasGutter = hasGutter;
63 | this.onMouseOver = function(e) { onMouseOver(cm, e); };
64 | this.waitingFor = 0
65 | }
66 |
67 | function parseOptions(_cm, options) {
68 | if (options instanceof Function) return {getAnnotations: options};
69 | if (!options || options === true) options = {};
70 | return options;
71 | }
72 |
73 | function clearMarks(cm) {
74 | var state = cm.state.lint;
75 | if (state.hasGutter) cm.clearGutter(GUTTER_ID);
76 | for (var i = 0; i < state.marked.length; ++i)
77 | state.marked[i].clear();
78 | state.marked.length = 0;
79 | }
80 |
81 | function makeMarker(labels, severity, multiple, tooltips) {
82 | var marker = document.createElement("div"), inner = marker;
83 | marker.className = "CodeMirror-lint-marker-" + severity;
84 | if (multiple) {
85 | inner = marker.appendChild(document.createElement("div"));
86 | inner.className = "CodeMirror-lint-marker-multiple";
87 | }
88 |
89 | if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
90 | showTooltipFor(e, labels, inner);
91 | });
92 |
93 | return marker;
94 | }
95 |
96 | function getMaxSeverity(a, b) {
97 | if (a == "error") return a;
98 | else return b;
99 | }
100 |
101 | function groupByLine(annotations) {
102 | var lines = [];
103 | for (var i = 0; i < annotations.length; ++i) {
104 | var ann = annotations[i], line = ann.from.line;
105 | (lines[line] || (lines[line] = [])).push(ann);
106 | }
107 | return lines;
108 | }
109 |
110 | function annotationTooltip(ann) {
111 | var severity = ann.severity;
112 | if (!severity) severity = "error";
113 | var tip = document.createElement("div");
114 | tip.className = "CodeMirror-lint-message-" + severity;
115 | if (typeof ann.messageHTML != 'undefined') {
116 | tip.innerHTML = ann.messageHTML;
117 | } else {
118 | tip.appendChild(document.createTextNode(ann.message));
119 | }
120 | return tip;
121 | }
122 |
123 | function lintAsync(cm, getAnnotations, passOptions) {
124 | var state = cm.state.lint
125 | var id = ++state.waitingFor
126 | function abort() {
127 | id = -1
128 | cm.off("change", abort)
129 | }
130 | cm.on("change", abort)
131 | getAnnotations(cm.getValue(), function(annotations, arg2) {
132 | cm.off("change", abort)
133 | if (state.waitingFor != id) return
134 | if (arg2 && annotations instanceof CodeMirror) annotations = arg2
135 | cm.operation(function() {updateLinting(cm, annotations)})
136 | }, passOptions, cm);
137 | }
138 |
139 | function startLinting(cm) {
140 | var state = cm.state.lint, options = state.options;
141 | /*
142 | * Passing rules in `options` property prevents JSHint (and other linters) from complaining
143 | * about unrecognized rules like `onUpdateLinting`, `delay`, `lintOnChange`, etc.
144 | */
145 | var passOptions = options.options || options;
146 | var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint");
147 | if (!getAnnotations) return;
148 | if (options.async || getAnnotations.async) {
149 | lintAsync(cm, getAnnotations, passOptions)
150 | } else {
151 | var annotations = getAnnotations(cm.getValue(), passOptions, cm);
152 | if (!annotations) return;
153 | if (annotations.then) annotations.then(function(issues) {
154 | cm.operation(function() {updateLinting(cm, issues)})
155 | });
156 | else cm.operation(function() {updateLinting(cm, annotations)})
157 | }
158 | }
159 |
160 | function updateLinting(cm, annotationsNotSorted) {
161 | clearMarks(cm);
162 | var state = cm.state.lint, options = state.options;
163 |
164 | var annotations = groupByLine(annotationsNotSorted);
165 |
166 | for (var line = 0; line < annotations.length; ++line) {
167 | var anns = annotations[line];
168 | if (!anns) continue;
169 |
170 | var maxSeverity = null;
171 | var tipLabel = state.hasGutter && document.createDocumentFragment();
172 |
173 | for (var i = 0; i < anns.length; ++i) {
174 | var ann = anns[i];
175 | var severity = ann.severity;
176 | if (!severity) severity = "error";
177 | maxSeverity = getMaxSeverity(maxSeverity, severity);
178 |
179 | if (options.formatAnnotation) ann = options.formatAnnotation(ann);
180 | if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
181 |
182 | if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
183 | className: "CodeMirror-lint-mark-" + severity,
184 | __annotation: ann
185 | }));
186 | }
187 |
188 | if (state.hasGutter)
189 | cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
190 | state.options.tooltips));
191 | }
192 | if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
193 | }
194 |
195 | function onChange(cm) {
196 | var state = cm.state.lint;
197 | if (!state) return;
198 | clearTimeout(state.timeout);
199 | state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
200 | }
201 |
202 | function popupTooltips(annotations, e) {
203 | var target = e.target || e.srcElement;
204 | var tooltip = document.createDocumentFragment();
205 | for (var i = 0; i < annotations.length; i++) {
206 | var ann = annotations[i];
207 | tooltip.appendChild(annotationTooltip(ann));
208 | }
209 | showTooltipFor(e, tooltip, target);
210 | }
211 |
212 | function onMouseOver(cm, e) {
213 | var target = e.target || e.srcElement;
214 | if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
215 | var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
216 | var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
217 |
218 | var annotations = [];
219 | for (var i = 0; i < spans.length; ++i) {
220 | var ann = spans[i].__annotation;
221 | if (ann) annotations.push(ann);
222 | }
223 | if (annotations.length) popupTooltips(annotations, e);
224 | }
225 |
226 | CodeMirror.defineOption("lint", false, function(cm, val, old) {
227 | if (old && old != CodeMirror.Init) {
228 | clearMarks(cm);
229 | if (cm.state.lint.options.lintOnChange !== false)
230 | cm.off("change", onChange);
231 | CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
232 | clearTimeout(cm.state.lint.timeout);
233 | delete cm.state.lint;
234 | }
235 |
236 | if (val) {
237 | var gutters = cm.getOption("gutters"), hasLintGutter = false;
238 | for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
239 | var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
240 | if (state.options.lintOnChange !== false)
241 | cm.on("change", onChange);
242 | if (state.options.tooltips != false && state.options.tooltips != "gutter")
243 | CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
244 |
245 | startLinting(cm);
246 | }
247 | });
248 |
249 | CodeMirror.defineExtension("performLint", function() {
250 | if (this.state.lint) startLinting(this);
251 | });
252 | });
253 |
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/lib/codemirror.css:
--------------------------------------------------------------------------------
1 | /* BASICS */
2 |
3 | .CodeMirror {
4 | /* Set height, width, borders, and global font properties here */
5 | font-family: monospace;
6 | height: 300px;
7 | color: black;
8 | direction: ltr;
9 | }
10 |
11 | /* PADDING */
12 |
13 | .CodeMirror-lines {
14 | padding: 4px 0; /* Vertical padding around content */
15 | }
16 | .CodeMirror pre.CodeMirror-line,
17 | .CodeMirror pre.CodeMirror-line-like {
18 | padding: 0 4px; /* Horizontal padding of content */
19 | }
20 |
21 | .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
22 | background-color: white; /* The little square between H and V scrollbars */
23 | }
24 |
25 | /* GUTTER */
26 |
27 | .CodeMirror-gutters {
28 | border-right: 1px solid #ddd;
29 | background-color: #f7f7f7;
30 | white-space: nowrap;
31 | }
32 | .CodeMirror-linenumbers {}
33 | .CodeMirror-linenumber {
34 | padding: 0 3px 0 5px;
35 | min-width: 20px;
36 | text-align: right;
37 | color: #999;
38 | white-space: nowrap;
39 | }
40 |
41 | .CodeMirror-guttermarker { color: black; }
42 | .CodeMirror-guttermarker-subtle { color: #999; }
43 |
44 | /* CURSOR */
45 |
46 | .CodeMirror-cursor {
47 | border-left: 1px solid black;
48 | border-right: none;
49 | width: 0;
50 | }
51 | /* Shown when moving in bi-directional text */
52 | .CodeMirror div.CodeMirror-secondarycursor {
53 | border-left: 1px solid silver;
54 | }
55 | .cm-fat-cursor .CodeMirror-cursor {
56 | width: auto;
57 | border: 0 !important;
58 | background: #7e7;
59 | }
60 | .cm-fat-cursor div.CodeMirror-cursors {
61 | z-index: 1;
62 | }
63 | .cm-fat-cursor-mark {
64 | background-color: rgba(20, 255, 20, 0.5);
65 | -webkit-animation: blink 1.06s steps(1) infinite;
66 | -moz-animation: blink 1.06s steps(1) infinite;
67 | animation: blink 1.06s steps(1) infinite;
68 | }
69 | .cm-animate-fat-cursor {
70 | width: auto;
71 | border: 0;
72 | -webkit-animation: blink 1.06s steps(1) infinite;
73 | -moz-animation: blink 1.06s steps(1) infinite;
74 | animation: blink 1.06s steps(1) infinite;
75 | background-color: #7e7;
76 | }
77 | @-moz-keyframes blink {
78 | 0% {}
79 | 50% { background-color: transparent; }
80 | 100% {}
81 | }
82 | @-webkit-keyframes blink {
83 | 0% {}
84 | 50% { background-color: transparent; }
85 | 100% {}
86 | }
87 | @keyframes blink {
88 | 0% {}
89 | 50% { background-color: transparent; }
90 | 100% {}
91 | }
92 |
93 | /* Can style cursor different in overwrite (non-insert) mode */
94 | .CodeMirror-overwrite .CodeMirror-cursor {}
95 |
96 | .cm-tab { display: inline-block; text-decoration: inherit; }
97 |
98 | .CodeMirror-rulers {
99 | position: absolute;
100 | left: 0; right: 0; top: -50px; bottom: 0;
101 | overflow: hidden;
102 | }
103 | .CodeMirror-ruler {
104 | border-left: 1px solid #ccc;
105 | top: 0; bottom: 0;
106 | position: absolute;
107 | }
108 |
109 | /* DEFAULT THEME */
110 |
111 | .cm-s-default .cm-header {color: blue;}
112 | .cm-s-default .cm-quote {color: #090;}
113 | .cm-negative {color: #d44;}
114 | .cm-positive {color: #292;}
115 | .cm-header, .cm-strong {font-weight: bold;}
116 | .cm-em {font-style: italic;}
117 | .cm-link {text-decoration: underline;}
118 | .cm-strikethrough {text-decoration: line-through;}
119 |
120 | .cm-s-default .cm-keyword {color: #708;}
121 | .cm-s-default .cm-atom {color: #219;}
122 | .cm-s-default .cm-number {color: #164;}
123 | .cm-s-default .cm-def {color: #00f;}
124 | .cm-s-default .cm-variable,
125 | .cm-s-default .cm-punctuation,
126 | .cm-s-default .cm-property,
127 | .cm-s-default .cm-operator {}
128 | .cm-s-default .cm-variable-2 {color: #05a;}
129 | .cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}
130 | .cm-s-default .cm-comment {color: #a50;}
131 | .cm-s-default .cm-string {color: #a11;}
132 | .cm-s-default .cm-string-2 {color: #f50;}
133 | .cm-s-default .cm-meta {color: #555;}
134 | .cm-s-default .cm-qualifier {color: #555;}
135 | .cm-s-default .cm-builtin {color: #30a;}
136 | .cm-s-default .cm-bracket {color: #997;}
137 | .cm-s-default .cm-tag {color: #170;}
138 | .cm-s-default .cm-attribute {color: #00c;}
139 | .cm-s-default .cm-hr {color: #999;}
140 | .cm-s-default .cm-link {color: #00c;}
141 |
142 | .cm-s-default .cm-error {color: #f00;}
143 | .cm-invalidchar {color: #f00;}
144 |
145 | .CodeMirror-composing { border-bottom: 2px solid; }
146 |
147 | /* Default styles for common addons */
148 |
149 | div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
150 | div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
151 | .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
152 | .CodeMirror-activeline-background {background: #e8f2ff;}
153 |
154 | /* STOP */
155 |
156 | /* The rest of this file contains styles related to the mechanics of
157 | the editor. You probably shouldn't touch them. */
158 |
159 | .CodeMirror {
160 | position: relative;
161 | overflow: hidden;
162 | background: white;
163 | }
164 |
165 | .CodeMirror-scroll {
166 | overflow: scroll !important; /* Things will break if this is overridden */
167 | /* 30px is the magic margin used to hide the element's real scrollbars */
168 | /* See overflow: hidden in .CodeMirror */
169 | margin-bottom: -30px; margin-right: -30px;
170 | padding-bottom: 30px;
171 | height: 100%;
172 | outline: none; /* Prevent dragging from highlighting the element */
173 | position: relative;
174 | }
175 | .CodeMirror-sizer {
176 | position: relative;
177 | border-right: 30px solid transparent;
178 | }
179 |
180 | /* The fake, visible scrollbars. Used to force redraw during scrolling
181 | before actual scrolling happens, thus preventing shaking and
182 | flickering artifacts. */
183 | .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
184 | position: absolute;
185 | z-index: 6;
186 | display: none;
187 | }
188 | .CodeMirror-vscrollbar {
189 | right: 0; top: 0;
190 | overflow-x: hidden;
191 | overflow-y: scroll;
192 | }
193 | .CodeMirror-hscrollbar {
194 | bottom: 0; left: 0;
195 | overflow-y: hidden;
196 | overflow-x: scroll;
197 | }
198 | .CodeMirror-scrollbar-filler {
199 | right: 0; bottom: 0;
200 | }
201 | .CodeMirror-gutter-filler {
202 | left: 0; bottom: 0;
203 | }
204 |
205 | .CodeMirror-gutters {
206 | position: absolute; left: 0; top: 0;
207 | min-height: 100%;
208 | z-index: 3;
209 | }
210 | .CodeMirror-gutter {
211 | white-space: normal;
212 | height: 100%;
213 | display: inline-block;
214 | vertical-align: top;
215 | margin-bottom: -30px;
216 | }
217 | .CodeMirror-gutter-wrapper {
218 | position: absolute;
219 | z-index: 4;
220 | background: none !important;
221 | border: none !important;
222 | }
223 | .CodeMirror-gutter-background {
224 | position: absolute;
225 | top: 0; bottom: 0;
226 | z-index: 4;
227 | }
228 | .CodeMirror-gutter-elt {
229 | position: absolute;
230 | cursor: default;
231 | z-index: 4;
232 | }
233 | .CodeMirror-gutter-wrapper ::selection { background-color: transparent }
234 | .CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }
235 |
236 | .CodeMirror-lines {
237 | cursor: text;
238 | min-height: 1px; /* prevents collapsing before first draw */
239 | }
240 | .CodeMirror pre.CodeMirror-line,
241 | .CodeMirror pre.CodeMirror-line-like {
242 | /* Reset some styles that the rest of the page might have set */
243 | -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
244 | border-width: 0;
245 | background: transparent;
246 | font-family: inherit;
247 | font-size: inherit;
248 | margin: 0;
249 | white-space: pre;
250 | word-wrap: normal;
251 | line-height: inherit;
252 | color: inherit;
253 | z-index: 2;
254 | position: relative;
255 | overflow: visible;
256 | -webkit-tap-highlight-color: transparent;
257 | -webkit-font-variant-ligatures: contextual;
258 | font-variant-ligatures: contextual;
259 | }
260 | .CodeMirror-wrap pre.CodeMirror-line,
261 | .CodeMirror-wrap pre.CodeMirror-line-like {
262 | word-wrap: break-word;
263 | white-space: pre-wrap;
264 | word-break: normal;
265 | }
266 |
267 | .CodeMirror-linebackground {
268 | position: absolute;
269 | left: 0; right: 0; top: 0; bottom: 0;
270 | z-index: 0;
271 | }
272 |
273 | .CodeMirror-linewidget {
274 | position: relative;
275 | z-index: 2;
276 | padding: 0.1px; /* Force widget margins to stay inside of the container */
277 | }
278 |
279 | .CodeMirror-widget {}
280 |
281 | .CodeMirror-rtl pre { direction: rtl; }
282 |
283 | .CodeMirror-code {
284 | outline: none;
285 | }
286 |
287 | /* Force content-box sizing for the elements where we expect it */
288 | .CodeMirror-scroll,
289 | .CodeMirror-sizer,
290 | .CodeMirror-gutter,
291 | .CodeMirror-gutters,
292 | .CodeMirror-linenumber {
293 | -moz-box-sizing: content-box;
294 | box-sizing: content-box;
295 | }
296 |
297 | .CodeMirror-measure {
298 | position: absolute;
299 | width: 100%;
300 | height: 0;
301 | overflow: hidden;
302 | visibility: hidden;
303 | }
304 |
305 | .CodeMirror-cursor {
306 | position: absolute;
307 | pointer-events: none;
308 | }
309 | .CodeMirror-measure pre { position: static; }
310 |
311 | div.CodeMirror-cursors {
312 | visibility: hidden;
313 | position: relative;
314 | z-index: 3;
315 | }
316 | div.CodeMirror-dragcursors {
317 | visibility: visible;
318 | }
319 |
320 | .CodeMirror-focused div.CodeMirror-cursors {
321 | visibility: visible;
322 | }
323 |
324 | .CodeMirror-selected { background: #d9d9d9; }
325 | .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
326 | .CodeMirror-crosshair { cursor: crosshair; }
327 | .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
328 | .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
329 |
330 | .cm-searching {
331 | background-color: #ffa;
332 | background-color: rgba(255, 255, 0, .4);
333 | }
334 |
335 | /* Used to force a border model for a node */
336 | .cm-force-border { padding-right: .1px; }
337 |
338 | @media print {
339 | /* Hide the cursor when printing */
340 | .CodeMirror div.CodeMirror-cursors {
341 | visibility: hidden;
342 | }
343 | }
344 |
345 | /* See issue #2901 */
346 | .cm-tab-wrap-hack:after { content: ''; }
347 |
348 | /* Help users use markselection to safely style text background */
349 | span.CodeMirror-selectedtext { background: none; }
350 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | MOCK HTTP
6 |
7 |
70 |
71 |
72 |
73 |
76 |
77 |
80 |
81 |
82 |
MOCK HTTP 请求
83 |
84 |
真实 HTTP 请求
85 |
86 |
87 |
88 |
89 |
148 |
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/request.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | MOCK HTTP
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
117 |
118 |
119 |
120 |
123 |
124 |
127 |
128 |
148 |
149 |
150 |
211 |
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/lib/jsonlint.js:
--------------------------------------------------------------------------------
1 | /* Jison generated parser */
2 | var jsonlint = (function(){
3 | var parser = {trace: function trace() { },
4 | yy: {},
5 | symbols_: {"error":2,"JSONString":3,"STRING":4,"JSONNumber":5,"NUMBER":6,"JSONNullLiteral":7,"NULL":8,"JSONBooleanLiteral":9,"TRUE":10,"FALSE":11,"JSONText":12,"JSONValue":13,"EOF":14,"JSONObject":15,"JSONArray":16,"{":17,"}":18,"JSONMemberList":19,"JSONMember":20,":":21,",":22,"[":23,"]":24,"JSONElementList":25,"$accept":0,"$end":1},
6 | terminals_: {2:"error",4:"STRING",6:"NUMBER",8:"NULL",10:"TRUE",11:"FALSE",14:"EOF",17:"{",18:"}",21:":",22:",",23:"[",24:"]"},
7 | productions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]],
8 | performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
9 |
10 | var $0 = $$.length - 1;
11 | switch (yystate) {
12 | case 1: // replace escaped characters with actual character
13 | this.$ = yytext.replace(/\\(\\|")/g, "$"+"1")
14 | .replace(/\\n/g,'\n')
15 | .replace(/\\r/g,'\r')
16 | .replace(/\\t/g,'\t')
17 | .replace(/\\v/g,'\v')
18 | .replace(/\\f/g,'\f')
19 | .replace(/\\b/g,'\b');
20 |
21 | break;
22 | case 2:this.$ = Number(yytext);
23 | break;
24 | case 3:this.$ = null;
25 | break;
26 | case 4:this.$ = true;
27 | break;
28 | case 5:this.$ = false;
29 | break;
30 | case 6:return this.$ = $$[$0-1];
31 | break;
32 | case 13:this.$ = {};
33 | break;
34 | case 14:this.$ = $$[$0-1];
35 | break;
36 | case 15:this.$ = [$$[$0-2], $$[$0]];
37 | break;
38 | case 16:this.$ = {}; this.$[$$[$0][0]] = $$[$0][1];
39 | break;
40 | case 17:this.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1];
41 | break;
42 | case 18:this.$ = [];
43 | break;
44 | case 19:this.$ = $$[$0-1];
45 | break;
46 | case 20:this.$ = [$$[$0]];
47 | break;
48 | case 21:this.$ = $$[$0-2]; $$[$0-2].push($$[$0]);
49 | break;
50 | }
51 | },
52 | table: [{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],12:1,13:2,15:7,16:8,17:[1,14],23:[1,15]},{1:[3]},{14:[1,16]},{14:[2,7],18:[2,7],22:[2,7],24:[2,7]},{14:[2,8],18:[2,8],22:[2,8],24:[2,8]},{14:[2,9],18:[2,9],22:[2,9],24:[2,9]},{14:[2,10],18:[2,10],22:[2,10],24:[2,10]},{14:[2,11],18:[2,11],22:[2,11],24:[2,11]},{14:[2,12],18:[2,12],22:[2,12],24:[2,12]},{14:[2,3],18:[2,3],22:[2,3],24:[2,3]},{14:[2,4],18:[2,4],22:[2,4],24:[2,4]},{14:[2,5],18:[2,5],22:[2,5],24:[2,5]},{14:[2,1],18:[2,1],21:[2,1],22:[2,1],24:[2,1]},{14:[2,2],18:[2,2],22:[2,2],24:[2,2]},{3:20,4:[1,12],18:[1,17],19:18,20:19},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:23,15:7,16:8,17:[1,14],23:[1,15],24:[1,21],25:22},{1:[2,6]},{14:[2,13],18:[2,13],22:[2,13],24:[2,13]},{18:[1,24],22:[1,25]},{18:[2,16],22:[2,16]},{21:[1,26]},{14:[2,18],18:[2,18],22:[2,18],24:[2,18]},{22:[1,28],24:[1,27]},{22:[2,20],24:[2,20]},{14:[2,14],18:[2,14],22:[2,14],24:[2,14]},{3:20,4:[1,12],20:29},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:30,15:7,16:8,17:[1,14],23:[1,15]},{14:[2,19],18:[2,19],22:[2,19],24:[2,19]},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:31,15:7,16:8,17:[1,14],23:[1,15]},{18:[2,17],22:[2,17]},{18:[2,15],22:[2,15]},{22:[2,21],24:[2,21]}],
53 | defaultActions: {16:[2,6]},
54 | parseError: function parseError(str, hash) {
55 | throw new Error(str);
56 | },
57 | parse: function parse(input) {
58 | var self = this,
59 | stack = [0],
60 | vstack = [null], // semantic value stack
61 | lstack = [], // location stack
62 | table = this.table,
63 | yytext = '',
64 | yylineno = 0,
65 | yyleng = 0,
66 | recovering = 0,
67 | TERROR = 2,
68 | EOF = 1;
69 |
70 | //this.reductionCount = this.shiftCount = 0;
71 |
72 | this.lexer.setInput(input);
73 | this.lexer.yy = this.yy;
74 | this.yy.lexer = this.lexer;
75 | if (typeof this.lexer.yylloc == 'undefined')
76 | this.lexer.yylloc = {};
77 | var yyloc = this.lexer.yylloc;
78 | lstack.push(yyloc);
79 |
80 | if (typeof this.yy.parseError === 'function')
81 | this.parseError = this.yy.parseError;
82 |
83 | function popStack (n) {
84 | stack.length = stack.length - 2*n;
85 | vstack.length = vstack.length - n;
86 | lstack.length = lstack.length - n;
87 | }
88 |
89 | function lex() {
90 | var token;
91 | token = self.lexer.lex() || 1; // $end = 1
92 | // if token isn't its numeric value, convert
93 | if (typeof token !== 'number') {
94 | token = self.symbols_[token] || token;
95 | }
96 | return token;
97 | }
98 |
99 | var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected;
100 | while (true) {
101 | // retreive state number from top of stack
102 | state = stack[stack.length-1];
103 |
104 | // use default actions if available
105 | if (this.defaultActions[state]) {
106 | action = this.defaultActions[state];
107 | } else {
108 | if (symbol == null)
109 | symbol = lex();
110 | // read action for current state and first input
111 | action = table[state] && table[state][symbol];
112 | }
113 |
114 | // handle parse error
115 | _handle_error:
116 | if (typeof action === 'undefined' || !action.length || !action[0]) {
117 |
118 | if (!recovering) {
119 | // Report error
120 | expected = [];
121 | for (p in table[state]) if (this.terminals_[p] && p > 2) {
122 | expected.push("'"+this.terminals_[p]+"'");
123 | }
124 | var errStr = '';
125 | if (this.lexer.showPosition) {
126 | errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + this.terminals_[symbol]+ "'";
127 | } else {
128 | errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
129 | (symbol == 1 /*EOF*/ ? "end of input" :
130 | ("'"+(this.terminals_[symbol] || symbol)+"'"));
131 | }
132 | this.parseError(errStr,
133 | {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
134 | }
135 |
136 | // just recovered from another error
137 | if (recovering == 3) {
138 | if (symbol == EOF) {
139 | throw new Error(errStr || 'Parsing halted.');
140 | }
141 |
142 | // discard current lookahead and grab another
143 | yyleng = this.lexer.yyleng;
144 | yytext = this.lexer.yytext;
145 | yylineno = this.lexer.yylineno;
146 | yyloc = this.lexer.yylloc;
147 | symbol = lex();
148 | }
149 |
150 | // try to recover from error
151 | while (1) {
152 | // check for error recovery rule in this state
153 | if ((TERROR.toString()) in table[state]) {
154 | break;
155 | }
156 | if (state == 0) {
157 | throw new Error(errStr || 'Parsing halted.');
158 | }
159 | popStack(1);
160 | state = stack[stack.length-1];
161 | }
162 |
163 | preErrorSymbol = symbol; // save the lookahead token
164 | symbol = TERROR; // insert generic error symbol as new lookahead
165 | state = stack[stack.length-1];
166 | action = table[state] && table[state][TERROR];
167 | recovering = 3; // allow 3 real symbols to be shifted before reporting a new error
168 | }
169 |
170 | // this shouldn't happen, unless resolve defaults are off
171 | if (action[0] instanceof Array && action.length > 1) {
172 | throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);
173 | }
174 |
175 | switch (action[0]) {
176 |
177 | case 1: // shift
178 | //this.shiftCount++;
179 |
180 | stack.push(symbol);
181 | vstack.push(this.lexer.yytext);
182 | lstack.push(this.lexer.yylloc);
183 | stack.push(action[1]); // push state
184 | symbol = null;
185 | if (!preErrorSymbol) { // normal execution/no error
186 | yyleng = this.lexer.yyleng;
187 | yytext = this.lexer.yytext;
188 | yylineno = this.lexer.yylineno;
189 | yyloc = this.lexer.yylloc;
190 | if (recovering > 0)
191 | recovering--;
192 | } else { // error just occurred, resume old lookahead f/ before error
193 | symbol = preErrorSymbol;
194 | preErrorSymbol = null;
195 | }
196 | break;
197 |
198 | case 2: // reduce
199 | //this.reductionCount++;
200 |
201 | len = this.productions_[action[1]][1];
202 |
203 | // perform semantic action
204 | yyval.$ = vstack[vstack.length-len]; // default to $$ = $1
205 | // default location, uses first token for firsts, last for lasts
206 | yyval._$ = {
207 | first_line: lstack[lstack.length-(len||1)].first_line,
208 | last_line: lstack[lstack.length-1].last_line,
209 | first_column: lstack[lstack.length-(len||1)].first_column,
210 | last_column: lstack[lstack.length-1].last_column
211 | };
212 | r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
213 |
214 | if (typeof r !== 'undefined') {
215 | return r;
216 | }
217 |
218 | // pop off stack
219 | if (len) {
220 | stack = stack.slice(0,-1*len*2);
221 | vstack = vstack.slice(0, -1*len);
222 | lstack = lstack.slice(0, -1*len);
223 | }
224 |
225 | stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce)
226 | vstack.push(yyval.$);
227 | lstack.push(yyval._$);
228 | // goto new state = table[STATE][NONTERMINAL]
229 | newState = table[stack[stack.length-2]][stack[stack.length-1]];
230 | stack.push(newState);
231 | break;
232 |
233 | case 3: // accept
234 | return true;
235 | }
236 |
237 | }
238 |
239 | return true;
240 | }};
241 | /* Jison generated lexer */
242 | var lexer = (function(){
243 | var lexer = ({EOF:1,
244 | parseError:function parseError(str, hash) {
245 | if (this.yy.parseError) {
246 | this.yy.parseError(str, hash);
247 | } else {
248 | throw new Error(str);
249 | }
250 | },
251 | setInput:function (input) {
252 | this._input = input;
253 | this._more = this._less = this.done = false;
254 | this.yylineno = this.yyleng = 0;
255 | this.yytext = this.matched = this.match = '';
256 | this.conditionStack = ['INITIAL'];
257 | this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};
258 | return this;
259 | },
260 | input:function () {
261 | var ch = this._input[0];
262 | this.yytext+=ch;
263 | this.yyleng++;
264 | this.match+=ch;
265 | this.matched+=ch;
266 | var lines = ch.match(/\n/);
267 | if (lines) this.yylineno++;
268 | this._input = this._input.slice(1);
269 | return ch;
270 | },
271 | unput:function (ch) {
272 | this._input = ch + this._input;
273 | return this;
274 | },
275 | more:function () {
276 | this._more = true;
277 | return this;
278 | },
279 | less:function (n) {
280 | this._input = this.match.slice(n) + this._input;
281 | },
282 | pastInput:function () {
283 | var past = this.matched.substr(0, this.matched.length - this.match.length);
284 | return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
285 | },
286 | upcomingInput:function () {
287 | var next = this.match;
288 | if (next.length < 20) {
289 | next += this._input.substr(0, 20-next.length);
290 | }
291 | return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, "");
292 | },
293 | showPosition:function () {
294 | var pre = this.pastInput();
295 | var c = new Array(pre.length + 1).join("-");
296 | return pre + this.upcomingInput() + "\n" + c+"^";
297 | },
298 | next:function () {
299 | if (this.done) {
300 | return this.EOF;
301 | }
302 | if (!this._input) this.done = true;
303 |
304 | var token,
305 | match,
306 | tempMatch,
307 | index,
308 | col,
309 | lines;
310 | if (!this._more) {
311 | this.yytext = '';
312 | this.match = '';
313 | }
314 | var rules = this._currentRules();
315 | for (var i=0;i < rules.length; i++) {
316 | tempMatch = this._input.match(this.rules[rules[i]]);
317 | if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
318 | match = tempMatch;
319 | index = i;
320 | if (!this.options.flex) break;
321 | }
322 | }
323 | if (match) {
324 | lines = match[0].match(/\n.*/g);
325 | if (lines) this.yylineno += lines.length;
326 | this.yylloc = {first_line: this.yylloc.last_line,
327 | last_line: this.yylineno+1,
328 | first_column: this.yylloc.last_column,
329 | last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length}
330 | this.yytext += match[0];
331 | this.match += match[0];
332 | this.yyleng = this.yytext.length;
333 | this._more = false;
334 | this._input = this._input.slice(match[0].length);
335 | this.matched += match[0];
336 | token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]);
337 | if (this.done && this._input) this.done = false;
338 | if (token) return token;
339 | else return;
340 | }
341 | if (this._input === "") {
342 | return this.EOF;
343 | } else {
344 | this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),
345 | {text: "", token: null, line: this.yylineno});
346 | }
347 | },
348 | lex:function lex() {
349 | var r = this.next();
350 | if (typeof r !== 'undefined') {
351 | return r;
352 | } else {
353 | return this.lex();
354 | }
355 | },
356 | begin:function begin(condition) {
357 | this.conditionStack.push(condition);
358 | },
359 | popState:function popState() {
360 | return this.conditionStack.pop();
361 | },
362 | _currentRules:function _currentRules() {
363 | return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
364 | },
365 | topState:function () {
366 | return this.conditionStack[this.conditionStack.length-2];
367 | },
368 | pushState:function begin(condition) {
369 | this.begin(condition);
370 | }});
371 | lexer.options = {};
372 | lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
373 |
374 | var YYSTATE=YY_START
375 | switch($avoiding_name_collisions) {
376 | case 0:/* skip whitespace */
377 | break;
378 | case 1:return 6
379 | break;
380 | case 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4
381 | break;
382 | case 3:return 17
383 | break;
384 | case 4:return 18
385 | break;
386 | case 5:return 23
387 | break;
388 | case 6:return 24
389 | break;
390 | case 7:return 22
391 | break;
392 | case 8:return 21
393 | break;
394 | case 9:return 10
395 | break;
396 | case 10:return 11
397 | break;
398 | case 11:return 8
399 | break;
400 | case 12:return 14
401 | break;
402 | case 13:return 'INVALID'
403 | break;
404 | }
405 | };
406 | lexer.rules = [/^(?:\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\.[0-9]+)?([eE][-+]?[0-9]+)?\b)/,/^(?:"(?:\\[\\"bfnrt/]|\\u[a-fA-F0-9]{4}|[^\\\0-\x09\x0a-\x1f"])*")/,/^(?:\{)/,/^(?:\})/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?::)/,/^(?:true\b)/,/^(?:false\b)/,/^(?:null\b)/,/^(?:$)/,/^(?:.)/];
407 | lexer.conditions = {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}};
408 |
409 |
410 | ;
411 | return lexer;})()
412 | parser.lexer = lexer;
413 | return parser;
414 | })();
415 | if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
416 | exports.parser = jsonlint;
417 | exports.parse = function () { return jsonlint.parse.apply(jsonlint, arguments); }
418 | exports.main = function commonjsMain(args) {
419 | if (!args[1])
420 | throw new Error('Usage: '+args[0]+' FILE');
421 | if (typeof process !== 'undefined') {
422 | var source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8");
423 | } else {
424 | var cwd = require("file").path(require("file").cwd());
425 | var source = cwd.join(args[1]).read({charset: "utf-8"});
426 | }
427 | return exports.parser.parse(source);
428 | }
429 | if (typeof module !== 'undefined' && require.main === module) {
430 | exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require("system").args);
431 | }
432 | }
--------------------------------------------------------------------------------
/mock-http/src/main/assets/mock-http/mode/javascript/javascript.js:
--------------------------------------------------------------------------------
1 | // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 | // Distributed under an MIT license: https://codemirror.net/LICENSE
3 |
4 | (function(mod) {
5 | if (typeof exports == "object" && typeof module == "object") // CommonJS
6 | mod(require("../../lib/codemirror"));
7 | else if (typeof define == "function" && define.amd) // AMD
8 | define(["../../lib/codemirror"], mod);
9 | else // Plain browser env
10 | mod(CodeMirror);
11 | })(function(CodeMirror) {
12 | "use strict";
13 |
14 | CodeMirror.defineMode("javascript", function(config, parserConfig) {
15 | var indentUnit = config.indentUnit;
16 | var statementIndent = parserConfig.statementIndent;
17 | var jsonldMode = parserConfig.jsonld;
18 | var jsonMode = parserConfig.json || jsonldMode;
19 | var isTS = parserConfig.typescript;
20 | var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
21 |
22 | // Tokenizer
23 |
24 | var keywords = function(){
25 | function kw(type) {return {type: type, style: "keyword"};}
26 | var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
27 | var operator = kw("operator"), atom = {type: "atom", style: "atom"};
28 |
29 | return {
30 | "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
31 | "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
32 | "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
33 | "function": kw("function"), "catch": kw("catch"),
34 | "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
35 | "in": operator, "typeof": operator, "instanceof": operator,
36 | "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
37 | "this": kw("this"), "class": kw("class"), "super": kw("atom"),
38 | "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
39 | "await": C
40 | };
41 | }();
42 |
43 | var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
44 | var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
45 |
46 | function readRegexp(stream) {
47 | var escaped = false, next, inSet = false;
48 | while ((next = stream.next()) != null) {
49 | if (!escaped) {
50 | if (next == "/" && !inSet) return;
51 | if (next == "[") inSet = true;
52 | else if (inSet && next == "]") inSet = false;
53 | }
54 | escaped = !escaped && next == "\\";
55 | }
56 | }
57 |
58 | // Used as scratch variables to communicate multiple values without
59 | // consing up tons of objects.
60 | var type, content;
61 | function ret(tp, style, cont) {
62 | type = tp; content = cont;
63 | return style;
64 | }
65 | function tokenBase(stream, state) {
66 | var ch = stream.next();
67 | if (ch == '"' || ch == "'") {
68 | state.tokenize = tokenString(ch);
69 | return state.tokenize(stream, state);
70 | } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
71 | return ret("number", "number");
72 | } else if (ch == "." && stream.match("..")) {
73 | return ret("spread", "meta");
74 | } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
75 | return ret(ch);
76 | } else if (ch == "=" && stream.eat(">")) {
77 | return ret("=>", "operator");
78 | } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
79 | return ret("number", "number");
80 | } else if (/\d/.test(ch)) {
81 | stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
82 | return ret("number", "number");
83 | } else if (ch == "/") {
84 | if (stream.eat("*")) {
85 | state.tokenize = tokenComment;
86 | return tokenComment(stream, state);
87 | } else if (stream.eat("/")) {
88 | stream.skipToEnd();
89 | return ret("comment", "comment");
90 | } else if (expressionAllowed(stream, state, 1)) {
91 | readRegexp(stream);
92 | stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
93 | return ret("regexp", "string-2");
94 | } else {
95 | stream.eat("=");
96 | return ret("operator", "operator", stream.current());
97 | }
98 | } else if (ch == "`") {
99 | state.tokenize = tokenQuasi;
100 | return tokenQuasi(stream, state);
101 | } else if (ch == "#") {
102 | stream.skipToEnd();
103 | return ret("error", "error");
104 | } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->")) {
105 | stream.skipToEnd()
106 | return ret("comment", "comment")
107 | } else if (isOperatorChar.test(ch)) {
108 | if (ch != ">" || !state.lexical || state.lexical.type != ">") {
109 | if (stream.eat("=")) {
110 | if (ch == "!" || ch == "=") stream.eat("=")
111 | } else if (/[<>*+\-]/.test(ch)) {
112 | stream.eat(ch)
113 | if (ch == ">") stream.eat(ch)
114 | }
115 | }
116 | return ret("operator", "operator", stream.current());
117 | } else if (wordRE.test(ch)) {
118 | stream.eatWhile(wordRE);
119 | var word = stream.current()
120 | if (state.lastType != ".") {
121 | if (keywords.propertyIsEnumerable(word)) {
122 | var kw = keywords[word]
123 | return ret(kw.type, kw.style, word)
124 | }
125 | if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
126 | return ret("async", "keyword", word)
127 | }
128 | return ret("variable", "variable", word)
129 | }
130 | }
131 |
132 | function tokenString(quote) {
133 | return function(stream, state) {
134 | var escaped = false, next;
135 | if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
136 | state.tokenize = tokenBase;
137 | return ret("jsonld-keyword", "meta");
138 | }
139 | while ((next = stream.next()) != null) {
140 | if (next == quote && !escaped) break;
141 | escaped = !escaped && next == "\\";
142 | }
143 | if (!escaped) state.tokenize = tokenBase;
144 | return ret("string", "string");
145 | };
146 | }
147 |
148 | function tokenComment(stream, state) {
149 | var maybeEnd = false, ch;
150 | while (ch = stream.next()) {
151 | if (ch == "/" && maybeEnd) {
152 | state.tokenize = tokenBase;
153 | break;
154 | }
155 | maybeEnd = (ch == "*");
156 | }
157 | return ret("comment", "comment");
158 | }
159 |
160 | function tokenQuasi(stream, state) {
161 | var escaped = false, next;
162 | while ((next = stream.next()) != null) {
163 | if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
164 | state.tokenize = tokenBase;
165 | break;
166 | }
167 | escaped = !escaped && next == "\\";
168 | }
169 | return ret("quasi", "string-2", stream.current());
170 | }
171 |
172 | var brackets = "([{}])";
173 | // This is a crude lookahead trick to try and notice that we're
174 | // parsing the argument patterns for a fat-arrow function before we
175 | // actually hit the arrow token. It only works if the arrow is on
176 | // the same line as the arguments and there's no strange noise
177 | // (comments) in between. Fallback is to only notice when we hit the
178 | // arrow, and not declare the arguments as locals for the arrow
179 | // body.
180 | function findFatArrow(stream, state) {
181 | if (state.fatArrowAt) state.fatArrowAt = null;
182 | var arrow = stream.string.indexOf("=>", stream.start);
183 | if (arrow < 0) return;
184 |
185 | if (isTS) { // Try to skip TypeScript return type declarations after the arguments
186 | var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
187 | if (m) arrow = m.index
188 | }
189 |
190 | var depth = 0, sawSomething = false;
191 | for (var pos = arrow - 1; pos >= 0; --pos) {
192 | var ch = stream.string.charAt(pos);
193 | var bracket = brackets.indexOf(ch);
194 | if (bracket >= 0 && bracket < 3) {
195 | if (!depth) { ++pos; break; }
196 | if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
197 | } else if (bracket >= 3 && bracket < 6) {
198 | ++depth;
199 | } else if (wordRE.test(ch)) {
200 | sawSomething = true;
201 | } else if (/["'\/`]/.test(ch)) {
202 | for (;; --pos) {
203 | if (pos == 0) return
204 | var next = stream.string.charAt(pos - 1)
205 | if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
206 | }
207 | } else if (sawSomething && !depth) {
208 | ++pos;
209 | break;
210 | }
211 | }
212 | if (sawSomething && !depth) state.fatArrowAt = pos;
213 | }
214 |
215 | // Parser
216 |
217 | var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
218 |
219 | function JSLexical(indented, column, type, align, prev, info) {
220 | this.indented = indented;
221 | this.column = column;
222 | this.type = type;
223 | this.prev = prev;
224 | this.info = info;
225 | if (align != null) this.align = align;
226 | }
227 |
228 | function inScope(state, varname) {
229 | for (var v = state.localVars; v; v = v.next)
230 | if (v.name == varname) return true;
231 | for (var cx = state.context; cx; cx = cx.prev) {
232 | for (var v = cx.vars; v; v = v.next)
233 | if (v.name == varname) return true;
234 | }
235 | }
236 |
237 | function parseJS(state, style, type, content, stream) {
238 | var cc = state.cc;
239 | // Communicate our context to the combinators.
240 | // (Less wasteful than consing up a hundred closures on every call.)
241 | cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
242 |
243 | if (!state.lexical.hasOwnProperty("align"))
244 | state.lexical.align = true;
245 |
246 | while(true) {
247 | var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
248 | if (combinator(type, content)) {
249 | while(cc.length && cc[cc.length - 1].lex)
250 | cc.pop()();
251 | if (cx.marked) return cx.marked;
252 | if (type == "variable" && inScope(state, content)) return "variable-2";
253 | return style;
254 | }
255 | }
256 | }
257 |
258 | // Combinator utils
259 |
260 | var cx = {state: null, column: null, marked: null, cc: null};
261 | function pass() {
262 | for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
263 | }
264 | function cont() {
265 | pass.apply(null, arguments);
266 | return true;
267 | }
268 | function inList(name, list) {
269 | for (var v = list; v; v = v.next) if (v.name == name) return true
270 | return false;
271 | }
272 | function register(varname) {
273 | var state = cx.state;
274 | cx.marked = "def";
275 | if (state.context) {
276 | if (state.lexical.info == "var" && state.context && state.context.block) {
277 | // FIXME function decls are also not block scoped
278 | var newContext = registerVarScoped(varname, state.context)
279 | if (newContext != null) {
280 | state.context = newContext
281 | return
282 | }
283 | } else if (!inList(varname, state.localVars)) {
284 | state.localVars = new Var(varname, state.localVars)
285 | return
286 | }
287 | }
288 | // Fall through means this is global
289 | if (parserConfig.globalVars && !inList(varname, state.globalVars))
290 | state.globalVars = new Var(varname, state.globalVars)
291 | }
292 | function registerVarScoped(varname, context) {
293 | if (!context) {
294 | return null
295 | } else if (context.block) {
296 | var inner = registerVarScoped(varname, context.prev)
297 | if (!inner) return null
298 | if (inner == context.prev) return context
299 | return new Context(inner, context.vars, true)
300 | } else if (inList(varname, context.vars)) {
301 | return context
302 | } else {
303 | return new Context(context.prev, new Var(varname, context.vars), false)
304 | }
305 | }
306 |
307 | function isModifier(name) {
308 | return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
309 | }
310 |
311 | // Combinators
312 |
313 | function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
314 | function Var(name, next) { this.name = name; this.next = next }
315 |
316 | var defaultVars = new Var("this", new Var("arguments", null))
317 | function pushcontext() {
318 | cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
319 | cx.state.localVars = defaultVars
320 | }
321 | function pushblockcontext() {
322 | cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
323 | cx.state.localVars = null
324 | }
325 | function popcontext() {
326 | cx.state.localVars = cx.state.context.vars
327 | cx.state.context = cx.state.context.prev
328 | }
329 | popcontext.lex = true
330 | function pushlex(type, info) {
331 | var result = function() {
332 | var state = cx.state, indent = state.indented;
333 | if (state.lexical.type == "stat") indent = state.lexical.indented;
334 | else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
335 | indent = outer.indented;
336 | state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
337 | };
338 | result.lex = true;
339 | return result;
340 | }
341 | function poplex() {
342 | var state = cx.state;
343 | if (state.lexical.prev) {
344 | if (state.lexical.type == ")")
345 | state.indented = state.lexical.indented;
346 | state.lexical = state.lexical.prev;
347 | }
348 | }
349 | poplex.lex = true;
350 |
351 | function expect(wanted) {
352 | function exp(type) {
353 | if (type == wanted) return cont();
354 | else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
355 | else return cont(exp);
356 | };
357 | return exp;
358 | }
359 |
360 | function statement(type, value) {
361 | if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
362 | if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
363 | if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
364 | if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
365 | if (type == "debugger") return cont(expect(";"));
366 | if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
367 | if (type == ";") return cont();
368 | if (type == "if") {
369 | if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
370 | cx.state.cc.pop()();
371 | return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
372 | }
373 | if (type == "function") return cont(functiondef);
374 | if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
375 | if (type == "class" || (isTS && value == "interface")) {
376 | cx.marked = "keyword"
377 | return cont(pushlex("form", type == "class" ? type : value), className, poplex)
378 | }
379 | if (type == "variable") {
380 | if (isTS && value == "declare") {
381 | cx.marked = "keyword"
382 | return cont(statement)
383 | } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
384 | cx.marked = "keyword"
385 | if (value == "enum") return cont(enumdef);
386 | else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));
387 | else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
388 | } else if (isTS && value == "namespace") {
389 | cx.marked = "keyword"
390 | return cont(pushlex("form"), expression, statement, poplex)
391 | } else if (isTS && value == "abstract") {
392 | cx.marked = "keyword"
393 | return cont(statement)
394 | } else {
395 | return cont(pushlex("stat"), maybelabel);
396 | }
397 | }
398 | if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
399 | block, poplex, poplex, popcontext);
400 | if (type == "case") return cont(expression, expect(":"));
401 | if (type == "default") return cont(expect(":"));
402 | if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
403 | if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
404 | if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
405 | if (type == "async") return cont(statement)
406 | if (value == "@") return cont(expression, statement)
407 | return pass(pushlex("stat"), expression, expect(";"), poplex);
408 | }
409 | function maybeCatchBinding(type) {
410 | if (type == "(") return cont(funarg, expect(")"))
411 | }
412 | function expression(type, value) {
413 | return expressionInner(type, value, false);
414 | }
415 | function expressionNoComma(type, value) {
416 | return expressionInner(type, value, true);
417 | }
418 | function parenExpr(type) {
419 | if (type != "(") return pass()
420 | return cont(pushlex(")"), expression, expect(")"), poplex)
421 | }
422 | function expressionInner(type, value, noComma) {
423 | if (cx.state.fatArrowAt == cx.stream.start) {
424 | var body = noComma ? arrowBodyNoComma : arrowBody;
425 | if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
426 | else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
427 | }
428 |
429 | var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
430 | if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
431 | if (type == "function") return cont(functiondef, maybeop);
432 | if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
433 | if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
434 | if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
435 | if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
436 | if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
437 | if (type == "{") return contCommasep(objprop, "}", null, maybeop);
438 | if (type == "quasi") return pass(quasi, maybeop);
439 | if (type == "new") return cont(maybeTarget(noComma));
440 | if (type == "import") return cont(expression);
441 | return cont();
442 | }
443 | function maybeexpression(type) {
444 | if (type.match(/[;\}\)\],]/)) return pass();
445 | return pass(expression);
446 | }
447 |
448 | function maybeoperatorComma(type, value) {
449 | if (type == ",") return cont(expression);
450 | return maybeoperatorNoComma(type, value, false);
451 | }
452 | function maybeoperatorNoComma(type, value, noComma) {
453 | var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
454 | var expr = noComma == false ? expression : expressionNoComma;
455 | if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
456 | if (type == "operator") {
457 | if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
458 | if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false))
459 | return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
460 | if (value == "?") return cont(expression, expect(":"), expr);
461 | return cont(expr);
462 | }
463 | if (type == "quasi") { return pass(quasi, me); }
464 | if (type == ";") return;
465 | if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
466 | if (type == ".") return cont(property, me);
467 | if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
468 | if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
469 | if (type == "regexp") {
470 | cx.state.lastType = cx.marked = "operator"
471 | cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
472 | return cont(expr)
473 | }
474 | }
475 | function quasi(type, value) {
476 | if (type != "quasi") return pass();
477 | if (value.slice(value.length - 2) != "${") return cont(quasi);
478 | return cont(expression, continueQuasi);
479 | }
480 | function continueQuasi(type) {
481 | if (type == "}") {
482 | cx.marked = "string-2";
483 | cx.state.tokenize = tokenQuasi;
484 | return cont(quasi);
485 | }
486 | }
487 | function arrowBody(type) {
488 | findFatArrow(cx.stream, cx.state);
489 | return pass(type == "{" ? statement : expression);
490 | }
491 | function arrowBodyNoComma(type) {
492 | findFatArrow(cx.stream, cx.state);
493 | return pass(type == "{" ? statement : expressionNoComma);
494 | }
495 | function maybeTarget(noComma) {
496 | return function(type) {
497 | if (type == ".") return cont(noComma ? targetNoComma : target);
498 | else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
499 | else return pass(noComma ? expressionNoComma : expression);
500 | };
501 | }
502 | function target(_, value) {
503 | if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
504 | }
505 | function targetNoComma(_, value) {
506 | if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
507 | }
508 | function maybelabel(type) {
509 | if (type == ":") return cont(poplex, statement);
510 | return pass(maybeoperatorComma, expect(";"), poplex);
511 | }
512 | function property(type) {
513 | if (type == "variable") {cx.marked = "property"; return cont();}
514 | }
515 | function objprop(type, value) {
516 | if (type == "async") {
517 | cx.marked = "property";
518 | return cont(objprop);
519 | } else if (type == "variable" || cx.style == "keyword") {
520 | cx.marked = "property";
521 | if (value == "get" || value == "set") return cont(getterSetter);
522 | var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
523 | if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
524 | cx.state.fatArrowAt = cx.stream.pos + m[0].length
525 | return cont(afterprop);
526 | } else if (type == "number" || type == "string") {
527 | cx.marked = jsonldMode ? "property" : (cx.style + " property");
528 | return cont(afterprop);
529 | } else if (type == "jsonld-keyword") {
530 | return cont(afterprop);
531 | } else if (isTS && isModifier(value)) {
532 | cx.marked = "keyword"
533 | return cont(objprop)
534 | } else if (type == "[") {
535 | return cont(expression, maybetype, expect("]"), afterprop);
536 | } else if (type == "spread") {
537 | return cont(expressionNoComma, afterprop);
538 | } else if (value == "*") {
539 | cx.marked = "keyword";
540 | return cont(objprop);
541 | } else if (type == ":") {
542 | return pass(afterprop)
543 | }
544 | }
545 | function getterSetter(type) {
546 | if (type != "variable") return pass(afterprop);
547 | cx.marked = "property";
548 | return cont(functiondef);
549 | }
550 | function afterprop(type) {
551 | if (type == ":") return cont(expressionNoComma);
552 | if (type == "(") return pass(functiondef);
553 | }
554 | function commasep(what, end, sep) {
555 | function proceed(type, value) {
556 | if (sep ? sep.indexOf(type) > -1 : type == ",") {
557 | var lex = cx.state.lexical;
558 | if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
559 | return cont(function(type, value) {
560 | if (type == end || value == end) return pass()
561 | return pass(what)
562 | }, proceed);
563 | }
564 | if (type == end || value == end) return cont();
565 | if (sep && sep.indexOf(";") > -1) return pass(what)
566 | return cont(expect(end));
567 | }
568 | return function(type, value) {
569 | if (type == end || value == end) return cont();
570 | return pass(what, proceed);
571 | };
572 | }
573 | function contCommasep(what, end, info) {
574 | for (var i = 3; i < arguments.length; i++)
575 | cx.cc.push(arguments[i]);
576 | return cont(pushlex(end, info), commasep(what, end), poplex);
577 | }
578 | function block(type) {
579 | if (type == "}") return cont();
580 | return pass(statement, block);
581 | }
582 | function maybetype(type, value) {
583 | if (isTS) {
584 | if (type == ":") return cont(typeexpr);
585 | if (value == "?") return cont(maybetype);
586 | }
587 | }
588 | function maybetypeOrIn(type, value) {
589 | if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
590 | }
591 | function mayberettype(type) {
592 | if (isTS && type == ":") {
593 | if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
594 | else return cont(typeexpr)
595 | }
596 | }
597 | function isKW(_, value) {
598 | if (value == "is") {
599 | cx.marked = "keyword"
600 | return cont()
601 | }
602 | }
603 | function typeexpr(type, value) {
604 | if (value == "keyof" || value == "typeof" || value == "infer") {
605 | cx.marked = "keyword"
606 | return cont(value == "typeof" ? expressionNoComma : typeexpr)
607 | }
608 | if (type == "variable" || value == "void") {
609 | cx.marked = "type"
610 | return cont(afterType)
611 | }
612 | if (value == "|" || value == "&") return cont(typeexpr)
613 | if (type == "string" || type == "number" || type == "atom") return cont(afterType);
614 | if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
615 | if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
616 | if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
617 | if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
618 | }
619 | function maybeReturnType(type) {
620 | if (type == "=>") return cont(typeexpr)
621 | }
622 | function typeprop(type, value) {
623 | if (type == "variable" || cx.style == "keyword") {
624 | cx.marked = "property"
625 | return cont(typeprop)
626 | } else if (value == "?" || type == "number" || type == "string") {
627 | return cont(typeprop)
628 | } else if (type == ":") {
629 | return cont(typeexpr)
630 | } else if (type == "[") {
631 | return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
632 | } else if (type == "(") {
633 | return pass(functiondecl, typeprop)
634 | }
635 | }
636 | function typearg(type, value) {
637 | if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
638 | if (type == ":") return cont(typeexpr)
639 | if (type == "spread") return cont(typearg)
640 | return pass(typeexpr)
641 | }
642 | function afterType(type, value) {
643 | if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
644 | if (value == "|" || type == "." || value == "&") return cont(typeexpr)
645 | if (type == "[") return cont(typeexpr, expect("]"), afterType)
646 | if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
647 | if (value == "?") return cont(typeexpr, expect(":"), typeexpr)
648 | }
649 | function maybeTypeArgs(_, value) {
650 | if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
651 | }
652 | function typeparam() {
653 | return pass(typeexpr, maybeTypeDefault)
654 | }
655 | function maybeTypeDefault(_, value) {
656 | if (value == "=") return cont(typeexpr)
657 | }
658 | function vardef(_, value) {
659 | if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
660 | return pass(pattern, maybetype, maybeAssign, vardefCont);
661 | }
662 | function pattern(type, value) {
663 | if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
664 | if (type == "variable") { register(value); return cont(); }
665 | if (type == "spread") return cont(pattern);
666 | if (type == "[") return contCommasep(eltpattern, "]");
667 | if (type == "{") return contCommasep(proppattern, "}");
668 | }
669 | function proppattern(type, value) {
670 | if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
671 | register(value);
672 | return cont(maybeAssign);
673 | }
674 | if (type == "variable") cx.marked = "property";
675 | if (type == "spread") return cont(pattern);
676 | if (type == "}") return pass();
677 | if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
678 | return cont(expect(":"), pattern, maybeAssign);
679 | }
680 | function eltpattern() {
681 | return pass(pattern, maybeAssign)
682 | }
683 | function maybeAssign(_type, value) {
684 | if (value == "=") return cont(expressionNoComma);
685 | }
686 | function vardefCont(type) {
687 | if (type == ",") return cont(vardef);
688 | }
689 | function maybeelse(type, value) {
690 | if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
691 | }
692 | function forspec(type, value) {
693 | if (value == "await") return cont(forspec);
694 | if (type == "(") return cont(pushlex(")"), forspec1, poplex);
695 | }
696 | function forspec1(type) {
697 | if (type == "var") return cont(vardef, forspec2);
698 | if (type == "variable") return cont(forspec2);
699 | return pass(forspec2)
700 | }
701 | function forspec2(type, value) {
702 | if (type == ")") return cont()
703 | if (type == ";") return cont(forspec2)
704 | if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
705 | return pass(expression, forspec2)
706 | }
707 | function functiondef(type, value) {
708 | if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
709 | if (type == "variable") {register(value); return cont(functiondef);}
710 | if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
711 | if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
712 | }
713 | function functiondecl(type, value) {
714 | if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
715 | if (type == "variable") {register(value); return cont(functiondecl);}
716 | if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
717 | if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
718 | }
719 | function typename(type, value) {
720 | if (type == "keyword" || type == "variable") {
721 | cx.marked = "type"
722 | return cont(typename)
723 | } else if (value == "<") {
724 | return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
725 | }
726 | }
727 | function funarg(type, value) {
728 | if (value == "@") cont(expression, funarg)
729 | if (type == "spread") return cont(funarg);
730 | if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
731 | if (isTS && type == "this") return cont(maybetype, maybeAssign)
732 | return pass(pattern, maybetype, maybeAssign);
733 | }
734 | function classExpression(type, value) {
735 | // Class expressions may have an optional name.
736 | if (type == "variable") return className(type, value);
737 | return classNameAfter(type, value);
738 | }
739 | function className(type, value) {
740 | if (type == "variable") {register(value); return cont(classNameAfter);}
741 | }
742 | function classNameAfter(type, value) {
743 | if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
744 | if (value == "extends" || value == "implements" || (isTS && type == ",")) {
745 | if (value == "implements") cx.marked = "keyword";
746 | return cont(isTS ? typeexpr : expression, classNameAfter);
747 | }
748 | if (type == "{") return cont(pushlex("}"), classBody, poplex);
749 | }
750 | function classBody(type, value) {
751 | if (type == "async" ||
752 | (type == "variable" &&
753 | (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
754 | cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
755 | cx.marked = "keyword";
756 | return cont(classBody);
757 | }
758 | if (type == "variable" || cx.style == "keyword") {
759 | cx.marked = "property";
760 | return cont(isTS ? classfield : functiondef, classBody);
761 | }
762 | if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody);
763 | if (type == "[")
764 | return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody)
765 | if (value == "*") {
766 | cx.marked = "keyword";
767 | return cont(classBody);
768 | }
769 | if (isTS && type == "(") return pass(functiondecl, classBody)
770 | if (type == ";" || type == ",") return cont(classBody);
771 | if (type == "}") return cont();
772 | if (value == "@") return cont(expression, classBody)
773 | }
774 | function classfield(type, value) {
775 | if (value == "?") return cont(classfield)
776 | if (type == ":") return cont(typeexpr, maybeAssign)
777 | if (value == "=") return cont(expressionNoComma)
778 | var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
779 | return pass(isInterface ? functiondecl : functiondef)
780 | }
781 | function afterExport(type, value) {
782 | if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
783 | if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
784 | if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
785 | return pass(statement);
786 | }
787 | function exportField(type, value) {
788 | if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
789 | if (type == "variable") return pass(expressionNoComma, exportField);
790 | }
791 | function afterImport(type) {
792 | if (type == "string") return cont();
793 | if (type == "(") return pass(expression);
794 | return pass(importSpec, maybeMoreImports, maybeFrom);
795 | }
796 | function importSpec(type, value) {
797 | if (type == "{") return contCommasep(importSpec, "}");
798 | if (type == "variable") register(value);
799 | if (value == "*") cx.marked = "keyword";
800 | return cont(maybeAs);
801 | }
802 | function maybeMoreImports(type) {
803 | if (type == ",") return cont(importSpec, maybeMoreImports)
804 | }
805 | function maybeAs(_type, value) {
806 | if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
807 | }
808 | function maybeFrom(_type, value) {
809 | if (value == "from") { cx.marked = "keyword"; return cont(expression); }
810 | }
811 | function arrayLiteral(type) {
812 | if (type == "]") return cont();
813 | return pass(commasep(expressionNoComma, "]"));
814 | }
815 | function enumdef() {
816 | return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
817 | }
818 | function enummember() {
819 | return pass(pattern, maybeAssign);
820 | }
821 |
822 | function isContinuedStatement(state, textAfter) {
823 | return state.lastType == "operator" || state.lastType == "," ||
824 | isOperatorChar.test(textAfter.charAt(0)) ||
825 | /[,.]/.test(textAfter.charAt(0));
826 | }
827 |
828 | function expressionAllowed(stream, state, backUp) {
829 | return state.tokenize == tokenBase &&
830 | /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
831 | (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
832 | }
833 |
834 | // Interface
835 |
836 | return {
837 | startState: function(basecolumn) {
838 | var state = {
839 | tokenize: tokenBase,
840 | lastType: "sof",
841 | cc: [],
842 | lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
843 | localVars: parserConfig.localVars,
844 | context: parserConfig.localVars && new Context(null, null, false),
845 | indented: basecolumn || 0
846 | };
847 | if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
848 | state.globalVars = parserConfig.globalVars;
849 | return state;
850 | },
851 |
852 | token: function(stream, state) {
853 | if (stream.sol()) {
854 | if (!state.lexical.hasOwnProperty("align"))
855 | state.lexical.align = false;
856 | state.indented = stream.indentation();
857 | findFatArrow(stream, state);
858 | }
859 | if (state.tokenize != tokenComment && stream.eatSpace()) return null;
860 | var style = state.tokenize(stream, state);
861 | if (type == "comment") return style;
862 | state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
863 | return parseJS(state, style, type, content, stream);
864 | },
865 |
866 | indent: function(state, textAfter) {
867 | if (state.tokenize == tokenComment) return CodeMirror.Pass;
868 | if (state.tokenize != tokenBase) return 0;
869 | var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
870 | // Kludge to prevent 'maybelse' from blocking lexical scope pops
871 | if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
872 | var c = state.cc[i];
873 | if (c == poplex) lexical = lexical.prev;
874 | else if (c != maybeelse) break;
875 | }
876 | while ((lexical.type == "stat" || lexical.type == "form") &&
877 | (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
878 | (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
879 | !/^[,\.=+\-*:?[\(]/.test(textAfter))))
880 | lexical = lexical.prev;
881 | if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
882 | lexical = lexical.prev;
883 | var type = lexical.type, closing = firstChar == type;
884 |
885 | if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
886 | else if (type == "form" && firstChar == "{") return lexical.indented;
887 | else if (type == "form") return lexical.indented + indentUnit;
888 | else if (type == "stat")
889 | return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
890 | else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
891 | return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
892 | else if (lexical.align) return lexical.column + (closing ? 0 : 1);
893 | else return lexical.indented + (closing ? 0 : indentUnit);
894 | },
895 |
896 | electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
897 | blockCommentStart: jsonMode ? null : "/*",
898 | blockCommentEnd: jsonMode ? null : "*/",
899 | blockCommentContinue: jsonMode ? null : " * ",
900 | lineComment: jsonMode ? null : "//",
901 | fold: "brace",
902 | closeBrackets: "()[]{}''\"\"``",
903 |
904 | helperType: jsonMode ? "json" : "javascript",
905 | jsonldMode: jsonldMode,
906 | jsonMode: jsonMode,
907 |
908 | expressionAllowed: expressionAllowed,
909 |
910 | skipExpression: function(state) {
911 | var top = state.cc[state.cc.length - 1]
912 | if (top == expression || top == expressionNoComma) state.cc.pop()
913 | }
914 | };
915 | });
916 |
917 | CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
918 |
919 | CodeMirror.defineMIME("text/javascript", "javascript");
920 | CodeMirror.defineMIME("text/ecmascript", "javascript");
921 | CodeMirror.defineMIME("application/javascript", "javascript");
922 | CodeMirror.defineMIME("application/x-javascript", "javascript");
923 | CodeMirror.defineMIME("application/ecmascript", "javascript");
924 | CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
925 | CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
926 | CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
927 | CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
928 | CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
929 |
930 | });
931 |
--------------------------------------------------------------------------------