summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/packages/testserver
diff options
context:
space:
mode:
Diffstat (limited to 'remote/test/puppeteer/packages/testserver')
-rw-r--r--remote/test/puppeteer/packages/testserver/CHANGELOG.md8
-rw-r--r--remote/test/puppeteer/packages/testserver/LICENSE202
-rw-r--r--remote/test/puppeteer/packages/testserver/README.md18
-rw-r--r--remote/test/puppeteer/packages/testserver/cert.pem20
-rw-r--r--remote/test/puppeteer/packages/testserver/key.pem28
-rw-r--r--remote/test/puppeteer/packages/testserver/package.json36
-rw-r--r--remote/test/puppeteer/packages/testserver/src/index.ts311
-rw-r--r--remote/test/puppeteer/packages/testserver/tsconfig.json12
-rw-r--r--remote/test/puppeteer/packages/testserver/tsdoc.json15
9 files changed, 650 insertions, 0 deletions
diff --git a/remote/test/puppeteer/packages/testserver/CHANGELOG.md b/remote/test/puppeteer/packages/testserver/CHANGELOG.md
new file mode 100644
index 0000000000..bb971ef46d
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/CHANGELOG.md
@@ -0,0 +1,8 @@
+# Changelog
+
+## [0.6.0](https://github.com/puppeteer/puppeteer/compare/testserver-v0.5.0...testserver-v0.6.0) (2022-10-05)
+
+
+### Features
+
+* separate puppeteer and puppeteer-core ([#9023](https://github.com/puppeteer/puppeteer/issues/9023)) ([f42336c](https://github.com/puppeteer/puppeteer/commit/f42336cf83982332829ca7e14ee48d8676e11545))
diff --git a/remote/test/puppeteer/packages/testserver/LICENSE b/remote/test/puppeteer/packages/testserver/LICENSE
new file mode 100644
index 0000000000..afdfe50e72
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 Google Inc.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/remote/test/puppeteer/packages/testserver/README.md b/remote/test/puppeteer/packages/testserver/README.md
new file mode 100644
index 0000000000..d22b2da449
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/README.md
@@ -0,0 +1,18 @@
+# TestServer
+
+This test server is used internally by Puppeteer to test Puppeteer itself.
+
+### Example
+
+```ts
+const {TestServer} = require('@pptr/testserver');
+
+(async(() => {
+ const httpServer = await TestServer.create(__dirname, 8000),
+ const httpsServer = await TestServer.createHTTPS(__dirname, 8001)
+ httpServer.setRoute('/hello', (req, res) => {
+ res.end('Hello, world!');
+ });
+ console.log('HTTP and HTTPS servers are running!');
+})();
+```
diff --git a/remote/test/puppeteer/packages/testserver/cert.pem b/remote/test/puppeteer/packages/testserver/cert.pem
new file mode 100644
index 0000000000..fd3838535a
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/cert.pem
@@ -0,0 +1,20 @@
+-----BEGIN CERTIFICATE-----
+MIIDWDCCAkCgAwIBAgIUM8Tmw+D1j+eVz9x9So4zRVqFsKowDQYJKoZIhvcNAQEL
+BQAwGjEYMBYGA1UEAwwPcHVwcGV0ZWVyLXRlc3RzMB4XDTIwMDUxMzA4MDQyOVoX
+DTMwMDUxMTA4MDQyOVowGjEYMBYGA1UEAwwPcHVwcGV0ZWVyLXRlc3RzMIIBIjAN
+BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApWbbhgc6CnWywd8xGETT1mfLi3wi
+KIbpAUHghLF4sj0jXz8vLh/4oicpQ12d6bsz+IAi7qrdXNh11P5nEej6/Gx4fWzB
+gGdrJFGPqsvXuhYdzZAmy6xOaWcLIJeQ543bXv3YeST7EGRXJBc/ocTo2jIGTGjq
+hksFaid910VQlX3KGOLTDMUCk00TeEYBTTUx47PWoIsxVqbl2RzVXRSWL5hlPWlW
+29/BQtBGmsXxZyWtqqHudiUulGBSr4LcPyicZLI8nqCqD0ioS0TEmGh61nRBuwBa
+xmLCvPmpt0+sDuOU+1bme3w8juvTVToBIFxGB86rADd3ys+8NeZzXqi+bQIDAQAB
+o4GVMIGSMB0GA1UdDgQWBBT/m3vdkZpQyVQFdYrKHVoAHXDFODAfBgNVHSMEGDAW
+gBT/m3vdkZpQyVQFdYrKHVoAHXDFODAPBgNVHRMBAf8EBTADAQH/MD8GA1UdEQQ4
+MDaCGHd3dy5wdXBwZXRlZXItdGVzdHMudGVzdIIad3d3LnB1cHBldGVlci10ZXN0
+cy0xLnRlc3QwDQYJKoZIhvcNAQELBQADggEBAI1qp5ZppV1R3e8XxzwwkFDPFN8W
+Pe3AoqhAKyJnJl1NUn9q3sroEeSQRhODWUHCd7lENzhsT+3mzonNNkN9B/hq0rpK
+KHHczXILDqdyuxH3LxQ1VHGE8VN2NbdkfobtzAsA3woiJxOuGeusXJnKB4kJQeIP
+V+BMEZWeaSDC2PREkG7GOezmE1/WDUCYaorPw2whdCA5wJvTW3zXpJjYhfsld+5z
+KuErx4OCxRJij73/BD9SpLxDEY1cdl819F1IvxsRGhmTIaSly2hQLrhOgo1jgZtV
+FGCa6DSlXnQGLaV+N+ssR0lkCksNrNBVDfA1bP5bT/4VCcwUWwm9TUeF0Qo=
+-----END CERTIFICATE-----
diff --git a/remote/test/puppeteer/packages/testserver/key.pem b/remote/test/puppeteer/packages/testserver/key.pem
new file mode 100644
index 0000000000..cbc3acb229
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQClZtuGBzoKdbLB
+3zEYRNPWZ8uLfCIohukBQeCEsXiyPSNfPy8uH/iiJylDXZ3puzP4gCLuqt1c2HXU
+/mcR6Pr8bHh9bMGAZ2skUY+qy9e6Fh3NkCbLrE5pZwsgl5Dnjdte/dh5JPsQZFck
+Fz+hxOjaMgZMaOqGSwVqJ33XRVCVfcoY4tMMxQKTTRN4RgFNNTHjs9agizFWpuXZ
+HNVdFJYvmGU9aVbb38FC0EaaxfFnJa2qoe52JS6UYFKvgtw/KJxksjyeoKoPSKhL
+RMSYaHrWdEG7AFrGYsK8+am3T6wO45T7VuZ7fDyO69NVOgEgXEYHzqsAN3fKz7w1
+5nNeqL5tAgMBAAECggEAKPveo0xBHnxhidZzBM9xKixX7D0a/a3IKI6ZQmfzPz8U
+97HhT+2OHyfS+qVEzribPRULEtZ1uV7Ne7R5958iKc/63yFGpTl6++nVzn1p++sl
+AV2Zr1gHqehlgnLr7eRhmh0OOZ5nM32ZdhDorH3tMLu6gc5xZktKkS4t6Vx8hj3a
+Docx+rbawp8GRd0p7I6vzIE3bsDab8hC+RTRO63q2G0BqgKwV9ZNtJxQgcDJ5L8N
+6gtM2z5nKXAIOCbCQYa1PsrDh3IRA/ZNxEeA9G3YQjwlZYCWmdRRplgDraYxcTBO
+oQGjaLwICNdcprMacPD6cCSgrI+PadzyMsAuk9SgpQKBgQDO9PT4gK40Pm+Damxv
++tWYBFmvn3vasmyolc1zVDltsxQbQTjKhVpTLXTTGmrIhDXEIIV9I4rg164WptQs
+6Brp2EwYR7ZJIrjvXs/9i2QTW1ZXvhdiWpB3s+RXD5VHGovHUadcI6wOgw2Cl+Jk
+zXjSIgyXKM99N1MAonuR7DyzTwKBgQDMmPX+9vWZMpS/gc6JLQiPPoGszE6tYjXg
+W3LpRUNqmO0/bDDjslbebDgrGAmhlkJlxzH6gz96VmGm1evEGPEet3euy8S9zuM3
+LCgEM9Ulqa3JbInwtKupmKv76Im+XWLLSxAXbfiel1zFRRwxI99A3ad0QRZ6Bov5
+3cHJBwvzgwKBgAU5HW2gIcVjxgC1EOOKmxVpFrJd/gw48JEYpsTAXWqtWFaPwNUr
+pGnw/b/OLN++pnS6tWPBH+Ioz1X3A+fWO8enE9SRCsKxw6UW6XzmpbHvXjB8ta5f
+xsGeoqan2AahXuG659RlehQrro2bM7WDkgcLoPG3r/TjDo83ipLWOXn1AoGAKWiL
+4R56dpcWI+xRsNG8ecFc3Ww8QDswTEg16aBrFJf+7GcpPexKSJn+hDpJOLsAlTjL
+lLgbkNcKzIlfPkEOC/l175quJvxIYFI/hxo2eXjuA2ZERMNMOvb7V/CocC7WX+7B
+Qvyu5OodjI+ANTHdbXNvAMhrlCbfDaMkJVuXv6ECgYBzvY4aYmVoFsr+72/EfLls
+Dz9pi55tUUWc61w6ovd+iliawvXeGi4wibtTH4iGj/C2sJIaMmOD99NQ7Oi/x89D
+oMgSUemkoFL8FGsZGyZ7szqxyON1jP42Bm2MQrW5kIf7Y4yaIGhoak5JNxn2JUyV
+gupVbY1mQ1GTPByxHeLh1w==
+-----END PRIVATE KEY-----
diff --git a/remote/test/puppeteer/packages/testserver/package.json b/remote/test/puppeteer/packages/testserver/package.json
new file mode 100644
index 0000000000..3a9ecf9c65
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "@pptr/testserver",
+ "version": "0.6.0",
+ "description": "testing server",
+ "main": "lib/index.js",
+ "scripts": {
+ "build": "wireit",
+ "clean": "../../tools/clean.js"
+ },
+ "wireit": {
+ "build": {
+ "command": "tsc -b",
+ "clean": "if-file-deleted",
+ "files": [
+ "src/**"
+ ],
+ "output": [
+ "lib/**",
+ "tsconfig.tsbuildinfo"
+ ]
+ }
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/puppeteer/puppeteer/tree/main/packages/testserver"
+ },
+ "author": "The Chromium Authors",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "mime": "3.0.0",
+ "ws": "8.16.0"
+ },
+ "devDependencies": {
+ "@types/mime": "3.0.4"
+ }
+}
diff --git a/remote/test/puppeteer/packages/testserver/src/index.ts b/remote/test/puppeteer/packages/testserver/src/index.ts
new file mode 100644
index 0000000000..2618fd4d0d
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/src/index.ts
@@ -0,0 +1,311 @@
+/**
+ * @license
+ * Copyright 2017 Google Inc.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import assert from 'assert';
+import {readFile, readFileSync} from 'fs';
+import {
+ createServer as createHttpServer,
+ type IncomingMessage,
+ type RequestListener,
+ type Server as HttpServer,
+ type ServerResponse,
+} from 'http';
+import {
+ createServer as createHttpsServer,
+ type Server as HttpsServer,
+ type ServerOptions as HttpsServerOptions,
+} from 'https';
+import type {AddressInfo} from 'net';
+import {join} from 'path';
+import type {Duplex} from 'stream';
+import {gzip} from 'zlib';
+
+import {getType as getMimeType} from 'mime';
+import {Server as WebSocketServer, type WebSocket} from 'ws';
+
+interface Subscriber {
+ resolve: (msg: IncomingMessage) => void;
+ reject: (err?: Error) => void;
+ promise: Promise<IncomingMessage>;
+}
+
+type TestIncomingMessage = IncomingMessage & {postBody?: Promise<string>};
+
+export class TestServer {
+ PORT!: number;
+ PREFIX!: string;
+ CROSS_PROCESS_PREFIX!: string;
+ EMPTY_PAGE!: string;
+
+ #dirPath: string;
+ #server: HttpsServer | HttpServer;
+ #wsServer: WebSocketServer;
+
+ #startTime = new Date();
+ #cachedPathPrefix?: string;
+
+ #connections = new Set<Duplex>();
+ #routes = new Map<
+ string,
+ (msg: IncomingMessage, res: ServerResponse) => void
+ >();
+ #auths = new Map<string, {username: string; password: string}>();
+ #csp = new Map<string, string>();
+ #gzipRoutes = new Set<string>();
+ #requestSubscribers = new Map<string, Subscriber>();
+ #requests = new Set<ServerResponse>();
+
+ static async create(dirPath: string): Promise<TestServer> {
+ let res!: (value: unknown) => void;
+ const promise = new Promise(resolve => {
+ res = resolve;
+ });
+ const server = new TestServer(dirPath);
+ server.#server.once('listening', res);
+ server.#server.listen(0);
+ await promise;
+ return server;
+ }
+
+ static async createHTTPS(dirPath: string): Promise<TestServer> {
+ let res!: (value: unknown) => void;
+ const promise = new Promise(resolve => {
+ res = resolve;
+ });
+ const server = new TestServer(dirPath, {
+ key: readFileSync(join(__dirname, '..', 'key.pem')),
+ cert: readFileSync(join(__dirname, '..', 'cert.pem')),
+ passphrase: 'aaaa',
+ });
+ server.#server.once('listening', res);
+ server.#server.listen(0);
+ await promise;
+ return server;
+ }
+
+ constructor(dirPath: string, sslOptions?: HttpsServerOptions) {
+ this.#dirPath = dirPath;
+
+ if (sslOptions) {
+ this.#server = createHttpsServer(sslOptions, this.#onRequest);
+ } else {
+ this.#server = createHttpServer(this.#onRequest);
+ }
+ this.#server.on('connection', this.#onServerConnection);
+ // Disable this as sometimes the socket will timeout
+ // We rely on the fact that we will close the server at the end
+ this.#server.keepAliveTimeout = 0;
+ this.#wsServer = new WebSocketServer({server: this.#server});
+ this.#wsServer.on('connection', this.#onWebSocketConnection);
+ }
+
+ #onServerConnection = (connection: Duplex): void => {
+ this.#connections.add(connection);
+ // ECONNRESET is a legit error given
+ // that tab closing simply kills process.
+ connection.on('error', error => {
+ if ((error as NodeJS.ErrnoException).code !== 'ECONNRESET') {
+ throw error;
+ }
+ });
+ connection.once('close', () => {
+ return this.#connections.delete(connection);
+ });
+ };
+
+ get port(): number {
+ return (this.#server.address() as AddressInfo).port;
+ }
+
+ enableHTTPCache(pathPrefix: string): void {
+ this.#cachedPathPrefix = pathPrefix;
+ }
+
+ setAuth(path: string, username: string, password: string): void {
+ this.#auths.set(path, {username, password});
+ }
+
+ enableGzip(path: string): void {
+ this.#gzipRoutes.add(path);
+ }
+
+ setCSP(path: string, csp: string): void {
+ this.#csp.set(path, csp);
+ }
+
+ async stop(): Promise<void> {
+ this.reset();
+ for (const socket of this.#connections) {
+ socket.destroy();
+ }
+ this.#connections.clear();
+ await new Promise(x => {
+ return this.#server.close(x);
+ });
+ }
+
+ setRoute(
+ path: string,
+ handler: (req: IncomingMessage, res: ServerResponse) => void
+ ): void {
+ this.#routes.set(path, handler);
+ }
+
+ setRedirect(from: string, to: string): void {
+ this.setRoute(from, (_, res) => {
+ res.writeHead(302, {location: to});
+ res.end();
+ });
+ }
+
+ waitForRequest(path: string): Promise<TestIncomingMessage> {
+ const subscriber = this.#requestSubscribers.get(path);
+ if (subscriber) {
+ return subscriber.promise;
+ }
+ let resolve!: (value: IncomingMessage) => void;
+ let reject!: (reason?: Error) => void;
+ const promise = new Promise<IncomingMessage>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ this.#requestSubscribers.set(path, {resolve, reject, promise});
+ return promise;
+ }
+
+ reset(): void {
+ this.#routes.clear();
+ this.#auths.clear();
+ this.#csp.clear();
+ this.#gzipRoutes.clear();
+ const error = new Error('Static Server has been reset');
+ for (const subscriber of this.#requestSubscribers.values()) {
+ subscriber.reject.call(undefined, error);
+ }
+ this.#requestSubscribers.clear();
+ for (const request of this.#requests.values()) {
+ if (!request.writableEnded) {
+ request.end();
+ }
+ }
+ this.#requests.clear();
+ }
+
+ #onRequest: RequestListener = (
+ request: TestIncomingMessage,
+ response
+ ): void => {
+ this.#requests.add(response);
+
+ request.on('error', (error: {code: string}) => {
+ if (error.code === 'ECONNRESET') {
+ response.end();
+ } else {
+ throw error;
+ }
+ });
+ request.postBody = new Promise(resolve => {
+ let body = '';
+ request.on('data', (chunk: string) => {
+ return (body += chunk);
+ });
+ request.on('end', () => {
+ return resolve(body);
+ });
+ });
+ assert(request.url);
+ const url = new URL(request.url, `https://${request.headers.host}`);
+ const path = url.pathname + url.search;
+ const auth = this.#auths.get(path);
+ if (auth) {
+ const credentials = Buffer.from(
+ (request.headers.authorization || '').split(' ')[1] || '',
+ 'base64'
+ ).toString();
+ if (credentials !== `${auth.username}:${auth.password}`) {
+ response.writeHead(401, {
+ 'WWW-Authenticate': 'Basic realm="Secure Area"',
+ });
+ response.end('HTTP Error 401 Unauthorized: Access is denied');
+ return;
+ }
+ }
+ const subscriber = this.#requestSubscribers.get(path);
+ if (subscriber) {
+ subscriber.resolve.call(undefined, request);
+ this.#requestSubscribers.delete(path);
+ }
+ const handler = this.#routes.get(path);
+ if (handler) {
+ handler.call(undefined, request, response);
+ } else {
+ this.serveFile(request, response, path);
+ }
+ };
+
+ serveFile(
+ request: IncomingMessage,
+ response: ServerResponse,
+ pathName: string
+ ): void {
+ if (pathName === '/') {
+ pathName = '/index.html';
+ }
+ const filePath = join(this.#dirPath, pathName.substring(1));
+
+ if (this.#cachedPathPrefix && filePath.startsWith(this.#cachedPathPrefix)) {
+ if (request.headers['if-modified-since']) {
+ response.statusCode = 304; // not modified
+ response.end();
+ return;
+ }
+ response.setHeader('Cache-Control', 'public, max-age=31536000');
+ response.setHeader('Last-Modified', this.#startTime.toISOString());
+ } else {
+ response.setHeader('Cache-Control', 'no-cache, no-store');
+ }
+ const csp = this.#csp.get(pathName);
+ if (csp) {
+ response.setHeader('Content-Security-Policy', csp);
+ }
+
+ readFile(filePath, (err, data) => {
+ // This can happen if the request is not awaited but started
+ // in the test and get clean via `reset()`
+ if (response.writableEnded) {
+ return;
+ }
+
+ if (err) {
+ response.statusCode = 404;
+ response.end(`File not found: ${filePath}`);
+ return;
+ }
+ const mimeType = getMimeType(filePath);
+ if (mimeType) {
+ const isTextEncoding = /^text\/|^application\/(javascript|json)/.test(
+ mimeType
+ );
+ const contentType = isTextEncoding
+ ? `${mimeType}; charset=utf-8`
+ : mimeType;
+ response.setHeader('Content-Type', contentType);
+ }
+ if (this.#gzipRoutes.has(pathName)) {
+ response.setHeader('Content-Encoding', 'gzip');
+ gzip(data, (_, result) => {
+ response.end(result);
+ });
+ } else {
+ response.end(data);
+ }
+ });
+ }
+
+ #onWebSocketConnection = (socket: WebSocket): void => {
+ socket.send('opened');
+ };
+}
diff --git a/remote/test/puppeteer/packages/testserver/tsconfig.json b/remote/test/puppeteer/packages/testserver/tsconfig.json
new file mode 100644
index 0000000000..08e6681481
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "allowJs": true,
+ "composite": true,
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "lib",
+ "rootDir": "src",
+ },
+ "include": ["src"],
+}
diff --git a/remote/test/puppeteer/packages/testserver/tsdoc.json b/remote/test/puppeteer/packages/testserver/tsdoc.json
new file mode 100644
index 0000000000..f5b91f4af6
--- /dev/null
+++ b/remote/test/puppeteer/packages/testserver/tsdoc.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
+
+ "extends": ["@microsoft/api-extractor/extends/tsdoc-base.json"],
+ "tagDefinitions": [
+ {
+ "tagName": "@license",
+ "syntaxKind": "modifier",
+ "allowMultiple": false
+ }
+ ],
+ "supportForTags": {
+ "@license": true
+ }
+}