├── .prettierrc.json ├── util.ts ├── router.ts ├── index.ts ├── LICENSE └── index.d.ts /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } 5 | -------------------------------------------------------------------------------- /util.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Get own property `prop` from `obj`. 3 | */ 4 | export const getOwn = ( 5 | obj: T, 6 | prop: P, 7 | ): T[P] | undefined => 8 | Object.prototype.hasOwnProperty.call(obj, prop) ? obj[prop] : undefined; 9 | -------------------------------------------------------------------------------- /router.ts: -------------------------------------------------------------------------------- 1 | import { getOwn } from './util.ts'; 2 | 3 | export type RouteHandler = ( 4 | url: URL, 5 | request: Request, 6 | ) => Promise | Response; 7 | type Route = RouteHandler | { [method: string]: RouteHandler }; 8 | 9 | const router = new Map(); 10 | 11 | function getRouteFunction( 12 | route: Route, 13 | method: string, 14 | ): RouteHandler | undefined { 15 | if (typeof route === 'function') { 16 | if (method === 'GET') return route; 17 | return undefined; 18 | } 19 | 20 | return getOwn(route, method) || getOwn(route, 'all'); 21 | } 22 | 23 | export const simpleErrorResponse = (status: number, message: string) => 24 | new Response(message, { 25 | status, 26 | headers: { 'Content-Type': 'text/plain' }, 27 | }); 28 | 29 | async function handleRequest(request: Request): Promise { 30 | const url = new URL(request.url); 31 | 32 | const route = router.get(url.pathname); 33 | 34 | if (!route) return simpleErrorResponse(404, 'Not found'); 35 | 36 | const routeHandler = getRouteFunction(route, request.method); 37 | 38 | if (!routeHandler) return simpleErrorResponse(405, 'Method not allowed'); 39 | 40 | try { 41 | return await routeHandler(url, request); 42 | } catch (error) { 43 | console.log(error); 44 | return simpleErrorResponse(500, 'Internal server error'); 45 | } 46 | } 47 | 48 | export function addRoute(path: string, route: Route) { 49 | router.set(path, route); 50 | } 51 | 52 | addEventListener('fetch', (event) => 53 | event.respondWith(handleRequest(event.request)), 54 | ); 55 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import { addRoute } from './router.ts'; 2 | 3 | addRoute('/psl', async () => { 4 | const pslResponse = await fetch( 5 | 'https://publicsuffix.org/list/public_suffix_list.dat', 6 | ); 7 | 8 | return new Response(pslResponse.body, { 9 | headers: { 10 | ...Object.fromEntries(pslResponse.headers), 11 | 'Content-Security-Policy': 'sandbox', 12 | 'Access-Control-Allow-Origin': '*', 13 | }, 14 | }); 15 | }); 16 | 17 | type KeyValue = [key: string, value: string]; 18 | 19 | interface Details { 20 | preflightHeaders?: KeyValue[]; 21 | headers?: KeyValue[]; 22 | method?: string; 23 | } 24 | const detailsMap = new Map(); 25 | 26 | function getDetails(id: string | null): Details { 27 | // Just return a dummy object to make things easier. 28 | if (!id) return {}; 29 | if (!detailsMap.has(id)) { 30 | detailsMap.set(id, {}); 31 | // Only keep details around for a minute: 32 | setTimeout(() => detailsMap.delete(id), 60_000); 33 | } 34 | return detailsMap.get(id)!; 35 | } 36 | 37 | addRoute('/resource', { 38 | OPTIONS(url, request) { 39 | const details = getDetails(url.searchParams.get('id')); 40 | details.preflightHeaders = [...request.headers]; 41 | const headers = new Headers(); 42 | const status = Number(url.searchParams.get('preflight-status')) || 204; 43 | 44 | for (const acHeader of [ 45 | 'allow-origin', 46 | 'allow-credentials', 47 | 'allow-methods', 48 | 'allow-headers', 49 | ]) { 50 | const fullHeader = `access-control-${acHeader}`; 51 | const queryKey = `preflight-${fullHeader}`; 52 | const value = url.searchParams.get(queryKey); 53 | if (value) headers.set(fullHeader, url.searchParams.get(queryKey)!); 54 | } 55 | 56 | return new Response(null, { status, headers }); 57 | }, 58 | all(url, request) { 59 | const details = getDetails(url.searchParams.get('id')); 60 | details.headers = [...request.headers]; 61 | details.method = request.method; 62 | const headers = new Headers({ 63 | foo: 'bar', 64 | hello: 'world', 65 | 'Content-Type': 'text/plain; charset=utf-8', 66 | vary: 'cookie, origin', 67 | }); 68 | const status = Number(url.searchParams.get('status')) || 200; 69 | 70 | for (const acHeader of [ 71 | 'allow-origin', 72 | 'allow-credentials', 73 | 'expose-headers', 74 | ]) { 75 | const fullHeader = `access-control-${acHeader}`; 76 | const value = url.searchParams.get(fullHeader); 77 | if (value) headers.set(fullHeader, url.searchParams.get(fullHeader)!); 78 | } 79 | 80 | const cookieValues = url.searchParams.getAll('cookie-value'); 81 | 82 | for (const [i, name] of url.searchParams.getAll('cookie-name').entries()) { 83 | const value = cookieValues[i] || ''; 84 | headers.append( 85 | 'Set-Cookie', 86 | encodeURIComponent(name) + 87 | '=' + 88 | encodeURIComponent(value) + 89 | '; Max-Age=86400; SameSite=None; Secure', 90 | ); 91 | } 92 | 93 | return new Response(status === 204 ? null : 'response! 😀', { 94 | status, 95 | headers, 96 | }); 97 | }, 98 | }); 99 | 100 | addRoute('/resource-details', (url) => { 101 | const details = getDetails(url.searchParams.get('id')); 102 | return new Response(JSON.stringify(details), { 103 | headers: { 104 | 'Content-Type': 'application/json', 105 | 'Access-Control-Allow-Origin': '*', 106 | }, 107 | }); 108 | }); 109 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2021 Deno Land Inc. All rights reserved. MIT license. 2 | 3 | // deno-lint-ignore-file 4 | 5 | /// 6 | /// 7 | 8 | /** Deno provides extra properties on `import.meta`. These are included here 9 | * to ensure that these are still available when using the Deno namespace in 10 | * conjunction with other type libs, like `dom`. */ 11 | declare interface ImportMeta { 12 | /** A string representation of the fully qualified module URL. */ 13 | url: string; 14 | 15 | /** A flag that indicates if the current module is the main module that was 16 | * called when starting the program under Deno. 17 | * 18 | * ```ts 19 | * if (import.meta.main) { 20 | * // this was loaded as the main module, maybe do some bootstrapping 21 | * } 22 | * ``` 23 | */ 24 | main: boolean; 25 | } 26 | 27 | declare namespace Deno { 28 | export const env: { 29 | /** Retrieve the value of an environment variable. Returns undefined if that 30 | * key doesn't exist. 31 | * 32 | * ```ts 33 | * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice" 34 | * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "Undefined" 35 | * ``` 36 | */ 37 | get(key: string): string | undefined; 38 | 39 | /** Set the value of an environment variable. 40 | * 41 | * ```ts 42 | * Deno.env.set("SOME_VAR", "Value")); 43 | * Deno.env.get("SOME_VAR"); // outputs "Value" 44 | * ``` 45 | */ 46 | set(key: string, value: string): void; 47 | 48 | /** Delete the value of an environment variable. 49 | * 50 | * ```ts 51 | * Deno.env.set("SOME_VAR", "Value")); 52 | * Deno.env.delete("SOME_VAR"); // outputs "Undefined" 53 | * ``` 54 | */ 55 | delete(key: string): void; 56 | 57 | /** Returns a snapshot of the environment variables at invocation. 58 | * 59 | * ```ts 60 | * Deno.env.set("TEST_VAR", "A"); 61 | * const myEnv = Deno.env.toObject(); 62 | * console.log(myEnv.SHELL); 63 | * Deno.env.set("TEST_VAR", "B"); 64 | * console.log(myEnv.TEST_VAR); // outputs "A" 65 | * ``` 66 | */ 67 | toObject(): { [index: string]: string }; 68 | }; 69 | 70 | /** Build related information. */ 71 | export const build: { 72 | /** The LLVM target triple */ 73 | target: string; 74 | /** Instruction set architecture */ 75 | arch: "x86_64"; 76 | /** Operating system */ 77 | os: "darwin" | "linux" | "windows"; 78 | /** Computer vendor */ 79 | vendor: string; 80 | /** Optional environment */ 81 | env?: string; 82 | }; 83 | 84 | /** Reflects the `NO_COLOR` environment variable. This is always set to `true` 85 | * on Deno Deploy, as the logs page supports ANSI colors. 86 | * 87 | * See: https://no-color.org/ */ 88 | export const noColor: boolean; 89 | 90 | export interface InspectOptions { 91 | /** Stylize output with ANSI colors. Defaults to false. */ 92 | colors?: boolean; 93 | /** Try to fit more than one entry of a collection on the same line. 94 | * Defaults to true. */ 95 | compact?: boolean; 96 | /** Traversal depth for nested objects. Defaults to 4. */ 97 | depth?: number; 98 | /** The maximum number of iterable entries to print. Defaults to 100. */ 99 | iterableLimit?: number; 100 | /** Show a Proxy's target and handler. Defaults to false. */ 101 | showProxy?: boolean; 102 | /** Sort Object, Set and Map entries by key. Defaults to false. */ 103 | sorted?: boolean; 104 | /** Add a trailing comma for multiline collections. Defaults to false. */ 105 | trailingComma?: boolean; 106 | /*** Evaluate the result of calling getters. Defaults to false. */ 107 | getters?: boolean; 108 | /** Show an object's non-enumerable properties. Defaults to false. */ 109 | showHidden?: boolean; 110 | } 111 | 112 | /** Converts the input into a string that has the same format as printed by 113 | * `console.log()`. 114 | * 115 | * ```ts 116 | * const obj = {}; 117 | * obj.propA = 10; 118 | * obj.propB = "hello"; 119 | * const objAsString = Deno.inspect(obj); // { propA: 10, propB: "hello" } 120 | * console.log(obj); // prints same value as objAsString, e.g. { propA: 10, propB: "hello" } 121 | * ``` 122 | * 123 | * You can also register custom inspect functions, via the `customInspect` Deno 124 | * symbol on objects, to control and customize the output. 125 | * 126 | * ```ts 127 | * class A { 128 | * x = 10; 129 | * y = "hello"; 130 | * [Deno.customInspect](): string { 131 | * return "x=" + this.x + ", y=" + this.y; 132 | * } 133 | * } 134 | * ``` 135 | * 136 | * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello" 137 | * console.log(inStringFormat); // prints "x=10, y=hello" 138 | * 139 | * Finally, you can also specify the depth to which it will format. 140 | * 141 | * Deno.inspect({a: {b: {c: {d: 'hello'}}}}, {depth: 2}); // { a: { b: [Object] } } 142 | * 143 | */ 144 | export function inspect(value: unknown, options?: InspectOptions): string; 145 | 146 | export interface NetAddr { 147 | transport: "tcp" | "udp"; 148 | hostname: string; 149 | port: number; 150 | } 151 | 152 | export type Addr = NetAddr; 153 | 154 | export interface Reader { 155 | /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number of 156 | * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error 157 | * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may 158 | * use all of `p` as scratch space during the call. If some data is 159 | * available but not `p.byteLength` bytes, `read()` conventionally resolves 160 | * to what is available instead of waiting for more. 161 | * 162 | * When `read()` encounters end-of-file condition, it resolves to EOF 163 | * (`null`). 164 | * 165 | * When `read()` encounters an error, it rejects with an error. 166 | * 167 | * Callers should always process the `n` > `0` bytes returned before 168 | * considering the EOF (`null`). Doing so correctly handles I/O errors that 169 | * happen after reading some bytes and also both of the allowed EOF 170 | * behaviors. 171 | * 172 | * Implementations should not retain a reference to `p`. 173 | * 174 | * Use iter() from https://deno.land/std/io/util.ts to turn a Reader into an 175 | * AsyncIterator. 176 | */ 177 | read(p: Uint8Array): Promise; 178 | } 179 | 180 | export interface Writer { 181 | /** Writes `p.byteLength` bytes from `p` to the underlying data stream. It 182 | * resolves to the number of bytes written from `p` (`0` <= `n` <= 183 | * `p.byteLength`) or reject with the error encountered that caused the 184 | * write to stop early. `write()` must reject with a non-null error if 185 | * would resolve to `n` < `p.byteLength`. `write()` must not modify the 186 | * slice data, even temporarily. 187 | * 188 | * Implementations should not retain a reference to `p`. 189 | */ 190 | write(p: Uint8Array): Promise; 191 | } 192 | 193 | export interface Closer { 194 | close(): void; 195 | } 196 | 197 | export interface Conn extends Reader, Writer, Closer { 198 | /** The local address of the connection. */ 199 | readonly localAddr: Addr; 200 | /** The remote address of the connection. */ 201 | readonly remoteAddr: Addr; 202 | /** The resource ID of the connection. */ 203 | readonly rid: number; 204 | /** Shuts down (`shutdown(2)`) the write side of the connection. Most 205 | * callers should just use `close()`. */ 206 | closeWrite(): Promise; 207 | } 208 | 209 | /** A generic network listener for stream-oriented protocols. */ 210 | export interface Listener extends AsyncIterable { 211 | /** Waits for and resolves to the next connection to the `Listener`. */ 212 | accept(): Promise; 213 | /** Close closes the listener. Any pending accept promises will be rejected 214 | * with errors. */ 215 | close(): void; 216 | /** Return the address of the `Listener`. */ 217 | readonly addr: Addr; 218 | 219 | /** Return the rid of the `Listener`. */ 220 | readonly rid: number; 221 | 222 | [Symbol.asyncIterator](): AsyncIterableIterator; 223 | } 224 | 225 | export interface ListenOptions { 226 | /** The port to listen on. */ 227 | port: number; 228 | /** A literal IP address or host name that can be resolved to an IP address. 229 | * If not specified, defaults to `0.0.0.0`. */ 230 | hostname?: string; 231 | } 232 | 233 | /** Listen announces on the local transport address. 234 | * 235 | * ```ts 236 | * const listener1 = Deno.listen({ port: 80 }) 237 | * const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 }) 238 | * const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 }); 239 | * const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" }); 240 | * ``` 241 | * 242 | * Requires `allow-net` permission. */ 243 | export function listen( 244 | options: ListenOptions & { transport?: "tcp" }, 245 | ): Listener; 246 | 247 | export interface RequestEvent { 248 | readonly request: Request; 249 | respondWith(r: Response | Promise): Promise; 250 | } 251 | 252 | export interface HttpConn extends AsyncIterable { 253 | readonly rid: number; 254 | 255 | nextRequest(): Promise; 256 | close(): void; 257 | } 258 | 259 | /** 260 | * Services HTTP requests given a TCP or TLS socket. 261 | * 262 | * ```ts 263 | * const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" }); 264 | * const httpConn = Deno.serveHttp(conn); 265 | * const e = await httpConn.nextRequest(); 266 | * if (e) { 267 | * e.respondWith(new Response("Hello World")); 268 | * } 269 | * ``` 270 | * 271 | * If `httpConn.nextRequest()` encounters an error or returns `null` 272 | * then the underlying HttpConn resource is closed automatically. 273 | * 274 | * Alternatively, you can also use the Async Iterator approach: 275 | * 276 | * ```ts 277 | * async function handleHttp(conn: Deno.Conn) { 278 | * for await (const e of Deno.serveHttp(conn)) { 279 | * e.respondWith(new Response("Hello World")); 280 | * } 281 | * } 282 | * 283 | * for await (const conn of Deno.listen({ port: 80 })) { 284 | * handleHttp(conn); 285 | * } 286 | * ``` 287 | */ 288 | export function serveHttp(conn: Conn): HttpConn; 289 | 290 | export interface WebSocketUpgrade { 291 | response: Response; 292 | socket: WebSocket; 293 | } 294 | 295 | export interface UpgradeWebSocketOptions { 296 | protocol?: string; 297 | } 298 | 299 | /** Used to upgrade an incoming HTTP request to a WebSocket. 300 | * 301 | * Given a request, returns a pair of WebSocket and Response. The original 302 | * request must be responded to with the returned response for the websocket 303 | * upgrade to be successful. 304 | * 305 | * ```ts 306 | * const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" }); 307 | * const httpConn = Deno.serveHttp(conn); 308 | * const e = await httpConn.nextRequest(); 309 | * if (e) { 310 | * const { socket, response } = Deno.upgradeWebSocket(e.request); 311 | * socket.onopen = () => { 312 | * socket.send("Hello World!"); 313 | * }; 314 | * socket.onmessage = (e) => { 315 | * console.log(e.data); 316 | * socket.close(); 317 | * }; 318 | * socket.onclose = () => console.log("WebSocket has been closed."); 319 | * socket.onerror = (e) => console.error("WebSocket error:", e.message); 320 | * e.respondWith(response); 321 | * } 322 | * ``` 323 | * 324 | * If the request body is disturbed (read from) before the upgrade is 325 | * completed, upgrading fails. 326 | * 327 | * This operation does not yet consume the request or open the websocket. This 328 | * only happens once the returned response has been passed to `respondWith`. 329 | */ 330 | export function upgradeWebSocket( 331 | request: Request, 332 | options?: UpgradeWebSocketOptions, 333 | ): WebSocketUpgrade; 334 | 335 | /** Asynchronously reads and returns the entire contents of a file as utf8 336 | * encoded string. Reading a directory throws an error. 337 | * 338 | * ```ts 339 | * const data = await Deno.readTextFile("hello.txt"); 340 | * console.log(data); 341 | * ``` 342 | */ 343 | export function readTextFile(path: string | URL): Promise; 344 | 345 | /** Reads and resolves to the entire contents of a file as an array of bytes. 346 | * `TextDecoder` can be used to transform the bytes to string if required. 347 | * Reading a directory returns an empty data array. 348 | * 349 | * ```ts 350 | * const decoder = new TextDecoder("utf-8"); 351 | * const data = await Deno.readFile("hello.txt"); 352 | * console.log(decoder.decode(data)); 353 | * ``` 354 | */ 355 | export function readFile(path: string | URL): Promise; 356 | 357 | /** 358 | * Return a string representing the current working directory. 359 | * 360 | * If the current directory can be reached via multiple paths (due to symbolic 361 | * links), `cwd()` may return any one of them. 362 | * 363 | * ```ts 364 | * const currentWorkingDirectory = Deno.cwd(); 365 | * ``` 366 | * 367 | * Throws `Deno.errors.NotFound` if directory not available. 368 | */ 369 | export function cwd(): string; 370 | } 371 | 372 | // Copyright 2018-2021 Deno Land Inc. All rights reserved. MIT license. 373 | 374 | // deno-lint-ignore-file 375 | 376 | // Documentation partially adapted from [MDN](https://developer.mozilla.org/), 377 | // by Mozilla Contributors, which is licensed under CC-BY-SA 2.5. 378 | 379 | /// 380 | /// 381 | 382 | declare class DOMException extends Error { 383 | constructor(message?: string, name?: string); 384 | readonly name: string; 385 | readonly message: string; 386 | readonly code: number; 387 | } 388 | 389 | interface EventInit { 390 | bubbles?: boolean; 391 | cancelable?: boolean; 392 | composed?: boolean; 393 | } 394 | 395 | /** An event which takes place in the DOM. */ 396 | declare class Event { 397 | constructor(type: string, eventInitDict?: EventInit); 398 | /** Returns true or false depending on how event was initialized. True if 399 | * event goes through its target's ancestors in reverse tree order, and 400 | * false otherwise. */ 401 | readonly bubbles: boolean; 402 | cancelBubble: boolean; 403 | /** Returns true or false depending on how event was initialized. Its return 404 | * value does not always carry meaning, but true can indicate that part of the 405 | * operation during which event was dispatched, can be canceled by invoking 406 | * the preventDefault() method. */ 407 | readonly cancelable: boolean; 408 | /** Returns true or false depending on how event was initialized. True if 409 | * event invokes listeners past a ShadowRoot node that is the root of its 410 | * target, and false otherwise. */ 411 | readonly composed: boolean; 412 | /** Returns the object whose event listener's callback is currently being 413 | * invoked. */ 414 | readonly currentTarget: EventTarget | null; 415 | /** Returns true if preventDefault() was invoked successfully to indicate 416 | * cancellation, and false otherwise. */ 417 | readonly defaultPrevented: boolean; 418 | /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, 419 | * AT_TARGET, and BUBBLING_PHASE. */ 420 | readonly eventPhase: number; 421 | /** Returns true if event was dispatched by the user agent, and false 422 | * otherwise. */ 423 | readonly isTrusted: boolean; 424 | /** Returns the object to which event is dispatched (its target). */ 425 | readonly target: EventTarget | null; 426 | /** Returns the event's timestamp as the number of milliseconds measured 427 | * relative to the time origin. */ 428 | readonly timeStamp: number; 429 | /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ 430 | readonly type: string; 431 | /** Returns the invocation target objects of event's path (objects on which 432 | * listeners will be invoked), except for any nodes in shadow trees of which 433 | * the shadow root's mode is "closed" that are not reachable from event's 434 | * currentTarget. */ 435 | composedPath(): EventTarget[]; 436 | /** If invoked when the cancelable attribute value is true, and while 437 | * executing a listener for the event with passive set to false, signals to 438 | * the operation that caused event to be dispatched that it needs to be 439 | * canceled. */ 440 | preventDefault(): void; 441 | /** Invoking this method prevents event from reaching any registered event 442 | * listeners after the current one finishes running and, when dispatched in a 443 | * tree, also prevents event from reaching any other objects. */ 444 | stopImmediatePropagation(): void; 445 | /** When dispatched in a tree, invoking this method prevents event from 446 | * reaching any objects other than the current object. */ 447 | stopPropagation(): void; 448 | readonly AT_TARGET: number; 449 | readonly BUBBLING_PHASE: number; 450 | readonly CAPTURING_PHASE: number; 451 | readonly NONE: number; 452 | static readonly AT_TARGET: number; 453 | static readonly BUBBLING_PHASE: number; 454 | static readonly CAPTURING_PHASE: number; 455 | static readonly NONE: number; 456 | } 457 | 458 | /** 459 | * EventTarget is a DOM interface implemented by objects that can receive events 460 | * and may have listeners for them. 461 | */ 462 | declare class EventTarget { 463 | /** Appends an event listener for events whose type attribute value is type. 464 | * The callback argument sets the callback that will be invoked when the event 465 | * is dispatched. 466 | * 467 | * The options argument sets listener-specific options. For compatibility this 468 | * can be a boolean, in which case the method behaves exactly as if the value 469 | * was specified as options's capture. 470 | * 471 | * When set to true, options's capture prevents callback from being invoked 472 | * when the event's eventPhase attribute value is BUBBLING_PHASE. When false 473 | * (or not present), callback will not be invoked when event's eventPhase 474 | * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if 475 | * event's eventPhase attribute value is AT_TARGET. 476 | * 477 | * When set to true, options's passive indicates that the callback will not 478 | * cancel the event by invoking preventDefault(). This is used to enable 479 | * performance optimizations described in § 2.8 Observing event listeners. 480 | * 481 | * When set to true, options's once indicates that the callback will only be 482 | * invoked once after which the event listener will be removed. 483 | * 484 | * The event listener is appended to target's event listener list and is not 485 | * appended if it has the same type, callback, and capture. */ 486 | addEventListener( 487 | type: string, 488 | listener: EventListenerOrEventListenerObject | null, 489 | options?: boolean | AddEventListenerOptions, 490 | ): void; 491 | /** Dispatches a synthetic event event to target and returns true if either 492 | * event's cancelable attribute value is false or its preventDefault() method 493 | * was not invoked, and false otherwise. */ 494 | dispatchEvent(event: Event): boolean; 495 | /** Removes the event listener in target's event listener list with the same 496 | * type, callback, and options. */ 497 | removeEventListener( 498 | type: string, 499 | callback: EventListenerOrEventListenerObject | null, 500 | options?: EventListenerOptions | boolean, 501 | ): void; 502 | [Symbol.toStringTag]: string; 503 | } 504 | 505 | interface EventListener { 506 | (evt: Evt): void | Promise; 507 | } 508 | 509 | interface EventListenerObject { 510 | handleEvent(evt: Evt): void | Promise; 511 | } 512 | 513 | declare type EventListenerOrEventListenerObject = 514 | | EventListener 515 | | EventListenerObject; 516 | 517 | interface AddEventListenerOptions extends EventListenerOptions { 518 | once?: boolean; 519 | passive?: boolean; 520 | } 521 | 522 | interface EventListenerOptions { 523 | capture?: boolean; 524 | } 525 | 526 | interface ProgressEventInit extends EventInit { 527 | lengthComputable?: boolean; 528 | loaded?: number; 529 | total?: number; 530 | } 531 | 532 | /** Events measuring progress of an underlying process, like an HTTP request 533 | * (for an XMLHttpRequest, or the loading of the underlying resource of an 534 | * ,