diff options
author | Bartek Iwańczuk <biwanczuk@gmail.com> | 2021-07-20 16:25:36 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-07-20 16:25:36 +0200 |
commit | d744c0c6d9a557bbaa2a23571ffb3acabf19c35a (patch) | |
tree | 6f7fb8a71b786e79c48f4b2c11a5a9ca988717e8 /docs/runtime | |
parent | 9b9becf1ae256b645e37a7eecf3441f3ae4b8ea5 (diff) |
chore: move docs to separate repository
Diffstat (limited to 'docs/runtime')
-rw-r--r-- | docs/runtime/compiler_apis.md | 4 | ||||
-rw-r--r-- | docs/runtime/http_server_apis.md | 258 | ||||
-rw-r--r-- | docs/runtime/location_api.md | 76 | ||||
-rw-r--r-- | docs/runtime/permission_apis.md | 186 | ||||
-rw-r--r-- | docs/runtime/program_lifecycle.md | 79 | ||||
-rw-r--r-- | docs/runtime/stability.md | 32 | ||||
-rw-r--r-- | docs/runtime/web_platform_apis.md | 97 | ||||
-rw-r--r-- | docs/runtime/web_storage_api.md | 39 | ||||
-rw-r--r-- | docs/runtime/workers.md | 251 |
9 files changed, 0 insertions, 1022 deletions
diff --git a/docs/runtime/compiler_apis.md b/docs/runtime/compiler_apis.md deleted file mode 100644 index b4a9f4377..000000000 --- a/docs/runtime/compiler_apis.md +++ /dev/null @@ -1,4 +0,0 @@ -## Compiler APIs - -> ℹ️ This section has been moved to -> [TypeScript Runtime APIs](../typescript/runtime.md). diff --git a/docs/runtime/http_server_apis.md b/docs/runtime/http_server_apis.md deleted file mode 100644 index 0d20c49ee..000000000 --- a/docs/runtime/http_server_apis.md +++ /dev/null @@ -1,258 +0,0 @@ -## HTTP Server APIs - -As of Deno 1.9 and later, _native_ HTTP server APIs were introduced which allow -users to create robust and performant web servers in Deno. - -The API tries to leverage as much of the web standards as is possible as well as -tries to be simple and straight forward. - -> ℹ️ The APIs are currently unstable, meaning they can change in the future in -> breaking ways and should be carefully considered before using in production -> code. They require the `--unstable` flag to make them available. - -### Listening for a connection - -In order to accept requests, first you need to listen for a connection on a -network port. To do this in Deno, you use `Deno.listen()`: - -```ts -const server = Deno.listen({ port: 8080 }); -``` - -> ℹ️ When supplying a port, Deno assumes you are going to listen on a TCP socket -> as well as bind to the localhost. You can specify `transport: "tcp"` to be -> more explicit as well as provide an IP address or hostname in the `hostname` -> property as well. - -If there is an issue with opening the network port, `Deno.listen()` will throw, -so often in a server sense, you will want to wrap it in the `try ... catch` -block in order to handle exceptions, like the port already being in use. - -You can also listen for a TLS connection (e.g. HTTPS) using `Deno.listenTls()`: - -```ts -const server = Deno.listenTls({ - port: 8443, - certFile: "localhost.crt", - keyFile: "localhost.key", - alpnProtocols: ["h2", "http/1.1"], -}); -``` - -The `certFile` and `keyFile` options are required and point to the appropriate -certificate and key files for the server. They are relative to the CWD for Deno. -The `alpnProtocols` property is optional, but if you want to be able to support -HTTP/2 on the server, you add the protocols here, as the protocol negotiation -happens during the TLS negotiation with the client and server. - -> ℹ️ Generating SSL certificates is outside of the scope of this documentation. -> There are many resources on the web which address this. - -### Handling connections - -Once we are listening for a connection, we need to handle the connection. The -return value of `Deno.listen()` or `Deno.listenTls()` is a `Deno.Listener` which -is an async iterable which yields up `Deno.Conn` connections as well as provide -a couple methods for handling connections. - -To use it as an async iterable we would do something like this: - -```ts -const server = Deno.listen({ port: 8080 }); - -for await (const conn of server) { - // ...handle the connection... -} -``` - -Every connection made would yielded up a `Deno.Conn` assigned to `conn`. Then -further processing can be applied to the connection. - -There is also the `.accept()` method on the listener which can be used: - -```ts -const server = Deno.listen({ port: 8080 }); - -while (true) { - try { - const conn = await server.accept(); - // ... handle the connection ... - } catch (err) { - // The listener has closed - break; - } -} -``` - -Whether using the async iterator or the `.accept()` method, exceptions can be -thrown and robust production code should handle these using `try ... catch` -blocks. Especially when it comes to accepting TLS connections, there can be many -conditions, like invalid or unknown certificates which can be surfaced on the -listener and might need handling in the user code. - -A listener also has a `.close()` method which can be used to close the listener. - -### Serving HTTP - -Once a connection is accepted, you can use `Deno.serveHttp()` to handle HTTP -requests and responses on the connection. `Deno.serveHttp()` returns a -`Deno.HttpConn`. A `Deno.HttpConn` is like a `Deno.Listener` in that requests -the connection receives from the client are asynchronously yielded up as a -`Deno.RequestEvent`. - -To deal with HTTP requests as async iterable it would look something like this: - -```ts -const server = Deno.listen({ port: 8080 }); - -for await (const conn of server) { - (async () => { - const httpConn = Deno.serveHttp(conn); - for await (const requestEvent of httpConn) { - // ... handle requestEvent ... - } - })(); -} -``` - -The `Deno.HttpConn` also has the method `.nextRequest()` which can be used to -await the next request. It would look something like this: - -```ts -const server = Deno.listen({ port: 8080 }); - -while (true) { - try { - const conn = await server.accept(); - (async () => { - const httpConn = Deno.serveHttp(conn); - while (true) { - try { - const requestEvent = await httpConn.nextRequest(); - // ... handle requestEvent ... - } catch (err) { - // the connection has finished - break; - } - } - })(); - } catch (err) { - // The listener has closed - break; - } -} -``` - -Note that in both cases we are using an IIFE to create an inner function to deal -with each connection. If we awaited the HTTP requests in the same function scope -as the one we were receiving the connections, we would be blocking accepting -additional connections, which would make it seem that our server was "frozen". -In practice, it might make more sense to have a separate function all together: - -```ts -async function handle(conn: Deno.Conn) { - const httpConn = Deno.serveHttp(conn); - for await (const requestEvent of httpConn) { - // ... handle requestEvent - } -} - -const server = Deno.listen({ port: 8080 }); - -for await (const conn of server) { - handle(conn); -} -``` - -In the examples from this point on, we will focus on what would occur within an -example `handle()` function and remove the listening and connection -"boilerplate". - -### HTTP Requests and Responses - -HTTP requests and responses in Deno are essentially the inverse of web standard -[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). The -Deno HTTP Server API and the Fetch API leverage the -[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and -[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object -classes. So if you are familiar with the Fetch API you just need to flip them -around in your mind and now it is a server API. - -As mentioned above, a `Deno.HttpConn` asynchronously yields up -`Deno.RequestEvent`s. These request events contain a `.request` property and a -`.respondWith()` method. - -The `.request` property is an instance of the `Request` class with the -information about the request. For example, if we wanted to know what URL path -was being requested, we would do something like this: - -```ts -async function handle(conn: Deno.Conn) { - const httpConn = Deno.serveHttp(conn); - for await (const requestEvent of httpConn) { - const url = new URL(requestEvent.request.url); - console.log(`path: ${url.path}`); - } -} -``` - -The `.respondWith()` method is how we complete a request. The method takes -either a `Response` object or a `Promise` which resolves with a `Response` -object. Responding with a basic "hello world" would look like this: - -```ts -async function handle(conn: Deno.Conn) { - const httpConn = Deno.serveHttp(conn); - for await (const requestEvent of httpConn) { - await requestEvent.respondWith( - new Response("hello world", { - status: 200, - }), - ); - } -} -``` - -Note that we awaited the `.respondWith()` method. It isn't required, but in -practice any errors in processing the response will cause the promise returned -from the method to be rejected, like if the client disconnected before all the -response could be sent. While there may not be anything your application needs -to do, not handling the rejection will cause an "unhandled rejection" to occur -which will terminate the Deno process, which isn't so good for a server. In -addition, you might want to await the promise returned in order to determine -when to do any cleanup from for the request/response cycle. - -The web standard `Response` object is pretty powerful, allowing easy creation of -complex and rich responses to a client, and Deno strives to provide a `Response` -object that as closely matches the web standard as possible, so if you are -wondering how to send a particular response, checkout out the documentation for -the web standard -[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). - -### HTTP/2 Support - -HTTP/2 support is effectively transparent within the Deno runtime. Typically -HTTP/2 is negotiated between a client and a server during the TLS connection -setup via -[ALPN](https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation). To -enable this, you need to provide the protocols you want to support when you -start listening via the `alpnProtocols` property. This will enable the -negotiation to occur when the connection is made. For example: - -```ts -const server = Deno.listenTls({ - port: 8443, - certFile: "localhost.crt", - keyFile: "localhost.key", - alpnProtocols: ["h2", "http/1.1"], -}); -``` - -The protocols are provided in order of preference. In practice, the only two -protocols that are supported currently are HTTP/2 and HTTP/1.1 which are -expressed as `h2` and `http/1.1`. - -Currently Deno does not support upgrading a plain-text HTTP/1.1 connection to an -HTTP/2 cleartext connection via the `Upgrade` header (see: -[#10275](https://github.com/denoland/deno/issues/10275)), so therefore HTTP/2 -support is only available via a TLS/HTTPS connection. diff --git a/docs/runtime/location_api.md b/docs/runtime/location_api.md deleted file mode 100644 index 6e7341828..000000000 --- a/docs/runtime/location_api.md +++ /dev/null @@ -1,76 +0,0 @@ -## Location API - -Deno supports the -[`location`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) -global from the web. Please read on. - -### Location flag - -There is no "web page" whose URL we can use for a location in a Deno process. We -instead allow users to emulate a document location by specifying one on the CLI -using the `--location` flag. It can be a `http` or `https` URL. - -```ts -// deno run --location https://example.com/path main.ts - -console.log(location.href); -// "https://example.com/path" -``` - -You must pass `--location <href>` for this to work. If you don't, any access to -the `location` global will throw an error. - -```ts -// deno run main.ts - -console.log(location.href); -// error: Uncaught ReferenceError: Access to "location", run again with --location <href>. -``` - -Setting `location` or any of its fields will normally cause navigation in -browsers. This is not applicable in Deno, so it will throw in this situation. - -```ts -// deno run --location https://example.com/path main.ts - -location.pathname = "./foo"; -// error: Uncaught NotSupportedError: Cannot set "location.pathname". -``` - -### Extended usage - -On the web, resource resolution (excluding modules) typically uses the value of -`location.href` as the root on which to base any relative URLs. This affects -some web APIs adopted by Deno. - -#### Fetch API - -```ts -// deno run --location https://api.github.com/ --allow-net main.ts - -const response = await fetch("./orgs/denoland"); -// Fetches "https://api.github.com/orgs/denoland". -``` - -The `fetch()` call above would throw if the `--location` flag was not passed, -since there is no web-analogous location to base it onto. - -#### Worker modules - -```ts -// deno run --location https://example.com/index.html --allow-net main.ts - -const worker = new Worker("./workers/hello.ts", { type: "module" }); -// Fetches worker module at "https://example.com/workers/hello.ts". -``` - -### Only use if necessary - -For the above use cases, it is preferable to pass URLs in full rather than -relying on `--location`. You can manually base a relative URL using the `URL` -constructor if needed. - -The `--location` flag is intended for those who have some specific purpose in -mind for emulating a document location and are aware that this will only work at -application-level. However, you may also use it to silence errors from a -dependency which is frivolously accessing the `location` global. diff --git a/docs/runtime/permission_apis.md b/docs/runtime/permission_apis.md deleted file mode 100644 index a71558526..000000000 --- a/docs/runtime/permission_apis.md +++ /dev/null @@ -1,186 +0,0 @@ -## Permission APIs - -Permissions are granted from the CLI when running the `deno` command. User code -will often assume its own set of required permissions, but there is no guarantee -during execution that the set of _granted_ permissions will align with this. - -In some cases, ensuring a fault-tolerant program requires a way to interact with -the permission system at runtime. - -### Permission descriptors - -On the CLI, read permission for `/foo/bar` is represented as -`--allow-read=/foo/bar`. In runtime JS, it is represented as the following: - -```ts -const desc = { name: "read", path: "/foo/bar" } as const; -``` - -Other examples: - -```ts -// Global write permission. -const desc1 = { name: "write" } as const; - -// Write permission to `$PWD/foo/bar`. -const desc2 = { name: "write", path: "foo/bar" } as const; - -// Global net permission. -const desc3 = { name: "net" } as const; - -// Net permission to 127.0.0.1:8000. -const desc4 = { name: "net", host: "127.0.0.1:8000" } as const; - -// High-resolution time permission. -const desc5 = { name: "hrtime" } as const; -``` - -### Query permissions - -Check, by descriptor, if a permission is granted or not. - -```ts -// deno run --allow-read=/foo main.ts - -const desc1 = { name: "read", path: "/foo" } as const; -console.log(await Deno.permissions.query(desc1)); -// PermissionStatus { state: "granted" } - -const desc2 = { name: "read", path: "/foo/bar" } as const; -console.log(await Deno.permissions.query(desc2)); -// PermissionStatus { state: "granted" } - -const desc3 = { name: "read", path: "/bar" } as const; -console.log(await Deno.permissions.query(desc3)); -// PermissionStatus { state: "prompt" } -``` - -### Permission states - -A permission state can be either "granted", "prompt" or "denied". Permissions -which have been granted from the CLI will query to `{ state: "granted" }`. Those -which have not been granted query to `{ state: "prompt" }` by default, while -`{ state: "denied" }` reserved for those which have been explicitly refused. -This will come up in [Request permissions](#request-permissions). - -### Permission strength - -The intuitive understanding behind the result of the second query in -[Query permissions](#query-permissions) is that read access was granted to -`/foo` and `/foo/bar` is within `/foo` so `/foo/bar` is allowed to be read. - -We can also say that `desc1` is -_[stronger than](https://www.w3.org/TR/permissions/#ref-for-permissiondescriptor-stronger-than)_ -`desc2`. This means that for any set of CLI-granted permissions: - -1. If `desc1` queries to `{ state: "granted" }` then so must `desc2`. -2. If `desc2` queries to `{ state: "denied" }` then so must `desc1`. - -More examples: - -```ts -const desc1 = { name: "write" } as const; -// is stronger than -const desc2 = { name: "write", path: "/foo" } as const; - -const desc3 = { name: "net", host: "127.0.0.1" } as const; -// is stronger than -const desc4 = { name: "net", host: "127.0.0.1:8000" } as const; -``` - -### Request permissions - -Request an ungranted permission from the user via CLI prompt. - -```ts -// deno run main.ts - -const desc1 = { name: "read", path: "/foo" } as const; -const status1 = await Deno.permissions.request(desc1); -// ⚠️ Deno requests read access to "/foo". Grant? [g/d (g = grant, d = deny)] g -console.log(status1); -// PermissionStatus { state: "granted" } - -const desc2 = { name: "read", path: "/bar" } as const; -const status2 = await Deno.permissions.request(desc2); -// ⚠️ Deno requests read access to "/bar". Grant? [g/d (g = grant, d = deny)] d -console.log(status2); -// PermissionStatus { state: "denied" } -``` - -If the current permission state is "prompt", a prompt will appear on the user's -terminal asking them if they would like to grant the request. The request for -`desc1` was granted so its new status is returned and execution will continue as -if `--allow-read=/foo` was specified on the CLI. The request for `desc2` was -denied so its permission state is downgraded from "prompt" to "denied". - -If the current permission state is already either "granted" or "denied", the -request will behave like a query and just return the current status. This -prevents prompts both for already granted permissions and previously denied -requests. - -### Revoke permissions - -Downgrade a permission from "granted" to "prompt". - -```ts -// deno run --allow-read=/foo main.ts - -const desc = { name: "read", path: "/foo" } as const; -console.log(await Deno.permissions.revoke(desc)); -// PermissionStatus { state: "prompt" } -``` - -However, what happens when you try to revoke a permission which is _partial_ to -one granted on the CLI? - -```ts -// deno run --allow-read=/foo main.ts - -const desc = { name: "read", path: "/foo/bar" } as const; -console.log(await Deno.permissions.revoke(desc)); -// PermissionStatus { state: "granted" } -``` - -It was not revoked. - -To understand this behaviour, imagine that Deno stores an internal set of -_explicitly granted permission descriptors_. Specifying `--allow-read=/foo,/bar` -on the CLI initializes this set to: - -```ts -[ - { name: "read", path: "/foo" }, - { name: "read", path: "/bar" }, -]; -``` - -Granting a runtime request for `{ name: "write", path: "/foo" }` updates the set -to: - -```ts -[ - { name: "read", path: "/foo" }, - { name: "read", path: "/bar" }, - { name: "write", path: "/foo" }, -]; -``` - -Deno's permission revocation algorithm works by removing every element from this -set which the argument permission descriptor is _stronger than_. So to ensure -`desc` is not longer granted, pass an argument descriptor _stronger than_ -whichever _explicitly granted permission descriptor_ is _stronger than_ `desc`. - -```ts -// deno run --allow-read=/foo main.ts - -const desc = { name: "read", path: "/foo/bar" } as const; -console.log(await Deno.permissions.revoke(desc)); // Insufficient. -// PermissionStatus { state: "granted" } - -const strongDesc = { name: "read", path: "/foo" } as const; -await Deno.permissions.revoke(strongDesc); // Good. - -console.log(await Deno.permissions.query(desc)); -// PermissionStatus { state: "prompt" } -``` diff --git a/docs/runtime/program_lifecycle.md b/docs/runtime/program_lifecycle.md deleted file mode 100644 index 72e21c4f4..000000000 --- a/docs/runtime/program_lifecycle.md +++ /dev/null @@ -1,79 +0,0 @@ -## Program lifecycle - -Deno supports browser compatible lifecycle events: `load` and `unload`. You can -use these events to provide setup and cleanup code in your program. - -Listeners for `load` events can be asynchronous and will be awaited. Listeners -for `unload` events need to be synchronous. Both events cannot be cancelled. - -Example: - -**main.ts** - -```ts -import "./imported.ts"; - -const handler = (e: Event): void => { - console.log(`got ${e.type} event in event handler (main)`); -}; - -window.addEventListener("load", handler); - -window.addEventListener("unload", handler); - -window.onload = (e: Event): void => { - console.log(`got ${e.type} event in onload function (main)`); -}; - -window.onunload = (e: Event): void => { - console.log(`got ${e.type} event in onunload function (main)`); -}; - -console.log("log from main script"); -``` - -**imported.ts** - -```ts -const handler = (e: Event): void => { - console.log(`got ${e.type} event in event handler (imported)`); -}; - -window.addEventListener("load", handler); -window.addEventListener("unload", handler); - -window.onload = (e: Event): void => { - console.log(`got ${e.type} event in onload function (imported)`); -}; - -window.onunload = (e: Event): void => { - console.log(`got ${e.type} event in onunload function (imported)`); -}; - -console.log("log from imported script"); -``` - -Note that you can use both `window.addEventListener` and -`window.onload`/`window.onunload` to define handlers for events. There is a -major difference between them, let's run the example: - -```shell -$ deno run main.ts -log from imported script -log from main script -got load event in event handler (imported) -got load event in event handler (main) -got load event in onload function (main) -got unload event in event handler (imported) -got unload event in event handler (main) -got unload event in onunload function (main) -``` - -All listeners added using `window.addEventListener` were run, but -`window.onload` and `window.onunload` defined in `main.ts` overrode handlers -defined in `imported.ts`. - -In other words, you can register multiple `window.addEventListener` `"load"` or -`"unload"` events, but only the last loaded `window.onload` or `window.onunload` -event handlers will be executed. It is preferable to use `addEventListener` when -possible for this reason. diff --git a/docs/runtime/stability.md b/docs/runtime/stability.md deleted file mode 100644 index 9cdc1eea8..000000000 --- a/docs/runtime/stability.md +++ /dev/null @@ -1,32 +0,0 @@ -## Stability - -As of Deno 1.0.0, the `Deno` namespace APIs are stable. That means we will -strive to make code working under 1.0.0 continue to work in future versions. - -However, not all of Deno's features are ready for production yet. Features which -are not ready, because they are still in draft phase, are locked behind the -`--unstable` command line flag. - -```shell -deno run --unstable mod_which_uses_unstable_stuff.ts -``` - -Passing this flag does a few things: - -- It enables the use of unstable APIs during runtime. -- It adds the - [`lib.deno.unstable.d.ts`](https://doc.deno.land/https/raw.githubusercontent.com/denoland/deno/main/cli/dts/lib.deno.unstable.d.ts) - file to the list of TypeScript definitions that are used for type checking. - This includes the output of `deno types`. - -You should be aware that many unstable APIs have **not undergone a security -review**, are likely to have **breaking API changes** in the future, and are -**not ready for production**. - -### Standard modules - -Deno's standard modules (https://deno.land/std/) are not yet stable. We -currently version the standard modules differently from the CLI to reflect this. -Note that unlike the `Deno` namespace, the use of the standard modules do not -require the `--unstable` flag (unless the standard module itself makes use of an -unstable Deno feature). diff --git a/docs/runtime/web_platform_apis.md b/docs/runtime/web_platform_apis.md deleted file mode 100644 index 0a1015b68..000000000 --- a/docs/runtime/web_platform_apis.md +++ /dev/null @@ -1,97 +0,0 @@ -# Web Platform APIs - -Deno aims to use web platform APIs (like `fetch`) instead of inventing a new -proprietary API where it makes sense. These APIs generally follow the -specifications and should match the implementation in Chrome and Firefox. In -some cases it makes sense to deviate from the spec slightly, because of the -different security model Deno has. - -Here is a list of web platform APIs Deno implements: - -## `fetch` API - -### Overview - -The `fetch` API can be used to make HTTP requests. It is implemented as -specified in the [WHATWG `fetch` spec](https://fetch.spec.whatwg.org/). - -You can find documentation about this API on -[MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). - -### Spec deviations - -- The Deno user agent does not have a cookie jar. As such, the `set-cookie` - header on a response is not processed, or filtered from the visible response - headers. -- Deno does not follow the same-origin policy, because the Deno user agent - currently does not have the concept of origins, and it does not have a cookie - jar. This means Deno does not need to protect against leaking authenticated - data cross origin. Because of this Deno does not implement the following - sections of the WHATWG `fetch` specification: - - Section `3.1. 'Origin' header`. - - Section `3.2. CORS protocol`. - - Section `3.5. CORB`. - - Section `3.6. 'Cross-Origin-Resource-Policy' header`. - - `Atomic HTTP redirect handling`. - - The `opaqueredirect` response type. -- A `fetch` with a `redirect` mode of `manual` will return a `basic` response - rather than an `opaqueredirect` response. - -## `CustomEvent`, `EventTarget` and `EventListener` - -### Overview - -The DOM Event API can be used to dispatch and listen to events happening in an -application. It is implemented as specified in the -[WHATWG DOM spec](https://dom.spec.whatwg.org/#events). - -You can find documentation about this API on -[MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget). - -### Spec deviations - -- Events do not bubble, because Deno does not have a DOM hierarchy, so there is - no tree for Events to bubble/capture through. - -## Web Worker API - -### Overview - -The WebWorker API can be used to executing code in a separate thread. It is -implemented as specified in the -[WHATWG HTML spec](https://html.spec.whatwg.org/multipage/workers.html#workers). - -You can find documentation about this API on -[MDN](https://developer.mozilla.org/en-US/docs/Web/API/Worker). - -### Spec deviations - -- Currently creating workers from blob URLs is not supported. -- Currently posted data is serialized to JSON instead of structured cloning. -- Currently object ownership cannot be transferred between workers. - -## Other APIs - -- [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) -- [Console](https://developer.mozilla.org/en-US/docs/Web/API/Console) -- [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) -- [Performance](https://developer.mozilla.org/en-US/docs/Web/API/Performance) -- [setTimeout, setInterval, clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) -- [Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) -- [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) -- [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) -- [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) - ---- - -## Typings - -The TypeScript definitions for the implemented web APIs can be found in the -[`lib.deno.shared_globals.d.ts`](https://github.com/denoland/deno/blob/$CLI_VERSION/cli/dts/lib.deno.shared_globals.d.ts) -and -[`lib.deno.window.d.ts`](https://github.com/denoland/deno/blob/$CLI_VERSION/cli/dts/lib.deno.window.d.ts) -files. - -Definitions that are specific to workers can be found in the -[`lib.deno.worker.d.ts`](https://github.com/denoland/deno/blob/$CLI_VERSION/cli/dts/lib.deno.worker.d.ts) -file. diff --git a/docs/runtime/web_storage_api.md b/docs/runtime/web_storage_api.md deleted file mode 100644 index 34a119067..000000000 --- a/docs/runtime/web_storage_api.md +++ /dev/null @@ -1,39 +0,0 @@ -## Web Storage API - -As of Deno 1.10, the Web Storage API (`localStorage` & `sessionStorage`) was -introduced, which through `localStorage` allows persistent storage, whereas -`sessionStorage` is a non-persistent memory-based storage. - -To use persistent storage, you need to pass the `--location` flag. The location -for persistent storage is listed in `deno info`, and additionally passing the -`--location` will give you the path for the specified origin. - -To learn more about the Web Storage APIs, visit the -[MDN page on Web Storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage). - -### Example - -The following snippet accesses the local storage bucket for the current origin -and adds a data item to it using `setItem()`. - -```ts -localStorage.setItem("myDemo", "Deno App"); -``` - -The syntax for reading the localStorage item is as follows: - -```ts -const cat = localStorage.getItem("myDemo"); -``` - -The syntax for removing the localStorage item is as follows: - -```ts -localStorage.removeItem("myDemo"); -``` - -The syntax for removing all the localStorage items is as follows: - -```ts -localStorage.clear(); -``` diff --git a/docs/runtime/workers.md b/docs/runtime/workers.md deleted file mode 100644 index d39a8b130..000000000 --- a/docs/runtime/workers.md +++ /dev/null @@ -1,251 +0,0 @@ -## Workers - -Deno supports -[`Web Worker API`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker). - -Workers can be used to run code on multiple threads. Each instance of `Worker` -is run on a separate thread, dedicated only to that worker. - -Currently Deno supports only `module` type workers; thus it's essential to pass -the `type: "module"` option when creating a new worker. - -Use of relative module specifiers in the main worker are only supported with -`--location <href>` passed on the CLI. This is not recommended for portability. -You can instead use the `URL` constructor and `import.meta.url` to easily create -a specifier for some nearby script. Dedicated workers, however, have a location -and this capability by default. - -```ts -// Good -new Worker(new URL("./worker.js", import.meta.url).href, { type: "module" }); - -// Bad -new Worker(new URL("./worker.js", import.meta.url).href); -new Worker(new URL("./worker.js", import.meta.url).href, { type: "classic" }); -new Worker("./worker.js", { type: "module" }); -``` - -### Instantiation permissions - -Creating a new `Worker` instance is similar to a dynamic import; therefore Deno -requires appropriate permission for this action. - -For workers using local modules; `--allow-read` permission is required: - -**main.ts** - -```ts -new Worker(new URL("./worker.ts", import.meta.url).href, { type: "module" }); -``` - -**worker.ts** - -```ts -console.log("hello world"); -self.close(); -``` - -```shell -$ deno run main.ts -error: Uncaught PermissionDenied: read access to "./worker.ts", run again with the --allow-read flag - -$ deno run --allow-read main.ts -hello world -``` - -For workers using remote modules; `--allow-net` permission is required: - -**main.ts** - -```ts -new Worker("https://example.com/worker.ts", { type: "module" }); -``` - -**worker.ts** (at https[]()://example.com/worker.ts) - -```ts -console.log("hello world"); -self.close(); -``` - -```shell -$ deno run main.ts -error: Uncaught PermissionDenied: net access to "https://example.com/worker.ts", run again with the --allow-net flag - -$ deno run --allow-net main.ts -hello world -``` - -### Using Deno in worker - -> This is an unstable Deno feature. Learn more about -> [unstable features](./stability.md). - -By default the `Deno` namespace is not available in worker scope. - -To enable the `Deno` namespace pass `deno.namespace = true` option when creating -new worker: - -**main.js** - -```ts -const worker = new Worker(new URL("./worker.js", import.meta.url).href, { - type: "module", - deno: { - namespace: true, - }, -}); -worker.postMessage({ filename: "./log.txt" }); -``` - -**worker.js** - -```ts -self.onmessage = async (e) => { - const { filename } = e.data; - const text = await Deno.readTextFile(filename); - console.log(text); - self.close(); -}; -``` - -**log.txt** - -``` -hello world -``` - -```shell -$ deno run --allow-read --unstable main.js -hello world -``` - -### Specifying worker permissions - -> This is an unstable Deno feature. Learn more about -> [unstable features](./stability.md). - -The permissions available for the worker are analogous to the CLI permission -flags, meaning every permission enabled there can be disabled at the level of -the Worker API. You can find a more detailed description of each of the -permission options [here](../getting_started/permissions.md). - -By default a worker will inherit permissions from the thread it was created in, -however in order to allow users to limit the access of this worker we provide -the `deno.permissions` option in the worker API. - -- For permissions that support granular access you can pass in a list of the - desired resources the worker will have access to, and for those who only have - the on/off option you can pass true/false respectively. - - ```ts - const worker = new Worker(new URL("./worker.js", import.meta.url).href, { - type: "module", - deno: { - namespace: true, - permissions: { - net: [ - "https://deno.land/", - ], - read: [ - new URL("./file_1.txt", import.meta.url), - new URL("./file_2.txt", import.meta.url), - ], - write: false, - }, - }, - }); - ``` - -- Granular access permissions receive both absolute and relative routes as - arguments, however take into account that relative routes will be resolved - relative to the file the worker is instantiated in, not the path the worker - file is currently in - - ```ts - const worker = new Worker( - new URL("./worker/worker.js", import.meta.url).href, - { - type: "module", - deno: { - namespace: true, - permissions: { - read: [ - "/home/user/Documents/deno/worker/file_1.txt", - "./worker/file_2.txt", - ], - }, - }, - }, - ); - ``` - -- Both `deno.permissions` and its children support the option `"inherit"`, which - implies it will borrow its parent permissions. - - ```ts - // This worker will inherit its parent permissions - const worker = new Worker(new URL("./worker.js", import.meta.url).href, { - type: "module", - deno: { - namespace: true, - permissions: "inherit", - }, - }); - ``` - - ```ts - // This worker will inherit only the net permissions of its parent - const worker = new Worker(new URL("./worker.js", import.meta.url).href, { - type: "module", - deno: { - namespace: true, - permissions: { - env: false, - hrtime: false, - net: "inherit", - plugin: false, - read: false, - run: false, - write: false, - }, - }, - }); - ``` - -- Not specifying the `deno.permissions` option or one of its children will cause - the worker to inherit by default. - - ```ts - // This worker will inherit its parent permissions - const worker = new Worker(new URL("./worker.js", import.meta.url).href, { - type: "module", - }); - ``` - - ```ts - // This worker will inherit all the permissions of its parent BUT net - const worker = new Worker(new URL("./worker.js", import.meta.url).href, { - type: "module", - deno: { - namespace: true, - permissions: { - net: false, - }, - }, - }); - ``` - -- You can disable the permissions of the worker all together by passing `"none"` - to the `deno.permissions` option. - - ```ts - // This worker will not have any permissions enabled - const worker = new Worker(new URL("./worker.js", import.meta.url).href, { - type: "module", - deno: { - namespace: true, - permissions: "none", - }, - }); - ``` |