diff --git a/1.0/.gitignore b/1.0/.gitignore new file mode 100755 index 00000000..e7aad410 --- /dev/null +++ b/1.0/.gitignore @@ -0,0 +1,3 @@ +/.couscous +.sass-cache +.DS_Store diff --git a/1.0/CONTRIBUTING.md b/1.0/CONTRIBUTING.md new file mode 100755 index 00000000..20663c07 --- /dev/null +++ b/1.0/CONTRIBUTING.md @@ -0,0 +1,7 @@ +# Contributing to Vapor Docs + +Found a mistake or want to add something? Fork the documentation, fix it, and submit a pull request. + +We'll merge it as soon as we can. + +Thanks! \ No newline at end of file diff --git a/README.es.md b/1.0/README.es.md old mode 100644 new mode 100755 similarity index 100% rename from README.es.md rename to 1.0/README.es.md diff --git a/README.md b/1.0/README.md old mode 100644 new mode 100755 similarity index 100% rename from README.md rename to 1.0/README.md diff --git a/README.zh-hant.md b/1.0/README.zh-hant.md old mode 100644 new mode 100755 similarity index 100% rename from README.zh-hant.md rename to 1.0/README.zh-hant.md diff --git a/auth/middleware.md b/1.0/auth/middleware.md old mode 100644 new mode 100755 similarity index 100% rename from auth/middleware.md rename to 1.0/auth/middleware.md diff --git a/auth/protect.md b/1.0/auth/protect.md old mode 100644 new mode 100755 similarity index 100% rename from auth/protect.md rename to 1.0/auth/protect.md diff --git a/auth/request.md b/1.0/auth/request.md old mode 100644 new mode 100755 similarity index 100% rename from auth/request.md rename to 1.0/auth/request.md diff --git a/auth/user.md b/1.0/auth/user.md old mode 100644 new mode 100755 similarity index 100% rename from auth/user.md rename to 1.0/auth/user.md diff --git a/couscous.yml b/1.0/couscous.yml old mode 100644 new mode 100755 similarity index 100% rename from couscous.yml rename to 1.0/couscous.yml diff --git a/deploy/nginx.md b/1.0/deploy/nginx.md old mode 100644 new mode 100755 similarity index 100% rename from deploy/nginx.md rename to 1.0/deploy/nginx.md diff --git a/deploy/supervisor.md b/1.0/deploy/supervisor.md old mode 100644 new mode 100755 similarity index 100% rename from deploy/supervisor.md rename to 1.0/deploy/supervisor.md diff --git a/fluent/driver.md b/1.0/fluent/driver.md old mode 100644 new mode 100755 similarity index 100% rename from fluent/driver.md rename to 1.0/fluent/driver.md diff --git a/fluent/fixtures.md b/1.0/fluent/fixtures.md old mode 100644 new mode 100755 similarity index 100% rename from fluent/fixtures.md rename to 1.0/fluent/fixtures.md diff --git a/fluent/model.md b/1.0/fluent/model.md old mode 100644 new mode 100755 similarity index 100% rename from fluent/model.md rename to 1.0/fluent/model.md diff --git a/fluent/query.md b/1.0/fluent/query.md old mode 100644 new mode 100755 similarity index 100% rename from fluent/query.md rename to 1.0/fluent/query.md diff --git a/fluent/relation.md b/1.0/fluent/relation.md old mode 100644 new mode 100755 similarity index 100% rename from fluent/relation.md rename to 1.0/fluent/relation.md diff --git a/getting-started/hello-world.md b/1.0/getting-started/hello-world.md old mode 100644 new mode 100755 similarity index 100% rename from getting-started/hello-world.md rename to 1.0/getting-started/hello-world.md diff --git a/getting-started/install-swift-3-macos.md b/1.0/getting-started/install-swift-3-macos.md old mode 100644 new mode 100755 similarity index 100% rename from getting-started/install-swift-3-macos.md rename to 1.0/getting-started/install-swift-3-macos.md diff --git a/getting-started/install-swift-3-ubuntu.md b/1.0/getting-started/install-swift-3-ubuntu.md old mode 100644 new mode 100755 similarity index 100% rename from getting-started/install-swift-3-ubuntu.md rename to 1.0/getting-started/install-swift-3-ubuntu.md diff --git a/getting-started/install-toolbox.md b/1.0/getting-started/install-toolbox.md old mode 100644 new mode 100755 similarity index 100% rename from getting-started/install-toolbox.md rename to 1.0/getting-started/install-toolbox.md diff --git a/getting-started/manual.md b/1.0/getting-started/manual.md old mode 100644 new mode 100755 similarity index 100% rename from getting-started/manual.md rename to 1.0/getting-started/manual.md diff --git a/getting-started/xcode.md b/1.0/getting-started/xcode.md old mode 100644 new mode 100755 similarity index 100% rename from getting-started/xcode.md rename to 1.0/getting-started/xcode.md diff --git a/guide/commands.md b/1.0/guide/commands.md old mode 100644 new mode 100755 similarity index 100% rename from guide/commands.md rename to 1.0/guide/commands.md diff --git a/guide/config.md b/1.0/guide/config.md old mode 100644 new mode 100755 similarity index 100% rename from guide/config.md rename to 1.0/guide/config.md diff --git a/guide/controllers.md b/1.0/guide/controllers.md old mode 100644 new mode 100755 similarity index 100% rename from guide/controllers.md rename to 1.0/guide/controllers.md diff --git a/guide/droplet.md b/1.0/guide/droplet.md old mode 100644 new mode 100755 similarity index 100% rename from guide/droplet.md rename to 1.0/guide/droplet.md diff --git a/guide/folder-structure.md b/1.0/guide/folder-structure.md old mode 100644 new mode 100755 similarity index 100% rename from guide/folder-structure.md rename to 1.0/guide/folder-structure.md diff --git a/guide/hash.md b/1.0/guide/hash.md old mode 100644 new mode 100755 similarity index 100% rename from guide/hash.md rename to 1.0/guide/hash.md diff --git a/guide/json.md b/1.0/guide/json.md old mode 100644 new mode 100755 similarity index 100% rename from guide/json.md rename to 1.0/guide/json.md diff --git a/guide/leaf.md b/1.0/guide/leaf.md old mode 100644 new mode 100755 similarity index 100% rename from guide/leaf.md rename to 1.0/guide/leaf.md diff --git a/guide/middleware.md b/1.0/guide/middleware.md old mode 100644 new mode 100755 similarity index 100% rename from guide/middleware.md rename to 1.0/guide/middleware.md diff --git a/guide/provider.md b/1.0/guide/provider.md old mode 100644 new mode 100755 similarity index 100% rename from guide/provider.md rename to 1.0/guide/provider.md diff --git a/guide/sessions.md b/1.0/guide/sessions.md old mode 100644 new mode 100755 similarity index 100% rename from guide/sessions.md rename to 1.0/guide/sessions.md diff --git a/guide/validation.md b/1.0/guide/validation.md old mode 100644 new mode 100755 similarity index 100% rename from guide/validation.md rename to 1.0/guide/validation.md diff --git a/guide/views.md b/1.0/guide/views.md old mode 100644 new mode 100755 similarity index 100% rename from guide/views.md rename to 1.0/guide/views.md diff --git a/http/body.md b/1.0/http/body.md old mode 100644 new mode 100755 similarity index 100% rename from http/body.md rename to 1.0/http/body.md diff --git a/http/client.md b/1.0/http/client.md old mode 100644 new mode 100755 similarity index 100% rename from http/client.md rename to 1.0/http/client.md diff --git a/http/cors.md b/1.0/http/cors.md old mode 100644 new mode 100755 similarity index 100% rename from http/cors.md rename to 1.0/http/cors.md diff --git a/http/request.md b/1.0/http/request.md old mode 100644 new mode 100755 similarity index 100% rename from http/request.md rename to 1.0/http/request.md diff --git a/http/responder.md b/1.0/http/responder.md old mode 100644 new mode 100755 similarity index 100% rename from http/responder.md rename to 1.0/http/responder.md diff --git a/http/response-representable.md b/1.0/http/response-representable.md old mode 100644 new mode 100755 similarity index 100% rename from http/response-representable.md rename to 1.0/http/response-representable.md diff --git a/http/response.md b/1.0/http/response.md old mode 100644 new mode 100755 similarity index 100% rename from http/response.md rename to 1.0/http/response.md diff --git a/http/server.md b/1.0/http/server.md old mode 100644 new mode 100755 similarity index 100% rename from http/server.md rename to 1.0/http/server.md diff --git a/routing/basic.md b/1.0/routing/basic.md old mode 100644 new mode 100755 similarity index 100% rename from routing/basic.md rename to 1.0/routing/basic.md diff --git a/routing/collection.md b/1.0/routing/collection.md old mode 100644 new mode 100755 similarity index 100% rename from routing/collection.md rename to 1.0/routing/collection.md diff --git a/routing/controller b/1.0/routing/controller old mode 100644 new mode 100755 similarity index 100% rename from routing/controller rename to 1.0/routing/controller diff --git a/routing/group.md b/1.0/routing/group.md old mode 100644 new mode 100755 similarity index 100% rename from routing/group.md rename to 1.0/routing/group.md diff --git a/routing/parameters.md b/1.0/routing/parameters.md old mode 100644 new mode 100755 similarity index 100% rename from routing/parameters.md rename to 1.0/routing/parameters.md diff --git a/routing/query-parameters.md b/1.0/routing/query-parameters.md old mode 100644 new mode 100755 similarity index 100% rename from routing/query-parameters.md rename to 1.0/routing/query-parameters.md diff --git a/template/default.twig b/1.0/template/default.twig old mode 100644 new mode 100755 similarity index 100% rename from template/default.twig rename to 1.0/template/default.twig diff --git a/template/images/droplet.svg b/1.0/template/images/droplet.svg old mode 100644 new mode 100755 similarity index 100% rename from template/images/droplet.svg rename to 1.0/template/images/droplet.svg diff --git a/template/screenshot.png b/1.0/template/screenshot.png old mode 100644 new mode 100755 similarity index 100% rename from template/screenshot.png rename to 1.0/template/screenshot.png diff --git a/template/scripts/highlight.pack.js b/1.0/template/scripts/highlight.pack.js old mode 100644 new mode 100755 similarity index 100% rename from template/scripts/highlight.pack.js rename to 1.0/template/scripts/highlight.pack.js diff --git a/template/styles/main.css b/1.0/template/styles/main.css old mode 100644 new mode 100755 similarity index 100% rename from template/styles/main.css rename to 1.0/template/styles/main.css diff --git a/template/styles/main.css.map b/1.0/template/styles/main.css.map old mode 100644 new mode 100755 similarity index 100% rename from template/styles/main.css.map rename to 1.0/template/styles/main.css.map diff --git a/template/styles/main.sass b/1.0/template/styles/main.sass old mode 100644 new mode 100755 similarity index 100% rename from template/styles/main.sass rename to 1.0/template/styles/main.sass diff --git a/template/styles/vapor-code.css b/1.0/template/styles/vapor-code.css old mode 100644 new mode 100755 similarity index 100% rename from template/styles/vapor-code.css rename to 1.0/template/styles/vapor-code.css diff --git a/testing/basic.md b/1.0/testing/basic.md old mode 100644 new mode 100755 similarity index 100% rename from testing/basic.md rename to 1.0/testing/basic.md diff --git a/testing/modules.md b/1.0/testing/modules.md old mode 100644 new mode 100755 similarity index 100% rename from testing/modules.md rename to 1.0/testing/modules.md diff --git a/websockets/custom.md b/1.0/websockets/custom.md old mode 100644 new mode 100755 similarity index 100% rename from websockets/custom.md rename to 1.0/websockets/custom.md diff --git a/websockets/droplet.md b/1.0/websockets/droplet.md old mode 100644 new mode 100755 similarity index 100% rename from websockets/droplet.md rename to 1.0/websockets/droplet.md diff --git a/2.0/docs/advanced/modules.md b/2.0/docs/advanced/modules.md new file mode 100644 index 00000000..e69de29b diff --git a/2.0/docs/auth/middleware.md b/2.0/docs/auth/middleware.md new file mode 100644 index 00000000..7168403d --- /dev/null +++ b/2.0/docs/auth/middleware.md @@ -0,0 +1,88 @@ +!!! warning + This section may contain outdated information. + +# Middleware + +`AuthMiddleware` is at the core of adding authorization to your project. It is responsible for initializing dependencies, checking credentials, and handling sessions. + +## Create + +Once you have something that conforms to `Auth.User`, you can create an `AuthMiddleware`. Let's assume we have a class `User` that conforms to `Auth.User`. + +> Note: You may need to include a module name before `User` to disambiguate. + +```swift +import Auth + +let auth = AuthMiddleware(user: User.self) +``` + +Creating the `AuthMiddleware` can be that simple, or you can customize it with additional initialization arguments. + +### Cookie + +Customize the type of cookie the `AuthMiddleware` creates by passing a `CookieFactory`. + +```swift +let auth = AuthMiddleware(user: User.self) { value in + return Cookie( + name: "vapor-auth", + value: value, + expires: Date().addingTimeInterval(60 * 60 * 5), // 5 hours + secure: true, + httpOnly: true + ) +} +``` + +### Cache + +A custom `CacheProtocol` can be passed as well. The `MemoryCache` used by default is not persisted between server restarts and does not allow for sharing between multiple running instances. + +```swift +import VaporRedis + +let redis = RedisCache() +let auth = AuthMiddleware(user: User.self, cache: redis) +``` + +> Note: This example uses the [redis-provider](https://github.com/vapor/redis-provider) package. + +### Realm + +To customize the `AuthMiddleware` even further, you can use a custom `Realm`. The `Realm` takes the responsibility of registering and authenticating the user away from the `Auth.User` protocol. + +```swift +let facebook = FacebookRealm() +let auth = AuthMiddleware(user: User.self, realm: facebook) +``` + +> Note: `FacebookRealm` is hypothetical. + +## Add + +Once you've created the `AuthMiddleware`, you can add it to the `Droplet`. + +```swift +let drop = Droplet() +drop.middleware.append(auth) +``` + +> Note: If you'd like to enable or disable the middleware based on config files, check out [middleware](../vapor/middleware.md). + +### Sharing Cache + +If you'd like the `Droplet` and the `AuthMiddleware` to share the same `CacheProtocol`, pass the same instance to both. + +``` +import Vapor +import VaporRedis + +let redis = RedisCache() +let auth = AuthMiddleware(user: User.self, cache: redis) + +let drop = Droplet() + +drop.cache = redis +drop.middleware.append(auth) +``` diff --git a/2.0/docs/auth/protect.md b/2.0/docs/auth/protect.md new file mode 100644 index 00000000..4a33f25d --- /dev/null +++ b/2.0/docs/auth/protect.md @@ -0,0 +1,32 @@ +!!! warning + This section may contain outdated information. + +# Protect + +Once the `AuthMiddleware` has been enabled, you can use `ProtectMiddleware` to prevent certain routes from being accessed without authorization. + +## Create + +To create a `ProtectMiddleware`, you must give it the error to throw in case authorization fails. + +```swift +let error = Abort.custom(status: .forbidden, message: "Invalid credentials.") +let protect = ProtectMiddleware(error: error) +``` + +Here we pass it a simple 403 response. + +## Route Group + +Once the middleware has been created, you can add it to route groups. Learn more about middleware and routing in [route groups](../routing/group.md). + +``` +drop.grouped(protect).group("secure") { secure in + secure.get("about") { req in + let user = try req.user() + return user + } +} +``` + +Visiting `GET /secure/about` will return the authorized user, or an error if no user is authorized. diff --git a/2.0/docs/auth/request.md b/2.0/docs/auth/request.md new file mode 100644 index 00000000..ea0f0dbb --- /dev/null +++ b/2.0/docs/auth/request.md @@ -0,0 +1,160 @@ +!!! warning + This section may contain outdated information. + +# Request + +The `auth` property on `Request` lets you authenticate users and also provides some convenience methods for accessing common authorization headers. + +## Authorization + +The authorization header is a great place to send credentials from a client. + +``` +Authorization: xxxxxxxxxx +``` + +You can access the authorization header through `req.auth.header`. Two common patterns are basic and bearer. + +### Basic + +Basic authorization consists of a username and password concatenated into a string and base64 encoded. + +``` +Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l +``` + +This is what an example header looks like. You can read more about basic auth on [wikipedia](https://en.wikipedia.org/wiki/Basic_access_authentication). + +Below is how you access this header using `req.auth`. + +```swift +guard let credentials = req.auth.header?.basic else { + throw Abort.badRequest +} +``` + +The basic header returns an `APIKey` credential. + +``` +class APIKey: Credentials { + let id: String + let secret: String +} +``` + +### Bearer + +Another common method is bearer which consists of a single API key. + +``` +Authorization: Bearer apikey123 +``` + +It is accessed similarly to the basic header and returns an `AccessToken` credential. + +``` +class AccessToken: Credentials { + let string: String +} +``` + +### Raw + +To access the raw authorization header, use `req.auth.header?.header`. + +## Credentials + +Both Basic and Bearer return something that conforms to `Credentials`. You can always create a custom `Credentials` object for authentication by conforming your own class to `Credentials` or by manually creating an `APIKey`, `AccessToken`, or `Identifier`. + +```swift +let key = AccessToken(string: "apikey123") +``` + +### Input + +You can also create credentials from form or JSON data. + +```swift +guard + let username = req.data["username"]?.string, + let password = req.data["password"]?.string +else { + throw Abort.badRequest +} + +let key = APIKey(id: username, secret: password) +``` + +## Login + +Once you have some object that conforms to `Credentials`, you can try to login the user. + +```swift +try req.auth.login(credentials) +``` + +If this call succeeds, the user is logged in and a session has been started. They will stay logged in as long as their cookie is valid. + +### Authenticate + +Logging in calls the `authenticate` method on `Auth.User` model you supplied to the `AuthMiddleware`. Make sure you add support for all the credential types you may want to use. + +> Note: If you used a custom Realm, it will be called instead. + +### Identifier + +Another important credential type is the `Identifier` type. This is used by Vapor when fetching the `User` object from the `vapor-auth` cookie. It is also a convenient way to log a user in manually. + +```swift +static func authenticate(credentials: Credentials) throws -> Auth.User { + switch credentials { + ... + case let id as Identifier: + guard let user = try User.find(id.id) else { + throw Abort.custom(status: .badRequest, message: "Invalid identifier.") + } + + return user + ... + } +} +``` + +Adding the `Identifier` case for `Credentials` is easy, just look up the user by the identifier. + +```swift +let id = Identifier(id: 42) +try req.auth.login(id) +``` + +Now you can manually log users in with just their identifiers. + +### Ephemeral + +If you just want to log the user in for a single request, disable persistance. + +```swift +req.auth.login(credentials, persist: false) +``` + +> Note: Supporting `Identifier` credentials is required for persisted authentication to work properly. + +## User + +By default, `request.auth.user()` returns the authorized `Auth.User`. This will need to be casted to your internal `User` type for use. + +Adding a convenience method on `Request` is a great way to simplify this. + +```swift +extension Request { + func user() throws -> User { + guard let user = try auth.user() as? User else { + throw Abort.custom(status: .badRequest, message: "Invalid user type.") + } + + return user + } +} +``` + +Now you can access your `User` type with `try req.user()`. diff --git a/2.0/docs/auth/user.md b/2.0/docs/auth/user.md new file mode 100644 index 00000000..db698128 --- /dev/null +++ b/2.0/docs/auth/user.md @@ -0,0 +1,119 @@ +!!! warning + This section may contain outdated information. + +# Auth + +Authentication and authorization is focused around the `Auth.User` protocol. Authentication is analagous to asking: "Who is this?", while authorization is analagous to asking: "What can they do?". Vapor includes an extensible authentication system that you can use as a base for more sophisticated authorization. + +> Note: An [auth-example](https://github.com/vapor/auth-example) project is available on GitHub. + +## User Protocol + +Any type can conform to the `Auth.User` protocol, but they are commonly added onto Fluent `Model`s. + +```swift +import Vapor +import Auth + +final class User: Model { + var id: Node? + var name: String + + ... +} + +extension User: Auth.User { + static func authenticate(credentials: Credentials) throws -> Auth.User { + + } + + static func register(credentials: Credentials) throws -> Auth.User { + + } +} +``` + +Here is an example `User` class with the `Auth.User` protocol requirements stubbed. Note that the name of our class and the protocol are the same. This is why we use the `Auth.` prefix to differentiate the protocol from the `Auth` module from our `User` class. + +### Authenticate + +A user is authenticated when a set of credentials is passed to the static `authenticate` method and the matching user is returned. + +#### Credentials + +```swift +protocol Credentials { } +``` + +The credentials protocol is an empty protocol that any type can conform to. This gives great flexibility to your authentication model, but also requires that you properly handle the case of unsupported credential types. + +#### Access Token + +One of the simplest credential types included is `AccessToken`. It carries a `String` based token that will be used to authenticate the user. + +Let's look at how we might support the access token type. + +```swift +static func authenticate(credentials: Credentials) throws -> Auth.User { + switch credentials { + case let accessToken as AccessToken: + guard let user = try User.query().filter("access_token", accessToken.string).first() else { + throw Abort.custom(status: .forbidden, message: "Invalid access token.") + } + + return user + default: + let type = type(of: credentials) + throw Abort.custom(status: .forbidden, message: "Unsupported credential type: \(type).") + } +} +``` + +The first step is to cast the credentials to the type we want to support--in this case, `AccessToken`. If we do not have an access token, we will inform the client that the credentials are invalid. + +Once we have the access token, we will use it to query the `User` model for an entry with a matching access token. This is assuming the `users` table or collection has the access tokens stored on it. You may opt to store them somewhere else. + +Once we have found the user associated with the supplied access token, we simply return it. + +#### Identifier + +Vapor uses the `Identifier` credential type internally to lookup users from sessions. You can read more in the [Request](request.md) section. + +### Register + +Similar to the authenticate method, the register method takes credentials. But instead of fetching the user from the data store, it provides a convenient way to create the user. You are not required to register your users through this method. + +## Example + +Here is an example of a User that supports multiple credentials. + +```swift +extension User: Auth.User { + static func authenticate(credentials: Credentials) throws -> Auth.User { + let user: User? + + switch credentials { + case let id as Identifier: + user = try User.find(id.id) + case let accessToken as AccessToken: + user = try User.query().filter("access_token", accessToken.string).first() + case let apiKey as APIKey: + user = try User.query().filter("email", apiKey.id).filter("password", apiKey.secret).first() + default: + throw Abort.custom(status: .badRequest, message: "Invalid credentials.") + } + + guard let u = user else { + throw Abort.custom(status: .badRequest, message: "User not found.") + } + + return u + } + + static func register(credentials: Credentials) throws -> Auth.User { + ... + } +} +``` + +> Note: Try not to store passwords. If you must, hash and salt them. diff --git a/2.0/docs/deploy/nginx.md b/2.0/docs/deploy/nginx.md new file mode 100644 index 00000000..a028e148 --- /dev/null +++ b/2.0/docs/deploy/nginx.md @@ -0,0 +1,148 @@ +!!! warning + This section may contain outdated information. + +# Deploying with Nginx + +Nginx is an extremely fast, battle tested, and easy-to-configure HTTP server and proxy. While Vapor supports directly serving HTTP requests with or without TLS, proxying behind Nginx can provide increased performance, security, and ease-of-use. + +> Note: We recommend proxying Vapor HTTP servers behind Nginx. + +## Overview + +What does it mean to proxy an HTTP server? In short, a proxy acts as a middleman between the public internet and your HTTP server. Requests come to the proxy and then it sends them to Vapor. + +An important feature of this middleman proxy is that it can alter or even redirect the requests. For instance, the proxy can require that the client use TLS (https), rate limit requests, or even serve public files without talking to your Vapor application. + +![nginx-proxy](https://cloud.githubusercontent.com/assets/1342803/20184965/5d9d588a-a738-11e6-91fe-28c3a4f7e46b.png) + +### More Detail + +The default port for receiving HTTP requests is port `80` (and `443` for HTTPS). When you bind a Vapor server to port `80`, it will directly receive and respond to the HTTP requests that come to your server. When adding a proxy like Nginx, you bind Vapor to an internal port, like port `8080`. + +> Note: Ports greater than 1024 do not require `sudo` to bind. + +When Vapor is bound to a port besides `80` or `443`, it will not be accessible to the outside internet. You then bind Nginx to port `80` and configure it to route requests to your Vapor server bound at port `8080` (or whichever port you've chosen). + +And that's it. If Nginx is properly configured, you will see your Vapor app responding to requests on port `80`. Nginx proxies the requests and responses invisibly. + +## Install Nginx + +The first step is installing Nginx. One of the great parts of Nginx is the tremendous amount of community resources and documentation surrounding it. Because of this, we will not go into great detail here about installing Nginx as there is almost definitely a tutorial for your specific platform, OS, and provider. + +Tutorials: +- [How To Install Nginx on Ubuntu 14.04 LTS](https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-14-04-lts) +- [How To Install Nginx on Ubuntu 16.04](https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-16-04) +- [How to Deploy Nginx on Heroku](https://blog.codeship.com/how-to-deploy-nginx-on-heroku/) +- [How To Run Nginx in a Docker Container on Ubuntu 14.04](https://www.digitalocean.com/community/tutorials/how-to-run-nginx-in-a-docker-container-on-ubuntu-14-04) + + +### APT + +Nginx can be installed through APT. + +```sh +sudo apt-get update +sudo apt-get install nginx +``` + +Check whether Nginx was installed correctly by visiting your server's IP address in a browser + +```sh +http://server_domain_name_or_IP +``` + +### Service + +Ther service an be started or stopped. + +```sh +sudo service nginx stop +sudo service nginx start +sudo service nginx restart +``` + +## Booting Vapor + +Nginx can be started an stopped with the `sudo service nginx ...` commands. You will need something similar to start and stop your Vapor server. + +There are many ways to do this, and they depend on which platform you are deploying to. Check out the [Supervisor](supervisor.md) instructions to add commands for starting and stopping your Vapor app. + +## Configure Proxy + +The configuration files for enabled sites can be found in `/etc/nginx/sites-enabled/`. + +Create a new file or copy the example template from `/etc/nginx/sites-available/` to get started. + +Here is an example configuration file for a Vapor project called `Hello` in the home directory. + +```sh +server { + server_name hello.com; + listen 80; + + root /home/vapor/Hello/Public/; + + location @proxy { + proxy_pass http://127.0.0.1:8080; + proxy_pass_header Server; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_pass_header Server; + proxy_connect_timeout 3s; + proxy_read_timeout 10s; + } +} +``` + +This configuration file assumes the `Hello` project binds to port `8080` when started in production mode. + +### Serving Files + +Nginx can also serve public files without asking your Vapor app. This can improve performance by freeing up the Vapor process for other tasks under heavy load. + +```sh +server { + ... + + # Serve all public/static files via nginx and then fallback to Vapor for the rest + try_files $uri @proxy; + + location @proxy { + ... + } +} +``` + +### TLS + +Adding TLS is relatively straightforward as long as the certificates have been properly generated. To generate TLS certificates for free, check out [Let's Encrypt](https://letsencrypt.org/getting-started/). + +```sh +server { + ... + + listen 443 ssl; + + ssl_certificate /etc/letsencrypt/live/hello.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/hello.com/privkey.pem; + + ssl_protocols TLSv1 TLSv1.1 TLSv1.2; + ssl_prefer_server_ciphers on; + ssl_dhparam /etc/ssl/certs/dhparam.pem; + ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA'; + ssl_session_timeout 1d; + ssl_session_cache shared:SSL:50m; + ssl_stapling on; + ssl_stapling_verify on; + add_header Strict-Transport-Security max-age=15768000; + + ... + + location @proxy { + ... + } +} +``` + +The configuration above are the relatively strict settings for TLS with Nginx. Some of the settings here are not required, but enhance security. diff --git a/2.0/docs/deploy/supervisor.md b/2.0/docs/deploy/supervisor.md new file mode 100644 index 00000000..fe9287ba --- /dev/null +++ b/2.0/docs/deploy/supervisor.md @@ -0,0 +1,63 @@ +!!! warning + This section may contain outdated information. + +# Supervisor + +[Supervisor](http://supervisord.org) is a process control system that makes it easy to start, stop, and restart your Vapor app. + +## Install + +```sh +sudo apt-get update +sudo apt-get install supervisor +``` + +## Configure + +Each Vapor app on your server should have its own configuration file. For an example `Hello` project, the configuration file would be located at `/etc/supervisor/conf.d/hello.conf` + +```sh +[program:hello] +command=/home/vapor/hello/.build/release/App serve --env=production +directory=/home/vapor/hello/ +user=www-data +stdout_logfile=/var/log/supervisor/%(program_name)-stdout.log +stderr_logfile=/var/log/supervisor/%(program_name)-stderr.log +``` + +As specified in our configuration file the `Hello` project is located in the home folder for the user `vapor`. Make sure `directory` points to the root directory of your project where the `Config/` folder is. + +The `--env=production` flag will disable verbose logging and prioritize the `Config/production` sub folder of your configuration files. + +### Environment + +You can export variables to your Vapor app with supervisor. + +```sh +environment=PORT=8123 +``` + +Exported variables can be used in Vapor's configuration files with the `$` prefix. + +`Config/production/servers.json ` +```json +{ + "my-server": { + "port": "$PORT" + } +} +``` + +The above config file will start a server named `my-server` on the port number exported by supervisor. This is a great way to control how Vapor starts from the supervisor config scripts. Feel free to name the server whatever you like. + +## Start + +You can now load and start your app. + +```sh +supervisorctl reread +supervisorctl add hello +supervisorctl start hello +``` + +> Note: The `add` command may have already started your app. diff --git a/2.0/docs/fluent/driver.md b/2.0/docs/fluent/driver.md new file mode 100644 index 00000000..d8f6766d --- /dev/null +++ b/2.0/docs/fluent/driver.md @@ -0,0 +1,51 @@ +!!! warning + This section may contain outdated information. + +# Driver + +Drivers are what power Fluent under the hood. Fluent comes with a memory driver by default and there are many providers for databases like MySQL, SQLite, Mongo, PostgreSQL, and more available as providers. + +![Drivers and Providers](https://cloud.githubusercontent.com/assets/1342803/17418823/73f1d1d2-5a68-11e6-9bed-90f42ce7781d.png) + +This graphic shows the relation between Drivers and Providers using MySQL as an example. This distinction allows Fluent to be used independently from Vapor. + +If you want to use Fluent without Vapor, you will import Drivers into your package. If you are using Vapor, you will import Providers. + +Search GitHub for: +- [Fluent Drivers](https://github.com/vapor?utf8=✓&q=-driver) +- [Vapor Providers](https://github.com/vapor?utf8=✓&q=-provider) + +Not all drivers have providers yet, and not all drivers or providers are up to date with the latest Vapor 1.0. This is a great way to contribute! + +## Creating a Driver + +Fluent is a powerful, database agnostic package for persisting your models. It was designed from the beginning to work with both SQL and NoSQL databases alike. + +Any database that conforms to `Fluent.Driver` will be able to power the models in Fluent and Vapor. + +The protocol itself is fairly simple: + +```swift +public protocol Driver { + var idKey: String { get } + func query(_ query: Query) throws -> Node + func schema(_ schema: Schema) throws + func raw(_ raw: String, _ values: [Node]) throws -> Node +} +``` + +### ID Key + +The ID key will be used to power functionality like `User.find()`. In SQL, this is often `id`. In MongoDB, it is `_id`. + +### Query + +This method will be called for every query made by Fluent. It is the drivers job to properly understand all of the properties on `Query` and return the desired rows, document, or other data as represented by `Node`. + +### Schema + +The schema method will be called before the database is expected to accept queries for a schema. For some NoSQL databases like MongoDB, this can be ignored. For SQL, this is where `CREATE` and other such commands should be called according to `Schema`. + +### Raw + +This is an optional method that can be used by any Fluent driver that accepts string queries. If your database does not accept such queries, an error can be thrown. diff --git a/2.0/docs/fluent/model.md b/2.0/docs/fluent/model.md new file mode 100644 index 00000000..8ed2a90e --- /dev/null +++ b/2.0/docs/fluent/model.md @@ -0,0 +1,245 @@ +!!! warning + This section may contain outdated information. + +# Model + +`Model` is the base protocol for any of your application's models, especially those you want to persist. + +> `Model` is only available in Vapor, the Fluent equivalent is `Entity` + +## Example + +Let's create a simple `User` model. + +```swift +final class User { + var name: String + + init(name: String) { + self.name = name + } +} +``` + +The first step to conforming to `Model` is to import Vapor and Fluent. + +```swift +import Vapor +import Fluent +``` + +Then add the conformance to your class. + +```swift +final class User: Model { + ... +} +``` + +The compiler will inform you that some methods need to be implemented to conform. + +### ID + +The first required property is an identifier. This property will contain the identifier when the model is fetched from the database. If it is `nil`, it will be set when the model is saved. + +```swift +final class User: Model { + var id: Node? + ... +} +``` + +### Node Initializable + +The next requirement is a way to create the model from the persisted data. Model uses `NodeInitializable` to achieve this. + +```swift +final class User: Model { + init(node: Node, in context: Context) throws { + id = try node.extract("id") + name = try node.extract("name") + } + ... +} +``` + +The keys `id` and `name` are what we expect the columns or fields in the database to be named. The `extract` call is marked with a `try` because it will throw an error if the value is not present or is the wrong type. + +### Node Representable + +Now that we have covered initializing the model, we need to show how to save it back into the database. Model uses `NodeRepresentable` to achieve this. + +```swift +final class User: Model { + func makeNode(context: Context) throws -> Node { + return try Node(node: [ + "id": id, + "name": name + ]) + } + ... +} +``` + +When a `User` is saved, the `makeNode()` method will be called and the resulting `Node` will be saved to the database. The keys `id` and `name` are what we expect the columns or fields in the database to be named. + +> In most of the cases you do not need to be concerned about `context` argument of the `makeNode(context:)` method. It’s a part of the protocol that allows extensibility in more advanced or specific scenarios. + +## Preparations + +Some databases, like MySQL, need to be prepared for a new schema. In MySQL, this means creating a new table. Preparations are also equatable to migrations, as they can be used to alter schemas after they've already been created. + +### Prepare + +Let's assume we are using a SQL database. To prepare the database for our `User` class, we need to create a table. If you are using a database like Mongo, you can leave this method unimplemented. + +```swift +final class User { + static func prepare(_ database: Database) throws { + try database.create("users") { users in + users.id() + users.string("name") + } + } + ... +} +``` + +Here we create a table named `users` that has an identifier field and a string field with the key `name`. This matches both our `init(node: Node)` and `makeNode() -> Node` methods. + +### Revert + +An optional preparation reversion can be created. This will be run if `vapor run prepare --revert` is called. + +```swift +final class User { + static func revert(_ database: Database) throws { + try database.delete("users") + } + ... +} +``` + +Here we are deleting the table named `users`. + +### Preparations as Migrations + +If you want to add a field to your table after you've already created the initial schema, you can create a struct or class that conforms to `Preparation` like so: + +```swift + +struct AddFooToBar: Preparation { + static func prepare(_ database: Database) throws { + try database.modify("bars", closure: { bar in + bar.string("foo", length: 150, optional: false, unique: false, default: nil) + }) + } + + static func revert(_ database: Database) throws { + + } +} +``` + +Then, in your Droplet setup, add this line: `drop.preparations.append(AddFooToBar.self)` + +### Droplet + +To run these prepations when the applications boots, you must add the Model to the `Droplet`. + +```swift +let drop = Droplet() + +drop.preparations.append(User.self) +``` + +> Note: Preparations must be appended before the Droplet is run. + +## Full Model + +This is what our final `User` model looks like: + +```swift +import Vapor +import Fluent + +final class User: Model { + var id: Node? + var name: String + + init(name: String) { + self.name = name + } + + + init(node: Node, in context: Context) throws { + id = try node.extract("id") + name = try node.extract("name") + } + + func makeNode(context: Context) throws -> Node { + return try Node(node: [ + "id": id, + "name": name + ]) + } + + static func prepare(_ database: Database) throws { + try database.create("users") { users in + users.id() + users.string("name") + } + } + + static func revert(_ database: Database) throws { + try database.delete("users") + } +} +``` + +## Interacting + +Now that `User` conforms to `Model`, it has a plethora of new methods like `find()`, `query()`, `makeJSON()` and more. + +### Fetch + +Models can be fetched by their database identifier. + +```swift +let user = try User.find(42) +``` + +### Save + +Newly created models can be saved to the database. + +```swift +var user = User(name: "Vapor") +try user.save() +print(user.id) // prints the new id +``` + +### Delete + +Persisted models with identifiers can be deleted. + +```swift +try user.delete() +``` + +## Model vs. Entity + +Model has a couple of extra conformances that a pure Fluent entity doesn't have. + +```swift +public protocol Model: Entity, JSONRepresentable, StringInitializable, ResponseRepresentable {} +``` + +As can be seen in the protocol, Vapor models can automatically convert to `JSON`, `Response`, and even be used in type-safe routing. + +## Options + +Change the table/collection name +```swift +static var entity = "new_name" +``` diff --git a/2.0/docs/fluent/query.md b/2.0/docs/fluent/query.md new file mode 100644 index 00000000..f59828ac --- /dev/null +++ b/2.0/docs/fluent/query.md @@ -0,0 +1,119 @@ +!!! warning + This section may contain outdated information. + +# Query + +The `Query` class is what powers every interaction with Fluent. Whether you're fetching a model with `.find()` or saving to the database, there is a `Query` involved somewhere. + +## Querying Models + +Every type that conforms to [Model](model.md) gets a static `.query()` method. + +```swift +let query = try User.query() +``` + +This is how you can create a `Query`. + +### No Database + +The `.query()` method is marked with `try` because it can throw an error if the Model has not had its static database property set. + +```swift +User.database = drop.database +``` + +This property is set automatically when you pass the Model as a preparation. + +## Filter + +The most common types of queries involve filtering data. + +```swift +let smithsQuery = try User.query().filter("last_name", "Smith") +``` + +Here is the short hand for adding an `equals` filter to the query. As you can see, queries can be chained together. + +In additional to `equals`, there are many other types of `Filter.Comparison`. + +```swift +let over21 = try User.query().filter("age", .greaterThanOrEquals, 21) +``` + +### Scope + +Filters can also be run on sets. + +```swift +let coolPets = try Pet.query().filter("type", .in, ["Dog", "Ferret"]) +``` + +Here only Pets of type Dog _or_ Ferret are returned. The opposite works for `notIn`. + + +### Contains + +Partially matching filters can also be applied. + +```swift +let statesWithNew = try State.query().filter("name", contains: "New") +``` + +## Retrieving + +There are two methods for running a query. + +### All + +All of the matching entities can be fetched. This returns an array of `[Model]`, in this case users. + +```swift +let usersOver21 = try User.query().filter("age", .greaterThanOrEquals, 21).all() +``` + +### First + +The first matching entity can be fetched. This returns an optional `Model?`, in this case a user. + +```swift +let firstSmith = try User.query().filter("last_name", "Smith").first() +``` + +## Union + +Other Models can be joined onto your query to assist in filtering. The results must still be either `[Model]` or `Model?` for whichever type created the query. + +```swift +let usersWithCoolPets = try User.query() + .union(Pet.self) + .filter(Pet.self, "type", .in, ["Dog", "Ferret"]) +``` + +Here the `User` collection is unioned to the `Pet` collection. Only `User`s who have a dog or a ferret will be returned. + +### Keys + +The `union` method assumes that the querying table has a foreign key identifier to the joining table. + +The above example with users and pets assumes the following schema. + +``` +users +- id +pets +- id +- user_id +``` + +Custom foreign keys can be provided through overloads to `union`. + +## Raw Queries + +Since Fluent is focused on interacting with models, each Query requires a model type. If you want to do raw database queries that aren't based on a model, you should use the underlying Fluent Driver to do so. + +```swift +if let mysql = drop.database?.driver as? MySQLDriver { + let version = try mysql.raw("SELECT @@version") +} +``` diff --git a/2.0/docs/fluent/relation.md b/2.0/docs/fluent/relation.md new file mode 100644 index 00000000..34207ea7 --- /dev/null +++ b/2.0/docs/fluent/relation.md @@ -0,0 +1,175 @@ +!!! warning + This section may contain outdated information. + +# Relation + +Relations allow foreign key based connections between database entities. This is common in SQL-based databases, but can also be used with NoSQL. + +Fluent's relations are named as follows: +- Parent (BelongsTo) +- Children (HasMany, HasOne) +- Siblings (ManyToMany, BelongsToMany) + +## Parent + +The parent relation should be called on an entity that has a foreign key to another entity. For example, assume the following schema: + +``` +pets +- id +- owner_id +- name +- type + +owner +- id +- name +``` + +Here each pet can have one owner. To access that owner from the pet, call `.parent()`. + +```swift +let pet: Pet = ... +let owner = try pet.parent(pet.ownerId, Owner.self).get() +``` + +The parent method requires the foreign key for the parent as well as the type. + +### Convenience + +To make requesting a parent easier, a method can be added to the model. + +```swift +extension Pet { + func owner() throws -> Parent { + return try parent(ownerId) + } +} +``` + +Since we are extending `Pet`, we no longer need to use `pet.` before the `ownerId`. Furthermore, because we are providing the type information about `Owner` in the return type of the method, we no longer need to pass that as an argument. + +The `Parent` type is a queryable object, meaning you could `delete()` the parent, `filter()`, etc. + +```swift +try pet.owner().delete() +``` + +To fetch the parent, you must call `get()`. + +```swift +let owner = try pet.owner().get() +``` + +## Children + +`Children` are the opposite side of the `Parent` relationship. Assuming the schema from the previous example, the pets could be retrieved from an owner like so: + +```swift +let owner: Owner = ... +let pets = owner.children(Pet.self).all() +``` + +Here only the type of child is required. + +### Convenience + +Similarly to `Parent`, convenience methods can be added for children. + +```swift +extension Owner { + func pets() throws -> Children { + return try children() + } +} +``` + +Since the type information is clear from the return value, `Pet.self` does not need to be passed to `children()`. + +The `Children` is also a queryable object like `Parent`. You can call `first()`, `all()`, `filter()`, etc. + +```swift +let coolPets = try owner.pets().filter("type", .in, ["Dog", "Ferret"]).all() +``` + +## Siblings + +`Siblings` work differently from `Children` or `Parent` since they require a `Pivot`. + +For an example, let's say we want to allow our pets to have multiple toys. But we also want the toys to be shared by multiple pets. We need a pivot entity for this. + +``` +pets +- id +- type +- owner_id + +toys +- id +- name + +pets_toys +- id +- pet_id +- toy_id +``` + +Here you can see the pivot entity, `pets_toys`, or `Pivot`. + +### Convenience + +Let's add the convenience methods to `Pet`. + +```swift +extension Pet { + func toys() throws -> Siblings { + return try siblings() + } +} +``` + +And the opposite for `Toy`. + +```swift +extension Toy { + func pets() throws -> Siblings { + return try siblings() + } +} +``` + +Now you are free to query pets and toys similarly to children. + +```swift +let pet: Pet = ... +let toys = pet.toys().all() +``` + +To create a new many-to-many relationship you can do the following. + +```swift + +var toy: Toy = ... // Create a new toy +try toy.save() // Save the toy to the db + + +var pet: Pet = ... // Create a new pet +try pet.save() // Save the pet to the db + +// Link them together in the db +var pivot = Pivot(toy, pet) // Create the relationship +try pivot.save() // Save the relationship to the db +``` + +### Preparation + +To prepare for a relationship with a `Pivot`, simply add the pivot to the `Droplet`'s preparations. + +```swift +let drop = Droplet() +drop.preparations += [ + Toy.self, + Pet.self, + Pivot.self +] +``` diff --git a/2.0/docs/getting-started/hello-world.md b/2.0/docs/getting-started/hello-world.md new file mode 100644 index 00000000..244ecc3b --- /dev/null +++ b/2.0/docs/getting-started/hello-world.md @@ -0,0 +1,144 @@ +# Hello, World + +This section assumes you have installed Swift 3.1 and the Vapor Toolbox and have verified they are working. + +!!! tip + Note: If you don't want to use the Toolbox, follow the [manual guide](manual.md). + +## New Project + +Let's start by creating a new project called "Hello, World". + +```sh +vapor new Hello +``` + +Vapor's folder structure will probably look familiar to you if you have worked with other web frameworks. + +``` +Hello +├── Sources +│ └── App +│ └── Controllers +│ └── Middleware +│ └── Models +│ └── main.swift +├── Public +├── Resources +│ └── Views +└── Package.swift +``` + +For our Hello, World project, we will be focusing on the `main.swift` file. + +``` +Hello +└── Sources + └── App + └── main.swift +``` +!!! tip + The `vapor new` command creates a new project with examples and comments about how to use the framework. You can delete these if you want. + +## Code + +### Droplet + +Look for the following line in the `main.swift` file. + +```swift +let drop = try Droplet() +``` + +This is where the one and only `Droplet `for this example will be created. The [Droplet](../vapor/droplet.md) class has a plethora of useful functions on it, and is used extensively. + +### Routing + +Right after the creation of `drop`, add the following code snippet. + +```swift +drop.get("hello") { request in + return "Hello, world!" +} +``` + +This creates a new route on the `Droplet` that will match all `GET` requests to `/hello`. + +All route closures are passed an instance of [Request](../http/request.md) that contains information such as the URI requested and data sent. + +This route simply returns a string, but anything that is [ResponseRepresentable](../http/response-representable.md) can be returned. Learn more in the [Routing](../routing/basic.md) section of the guide. + +!!! tip + Xcode autocomplete may add extraneous type information to your closure's input arguments. This can be deleted to keep the code clean. If you'd like to keep the type information add `import HTTP` to the top of the file. + +### Serving + +At the bottom of the main file, make sure to run your `Droplet`. + +```swift +drop.run() +``` + +Save the file, and switch back to the terminal. + +## Compile & Run + +### Building + +A big part of what makes Vapor so great is Swift's state of the art compiler. Let's fire it up. Make sure you are in the root directory of the project and run the following command. + +```swift +vapor build +``` + +!!! note + `vapor build` runs `swift build` in the background. + +The Swift Package Manager will first start by downloading the appropriate dependencies from git. It will then compile and link these dependencies together. + +When the process has completed, you will see `Building Project [Done]` + +!!! tip + If you see a message like `unable to execute command: Killed`, you need to increase your swap space. This can happen if you are running on a machine with limited memory. + +#### Release + +Building your application in release mode takes longer, but increases performance. + +```sh +vapor build --release +``` + +### Serving + +Boot up the server by running the following command. + +```sh +vapor run serve +``` + +You should see a message `Server starting...`. You can now visit `http://localhost:8080/hello` in your browser. + +!!! note + Certain port numbers require super user access to bind. Simply run `sudo vapor run` to allow access. If you decide to run on a port besides `80`, make sure to direct your browser accordingly. + +#### Production + +Serving your application in the production environment increases its security and performance. + +```sh +vapor run serve --env=production +``` + +Debug errors will be silenced while in the production environment, so make sure to check your logs for errors. + +!!! warning + If you compiled your application with `--release`, make sure to add that flag to the `vapor run` command as well. e.g., `vapor run serve --env=production --release`. + +### Hello, World + +You should see the following output in your browser window. + +``` +Hello, world! +``` diff --git a/2.0/docs/getting-started/install-swift-3-macos.md b/2.0/docs/getting-started/install-swift-3-macos.md new file mode 100644 index 00000000..695a02f7 --- /dev/null +++ b/2.0/docs/getting-started/install-swift-3-macos.md @@ -0,0 +1,29 @@ +# Install Swift 3.1: macOS + +To use Swift 3.1 on macOS, you just need to have Xcode 8 installed. + +## Install Xcode + +Install [Xcode 8](https://itunes.apple.com/us/app/xcode/id497799835?mt=12) from the Mac App Store. + +[![Xcode 8](https://cloud.githubusercontent.com/assets/1342803/18537674/2ddd8e9c-7ad5-11e6-9bc2-7155d57d20ec.png)](https://itunes.apple.com/us/app/xcode/id497799835?mt=12) + +### Open Xcode + +After Xcode 8 has been downloaded, you must open it to finish the installation. This may take a while. + +## Check + +Double check the installation was successful by running: + +```sh +curl -sL check.vapor.sh | bash +``` + +## Toolbox + +You can now move on to [Install Toolbox](install-toolbox.md). + +## Swift.org + +Check out [Swift.org](https://swift.org)'s extensive guides if you need more detailed instructions for installing Swift 3.0. diff --git a/2.0/docs/getting-started/install-swift-3-ubuntu.md b/2.0/docs/getting-started/install-swift-3-ubuntu.md new file mode 100644 index 00000000..885c0d66 --- /dev/null +++ b/2.0/docs/getting-started/install-swift-3-ubuntu.md @@ -0,0 +1,122 @@ +# Install Swift 3.1: Ubuntu + +Installing Swift 3.1 on Ubuntu only takes a couple of minutes. + +## Quick + +Don't want to type? Run the following script to quickly install Swift 3.1. + +```sh +curl -sL swift.vapor.sh/ubuntu | bash +``` + +!!! note + The install script adds Swift to your `~/.bashrc` profile automatically. + +## Manual + +To install manually, you just need to install Swift's dependencies with `apt-get` and download the Swift toolchain. + +### Version + +Swift 3.1 supports the following Ubuntu versions: + +- 14.04 LTS (Trusty Tahr) +- 16.04 LTS (Xenial Xerus) +- 16.10 (Yakkety Yak) + +To check which version of Ubuntu you have, run: + +```bash +lsb_release -a +``` + +### Dependencies + +Depending on your version of Ubuntu, you may need some additional tools for the compiler. We'll err on the safe side and install everything you should need + +```sh +sudo apt-get update +sudo apt-get install clang libicu-dev binutils git libpython2.7-dev libcurl3 +``` + +### Download + +Download the Swift 3.1 toolchain for your Ubuntu version. + +```sh +# Ubuntu 14.04 +wget https://swift.org/builds/swift-3.1-release/ubuntu1404/swift-3.1-RELEASE/swift-3.1-RELEASE-ubuntu14.04.tar.gz + +# Ubuntu 16.04 +wget https://swift.org/builds/swift-3.1-release/ubuntu1604/swift-3.1-RELEASE/swift-3.1-RELEASE-ubuntu16.04.tar.gz + +# Ubuntu 16.10 +wget https://swift.org/builds/swift-3.1-release/ubuntu1610/swift-3.1-RELEASE/swift-3.1-RELEASE-ubuntu16.10.tar.gz +``` + +### Decompress + +After Swift has downloaded, decompress it. + +```sh +# Ubuntu 14.04 +tar zxf swift-3.1-RELEASE-ubuntu14.04.tar.gz + +# Ubuntu 16.04 +tar zxf swift-3.1-RELEASE-ubuntu16.04.tar.gz + +# Ubuntu 16.10 +tar zxf swift-3.1-RELEASE-ubuntu16.10.tar.gz +``` + +### Install + +Move Swift 3.1 to a safe, permanent place on your computer. We'll use `/swift-3.1`, but feel free to choose wherever you like. + +```sh +# Ubuntu 14.04 +mv swift-3.1-RELEASE-ubuntu14.04 /swift-3.1 + +# Ubuntu 16.04 +mv swift-3.1-RELEASE-ubuntu16.04 /swift-3.1 + +# Ubuntu 16.10 +mv swift-3.1-RELEASE-ubuntu16.10 /swift-3.1 +``` + +!!! warning + You may need to use `sudo`. + +### Export + +Edit your bash profile using your text editor of choice. + +```sh +vim ~/.bashrc +``` + +Add the following line: + +```sh +export PATH=/swift-3.1/usr/bin:"${PATH}" +``` + +!!! warning + If you moved Swift 3.1 to a folder other than `/swift-3.1`, your path will be different. + +## Check + +Double check the installation was successful by running: + +```sh +curl -sL check.vapor.sh | bash +``` + +## Toolbox + +You can now move on to [Install Toolbox](install-toolbox.md) + +## Swift.org + +Check out [Swift.org](https://swift.org)'s guide to [using downloads](https://swift.org/download/#using-downloads) if you need more detailed instructions for installing Swift 3.1. diff --git a/2.0/docs/getting-started/install-toolbox.md b/2.0/docs/getting-started/install-toolbox.md new file mode 100644 index 00000000..14a4579f --- /dev/null +++ b/2.0/docs/getting-started/install-toolbox.md @@ -0,0 +1,59 @@ +# Install Toolbox + +Vapor's command line interface provides shortcuts and assistance for common tasks. + +Vapor Toolbox + +!!! tip + If you do not want to install the Toolbox, checkout the [Manual](manual.md) quickstart. + +## Install + +Run the following script to install the [Toolbox](https://github.com/vapor/toolbox). + +```sh +curl -sL toolbox.vapor.sh | bash +``` + +!!! warning + Vapor Toolbox is written in Swift, so you must have Swift 3.1 installed. See the earlier steps of Getting Started for instructions on installing Swift. + +### Verify + +Make sure the Toolbox installed successfully by running the help query. You should see a print out of the available commands. You can run the `--help` option on any Toolbox command. + +```sh +vapor --help +``` +## Create A Project + +Now that you have installed the Toolbox, you can create your first Vapor project following the [Hello, World guide](hello-world.md). + +## Updating + +The toolbox can update itself. This may be useful if you experience any issues in the future. + +```sh +vapor self update +``` + +## Templates + +The toolbox can create a project from the Vapor basic-template or any other git repo. + +```sh +vapor new [--template=] +``` + +### Options + +The toolbox will build an absolute URL based on what you pass as the template option. + +- `--template=light` clones `http://github.com/vapor/light-template`. +- `--template=user/repo` clones `http://github.com/user/repo`. +- `--template=http://example.com/repo-path` clones the full url given. + +!!! note + If you do not specify a template option, the project will be built from Vapor's [basic template](https://github.com/vapor/basic-template). + + diff --git a/2.0/docs/getting-started/manual.md b/2.0/docs/getting-started/manual.md new file mode 100644 index 00000000..72d1892e --- /dev/null +++ b/2.0/docs/getting-started/manual.md @@ -0,0 +1,106 @@ +# Manual Quickstart + +Learn how to create a Vapor project _without_ the Toolbox using just Swift 3 and the Swift Package Manager. + +This document assumes that you have Swift 3.1 installed. + +!!! tip + If you'd prefer to use the Toolbox, learn how to install it [here](install-toolbox.md). If you've installed the Toolbox, follow the toolbox guide [here](hello-world.md). + +## Check + +To check that your environment is compatible, run the following script: + +```bash +curl -sL check.vapor.sh | bash +``` + +## Make new project using SwiftPM + +Open your terminal + +!!! note + For our example, we'll be using the Desktop folder. + +```bash +cd ~/Desktop +mkdir Hello +cd Hello +swift package init --type executable +``` + +Your folder should look like this: + +``` +├── Package.swift +├── Sources +│   └── main.swift +└── Tests +``` + +### Edit `Package.swift` + +Open your `Package.swift` file: + +```bash +open Package.swift +``` + +And add Vapor as a dependency. Here's how your file will look. + +### Package.swift + +```swift +import PackageDescription + +let package = Package( + name: "Hello", + dependencies: [ + .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2) + ] +) +``` + +!!! warning + We try to keep this document up to date, however, you can view latest releases [here](https://github.com/vapor/vapor/releases). + +### Edit `main.swift` + +A simple hello world: + +```swift +import Vapor + +let drop = Droplet() + +drop.get("hello") { req in + return "Hello Vapor" +} + +drop.run() +``` + +## Compile & Run + +The first `build` command can take a while to fetch dependencies. + +```bash +swift build +.build/debug/Hello serve +``` + +!!! warning + If different, replace `Hello` above with the name of your executable (as defined in `Package.swift`). + +### Production + +Compiling in Swift's release mode and setting Vapor's environment to production will make your app more secure and performant. + +```sh +swift build --configuraiton release +.build/release/Hello serve --env=production +``` + +## View + +Go to your favorite browser and visit `http://localhost:8080/hello` diff --git a/2.0/docs/getting-started/xcode.md b/2.0/docs/getting-started/xcode.md new file mode 100644 index 00000000..aac056dc --- /dev/null +++ b/2.0/docs/getting-started/xcode.md @@ -0,0 +1,39 @@ +# Xcode + +The first thing you'll probably notice about Vapor and Swift Package Manager projects in general is that they don't include an Xcode project. In fact, when SPM generates packages, the `.xcodeproj` file is `.gitignore`d by default. + +This means we don't have to worry about `.pbxproj` conflicts, and it's easy for different platforms to utilize their own editors. + +## Generate Project + +### Vapor Toolbox + +To generate a new Xcode project for a project, use: + +```sh +vapor xcode +``` + +!!! tip + If you'd like to automatically open the Xcode project, use `vapor xcode -y` + +### Manual + +To generate a new Xcode project manually. + +```sh +swift package generate-xcodeproj +``` + +Open the project and continue normally. + +## Flags + +For some packages with underlying C dependencies, users will need to pass linker flags during **build** and **project generation**. Make sure to consult the guides associated with those dependencies. For example, MySQL: + +``` +swift package generate-xcodeproj -Xswiftc -I/usr/local/include/mysql -Xlinker -L/usr/local/lib +``` + +!!! tip + The Vapor Toolbox automatically detects and adds linker flags required for Vapor packages. diff --git a/2.0/docs/http/body.md b/2.0/docs/http/body.md new file mode 100644 index 00000000..ace31ee0 --- /dev/null +++ b/2.0/docs/http/body.md @@ -0,0 +1,140 @@ +!!! warning + This section may contain outdated information. + +> Module: `import HTTP` + +# Body + +The `HTTP.Body` represents the payload of an `HTTP.Message`, and is used to pass the underlying data. Some examples of this in practice would be `JSON`, `HTML` text, or the bytes of an image. Let's look at the implementation: + +```swift +public enum Body { + case data(Bytes) + case chunked((ChunkStream) throws -> Void) +} +``` + +## Data Case + +The `data` case is by far the most common use for a `Body` in an `HTTP.Message`. It is simply an array of bytes. The serialization protocol or type associated with these bytes is usually defined by the `Content-Type` header. Let's look at some examples. + +### Application/JSON + +If our `Content-Type` header contains `application/json`, then the underlying bytes represent serialized JSON. + +```swift +if let contentType = req.headers["Content-Type"], contentType.contains("application/json"), let bytes = req.body.bytes { + let json = try JSON(bytes: bytes) + print("Got JSON: \(json)") +} +``` + +### Image/PNG + +If our `Content-Type` contains `image/png`, then the underlying bytes represent an encoded png. + +```swift +if let contentType = req.headers["Content-Type"], contentType.contains("image/png"), let bytes = req.body.bytes { + try database.save(image: bytes) +} +``` + +## Chunked Case + +The `chunked` case only applies to outgoing `HTTP.Message`s in Vapor. It is traditionally a responder's role to collect an entire chunked encoding before passing it on. We can use this to send a body asynchronously. + +```swift +let body: Body = Body.chunked(sender) +return Response(status: .ok, body: body) +``` + +We can implement this manually, or use Vapor's built in convenience initializer for chunked bodies: + +```swift +return Response(status: .ok) { chunker in + for name in ["joe", "pam", "cheryl"] { + sleep(1) + try chunker.send(name) + } + + try chunker.close() +} +``` + +> Make sure to call `close()` before the chunker leaves scope. + +## BodyRepresentable + +In addition to the concrete `Body` type, as is common in Vapor, we also have wide support for `BodyRepresentable`. This means objects that we're commonly converting to `Body` type can be used interchangeably. For example: + +```swift +return Response(body: "Hello, World!") +``` + +In the above example, string is converted to bytes and added to the body. + +> In practice, it is better to use `return "Hello, World!"`. Vapor will automatically be able to set the `Content-Type` to appropriate values. + +Let's look at how it's implemented: + +```swift +public protocol BodyRepresentable { + func makeBody() -> Body +} +``` + +### Custom + +We can conform our own types to this as well where applicable. Let's pretend we have a custom data type, `.vpr`. Let's conform our `VPR` file type model: + +```swift +extension VPRFile: HTTP.BodyRepresentable { + func makeBody() -> Body { + // collect bytes + return .data(bytes) + } +} +``` + +> You may have noticed above, that the protocol throws, but our implementation does not. This is completely valid in Swift and will allow you to not throw if you're ever calling the function manually. + +Now we're able to include our `VPR` file directly in our `Responses`. + +```swift +drop.get("files", ":file-name") { request in + let filename = try request.parameters.extract("file-name") as String + let file = VPRFileManager.fetch(filename) + return Response(status: .ok, headers: ["Content-Type": "file/vpr"], body: file) +} +``` + +In practice, if we're repeating this often, we'll probably conform `VPRFile` directly to `ResponseRepresentable` + +```swift +extension VPRFile: HTTP.ResponseRepresentable { + func makeResponse() -> Response { + return Response( + status: .ok, + headers: ["Content-Type": "file/vpr"], + body: file + ) + } +} +``` + +Here's our above example now: + +```swift +drop.get("files", ":file-name") { request in + let filename = try request.parameters.extract("file-name") as String + return VPRFileManager.fetch(filename) +} +``` + +We could also use type-safe routing to make this even more concise: + +```swift +drop.get("files", String.self) { request, filename in + return VPRFileManager.fetch(filename) +} +``` diff --git a/2.0/docs/http/client.md b/2.0/docs/http/client.md new file mode 100644 index 00000000..71d33407 --- /dev/null +++ b/2.0/docs/http/client.md @@ -0,0 +1,159 @@ +!!! warning + This section may contain outdated information. + +> Module: `import HTTP` + +# Client + +The client provided by `HTTP` is used to make outgoing requests to remote servers. Let's look at a simple outgoing request. + +## QuickStart + +Let's jump right in to make a simple HTTP Request. Here's a basic `GET` request using your Vapor `Droplet`. + +```swift +let query = ... +let spotifyResponse = try drop.client.get("https://api.spotify.com/v1/search?type=artist&q=\(query)") +print(spotifyR) +``` + +### Clean Up + +The url above can be a little tricky to read, so let's use the query parameter to clean it up a little bit: + +```swift +try drop.client.get("https://api.spotify.com/v1/search", query: ["type": "artist", "q": query]) +``` + +### Continued + +In addition to `GET` requests, Vapor's client provides support for most common HTTP functions. `GET`, `POST`, `PUT`, `PATCH`, `DELETE` + +### POST as json +```swift +try drop.client.post("http://some-endpoint/json", headers: ["Content-Type": "application/json"], body: myJSON.makeBody()) +``` + +### POST as x-www-form-urlencoded +```swift +try drop.client.post("http://some-endpoint", headers: [ + "Content-Type": "application/x-www-form-urlencoded" +], body: Body.data( Node(node: [ + "email": "mymail@vapor.codes" +]).formURLEncoded())) +``` + +### Full Request + +To access additional functionality or custom methods, use the underlying `request` function directly. + +```swift +public static func get(_ method: Method, + _ uri: String, + headers: [HeaderKey: String] = [:], + query: [String: CustomStringConvertible] = [:], + body: Body = []) throws -> Response +``` + +For example: + +```swift +try drop.client.request(.other(method: "CUSTOM"), "http://some-domain", headers: ["My": "Header"], query: ["key": "value"], body: []) +``` + +## Config + +The `Config/clients.json` file can be used to modify the client's settings. + +### TLS + +Host and certificate verification can be disabled. + +> Note: Use extreme caution when modifying these settings. + +```json +{ + "tls": { + "verifyHost": false, + "verifyCertificates": false + } +} +``` + +### Mozilla + +The Mozilla certificates are included by default to make fetching content from secure sites easy. + +```json +{ + "tls": { + "certificates": "mozilla" + } +} +``` + +## Advanced + +In addition to our Droplet, we can also use and interact with the `Client` manually. Here's how our default implementation in Vapor looks: + +```swift +let response = try Client.get("http://some-endpoint/mine") +``` + +The first thing we likely noticed is `TCPClientStream` being used as a Generic value. This will be the underlying connection that the `HTTP.Client` can use when performing the request. By conforming to the underlying `ClientStream`, an `HTTP.Client` can accept custom stream implementations seamlessly. + +## Save Connection + +Up to this point, we've been interacting with the Client via `class` or `static` level functions. This allows us to end the connection upon a completed request and is the recommended interaction for most use cases. For some advanced situations, we may want to reuse a connection. For these, we can initialize our client and perform multiple requests like this. + +```swift +let pokemonClient = try drop?.client.make(scheme: "http", host: "pokeapi.co") +for i in 0...1 { + let response = try pokemonClient?.get(path: "/api/v2/pokemon/", query: ["limit": 20, "offset": i]) + print("response: \(response)") +} +``` + +## ClientProtocol + +Up to this point, we've focused on the built in `HTTP.Client`, but users can also include their own customized clients by conforming to `HTTP.ClientProtocol`. Let's look at the implementation: + +```swift +public protocol Responder { + func respond(to request: Request) throws -> Response +} + +public protocol Program { + var host: String { get } + var port: Int { get } + var securityLayer: SecurityLayer { get } + // default implemented + init(host: String, port: Int, securityLayer: SecurityLayer) throws +} + +public protocol ClientProtocol: Program, Responder { + var scheme: String { get } + var stream: Stream { get } + init(scheme: String, host: String, port: Int, securityLayer: SecurityLayer) throws +} +``` + +By conforming to these underlying functions, we immediately gain access to the public `ClientProtocol` apis we viewed above. + +## Customize Droplet + +If we've introduced a custom conformance to `HTTP.ClientProtocol`, we can pass this into our droplet without changing the underlying behavior in our application. + +For example: + +```swift +let drop = Droplet() + +drop.client = MyCustomClient.self +``` + +Going forward, all of your calls to `drop.client` will use `MyCustomClient.self`: + +```swift +drop.client.get(... // uses `MyCustomClient` +``` diff --git a/2.0/docs/http/cors.md b/2.0/docs/http/cors.md new file mode 100644 index 00000000..7c3445df --- /dev/null +++ b/2.0/docs/http/cors.md @@ -0,0 +1,93 @@ +!!! warning + This section may contain outdated information. + +# CORS + +Vapor by default provides a middleware for implementing proper support for Cross-Origin Resource Sharing (CORS) named `CORSMiddleware`. + +"Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript / browser access." - [http://enable-cors.org/](http://enable-cors.org/) + +To learn more about middlewares, please visit the Middleware section of the documentation [here](https://vapor.github.io/documentation/guide/middleware.html). + +![](https://upload.wikimedia.org/wikipedia/commons/c/ca/Flowchart_showing_Simple_and_Preflight_XHR.svg) +*Image Author: [Wikipedia](https://commons.wikimedia.org/wiki/File:Flowchart_showing_Simple_and_Preflight_XHR.svg)* + +## Basic + +First of all, add the CORS middleware into your droplet middlewares array. + +```swift +# Insert CORS before any other middlewares +drop.middleware.insert(CORSMiddleware(), at: 0) +``` + +> Note: Make sure you insert CORS middleware before any other throwing middlewares, like the AbortMiddleware or similar. Otherwise the proper headers might not be added to the response. + +`CORSMiddleware` has a default configuration which should suit most users, with values as follows: + +- **Allowed Origin** + - Value of origin header in the request. +- **Allowed Methods** + - `GET`, `POST`, `PUT`, `OPTIONS`, `DELETE`, `PATCH` +- **Allowed Headers** + - `Accept`, `Authorization`, `Content-Type`, `Origin`, `X-Requested-With` + +## Advanced + +All settings and presets can be customized by advanced users. There's two ways of doing this, either you programatically create and configure a `CORSConfiguration` object or you can put your configuration into a Vapor's JSON config file. + +See below for how to set up both and what are the options. + +### Configuration + +The `CORSConfiguration` struct is used to configure the `CORSMiddleware`. You can instanitate one like this: + +```swift +let configuration = CORSConfiguration(allowedOrigin: .custom("https://vapor.codes"), + allowedMethods: [.get, .post, .options], + allowedHeaders: ["Accept", "Authorization"], + allowCredentials: false, + cacheExpiration: 600, + exposedHeaders: ["Cache-Control", "Content-Language"]) +``` + +After creating a configuration you can add the CORS middleware. + +```swift +drop.middleware.insert(CORSMiddleware(configuration: configuration), at: 0) +``` + +> Note: Please consult the documentation in the source code of the `CORSConfiguration` for more information about available values for the settings. + + +### JSON Config + +Optionally, `CORSMiddleware` can be configured using the Vapor's `Config` which is created out of the json files contained in your Config folder. You will need to create a file called `cors.json` or `CORS.json` in your Config folder in your project and add the required keys. + +Example of how such a file could look as follows: + +```swift +{ + "allowedOrigin": "origin", + "allowedMethods": "GET,POST,PUT,OPTIONS,DELETE,PATCH", + "allowedHeaders": ["Accept", "Authorization", "Content-Type", "Origin", "X-Requested-With"] +} + +``` + +> Note: Following keys are required: `allowedOrigin`, `allowedMethods`, `allowedHeaders`. If they are not present an error will be thrown while instantiating the middleware. +> +> Optionally you can also specify the keys `allowCredentials` (Bool), `cacheExpiration` (Int) and `exposedHeaders` ([String]). + +Afterwards you can add the middleware using the a throwing overload of the initialiser that accepts Vapor's `Config`. + +```swift +let drop = Droplet() + +do { + drop.middleware.insert(try CORSMiddleware(configuration: drop.config), at: 0) +} catch { + fatalError("Error creating CORSMiddleware, please check that you've setup cors.json correctly.") +} +``` + diff --git a/2.0/docs/http/request.md b/2.0/docs/http/request.md new file mode 100644 index 00000000..4fc8cc1a --- /dev/null +++ b/2.0/docs/http/request.md @@ -0,0 +1,222 @@ +!!! warning + This section may contain outdated information. + +> Module: `import HTTP` + +# Request + +The most common part of the `HTTP` library we'll be interacting with is the `Request` type. Here's a look at some of the most commonly used attributes in this type. + +```swift +public var method: Method +public var uri: URI +public var parameters: Node +public var headers: [HeaderKey: String] +public var body: Body +public var data: Content +``` + +### Method + +The HTTP `Method` associated with the `Request`, ie: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`. + +### URI + +The associated `URI` of the request. We will use this to access attributes about the `uri` the request was sent to. + +For example, given the following uri: `http://vapor.codes/example?query=hi#fragments-too` + +```swift +let scheme = request.uri.scheme // http +let host = request.uri.host // vapor.codes + +let path = request.uri.path // /example +let query = request.uri.query // query=hi +let fragment = request.uri.fragment // fragments-too +``` + +### Route Parameters + +The url parameters associated with the request. For example, if we have a path registered as `hello/:name/age/:age`, we would be able to access those in our request, like so: + +```swift +let name = request.parameters["name"] // String? +let age = request.parameters["age"]?.int // Int? +``` + +Or, to automatically throw on `nil` or invalid variable, you can also `extract` + +```swift +let name = try request.parameters.extract("name") as String +let age = try request.parameters.extract("age") as Int +``` + +These extract functions can cast to any `NodeInitializable` type, including your own custom types. Make sure to check out [Node](https://github.com/vapor/node) for more info. + +> Note: Vapor also provides type safe routing in the routing section of our docs. + + +### Headers + +These are the headers associated with the request. If you are preparing an outgoing request, this can be used to add your own keys. + +```swift +let contentType = request.headers["Content-Type"] +``` + +Or for outgoing requests: + +```swift +let request = Request ... +request.headers["Content-Type"] = "application/json" +request.headers["Authorization"] = ... my auth token +``` + +#### Extending Headers + +We generally seek to improve code bases by removing stringly typed code where possible. We can add variables to the headers using generic extensions. + +```swift +extension HTTP.KeyAccessible where Key == HeaderKey, Value == String { + var customKey: String? { + get { + return self["Custom-Key"] + } + set { + self["Custom-Key"] = newValue + } + } +} +``` + +With this pattern implemented, our string `"Custom-Key"` is contained in one section of our code. We can now access like this: + +```swift +let customKey = request.headers.customKey + +// or + +let request = ... +request.headers.customKey = "my custom value" +``` + +### Body + +This is the body associated with the request and represents the general data payload. You can view more about body in the associated [docs](./body.md) + +For incoming requests, we'll often pull out the associated bytes like so: + +```swift +let rawBytes = request.body.bytes +``` + +## Content + +Generally when we're sending or receiving requests, we're using them as a way to transport content. For this, Vapor provides a convenient `data` variable associated with the request that prioritizes content in a consistent way. + +For example, say I receive a request to `http://vapor.codes?hello=world`. + +```swift +let world = request.data["hello"]?.string +``` + +This same code will work if I receive a JSON request, for example: + +```json +{ + "hello": "world" +} +``` + +Will still be accessible through data. + +```swift +let world = request.data["hello"]?.string +``` +> Note: Force unwrap should never be used. + +This also applies to multi-part requests and can even be extended to new types such as XML or YAML through middleware. + +If you'd prefer to access given types more explicitly, that's totally fine. The `data` variable is purely opt-in convenience for those who want it. + +## JSON + +To access JSON directly on a given request, use the following: + +```swift +let json = request.json["hello"] +``` + +## Query Parameters + +The same applies to query convenience: + +```swift +let query = request.query?["hello"] // String? +let name = request.query?["name"]?.string // String? +let age = request.query?["age"]?.int // Int? +let rating = request.query?["rating"]?.double // Double? +``` + +## Key Paths + +Key paths work on most Vapor types that can have nested key value objects. Here's a couple examples of how to access given the following json: + +```json +{ + "metadata": "some metadata", + "artists" : { + "href": "http://someurl.com", + "items": [ + { + "name": "Van Gogh", + }, + { + "name": "Mozart" + } + ] + } +} +``` + +We could access the data in the following ways: + +### Metadata + +Access top level values + +```swift +let type = request.data["metadata"].string // "some metadata" +``` + +### Items + +Access nested values + +```swift +let items = request.data["artists", "items"] // [["name": "Van Gogh"], ["name": "Mozart"]] +``` + +### Mixing Arrays and Objects + +Get first artists + +```swift +let first = request.data["artists", "items", 0] // ["name": "Van Gogh"] +``` + +### Array Item + +Get key from array item + +```swift +let firstName = request.data["artists", "items", 0, "name"] // "Van Gogh" +``` + +### Array Comprehension + +We can also smartly map an array of keys, for example, to just get the names of all of the artists, we could use the following + +```swift +let names = request.data["artists", "items", "name"] // ["Van Gogh", "Mozart"] +``` diff --git a/2.0/docs/http/responder.md b/2.0/docs/http/responder.md new file mode 100644 index 00000000..94b978e5 --- /dev/null +++ b/2.0/docs/http/responder.md @@ -0,0 +1,78 @@ +!!! warning + This section may contain outdated information. + +> Module: `import HTTP` + +# Responder + +The `Responder` is a simple protocol defining the behavior of objects that can accept a `Request` and return a `Response`. Most notably in Vapor, it is the core API endpoint that connects the `Droplet` to the `Server`. Let's look at the definition: + +```swift +public protocol Responder { + func respond(to request: Request) throws -> Response +} +``` + +> The responder protocol is most notably related to Droplet and it's relationship with a server. Average users will not likely interact with it much. + +## Simple + +Of course, Vapor provides some conveniences for this, and in practice, we will often call: + +```swift +try drop.run() +``` + +## Manual + +As we just mentioned, the Vapor `Droplet` itself conforms to `Responder`, connecting it to the `Server`. This means if we wanted to serve our droplet manually, we could do: + +```swift +let server = try Server, Serializer>(port: port) +try server.start(responder: droplet) { error in + print("Got error: \(error)") +} +``` + +## Advanced + +We can conform our own objects to `Responder` and pass them to `Servers`. Let's look at an example: + +```swift +final class Responder: HTTP.Responder { + func respond(to request: Request) throws -> Response { + let body = "Hello World".makeBody() + return Response(body: body) + } +} +``` + +This only returns `"Hello World"` for every request, it's most commonly going to be linked with a router of some type. + + +```swift +final class Responder: HTTP.Responder { + let router: Router = ... + + func respond(to request: Request) throws -> Response { + return try router.route(request) + } +} +``` + +We'll then pass this responder to a server and let it go. + +```swift +let server = try Server, Serializer>(port: port) + +print("visit http://localhost:\(port)/") +try server.start(responder: Responder()) { error in + print("Got error: \(error)") +} +``` + +This can be used as a jumping off point for applications looking to implement features manually. + +## Client + +The `HTTP.Client` is itself a `Responder` although, instead of handling the `Request` itself, it passes it on to the underlying URI. diff --git a/2.0/docs/http/response-representable.md b/2.0/docs/http/response-representable.md new file mode 100644 index 00000000..302d9f47 --- /dev/null +++ b/2.0/docs/http/response-representable.md @@ -0,0 +1,103 @@ +!!! warning + This section may contain outdated information. + +> Module: `import HTTP` + +# ResponseRepresentable + +Traditionally HTTP servers take a `Request` and return a `Response`. Vapor is no different, but we can take advantage of Swift's powerful protocols to be a bit more flexible to the user facing API. + +Let's start with the definition of `ResponseRepresentable` + +```swift +public protocol ResponseRepresentable { + func makeResponse() throws -> Response +} +``` + +By conforming to this protocol, we can more flexibly return things that conform instead of creating the response manually each time. Vapor provides some of these by default. Including (but not limited to): + +### String + +Because string conforms to `ResponseRepresentable`, we can return it directly in a Vapor route handler. + +```swift +drop.get("hello") { request in + return "Hello, World!" +} +``` + +### JSON + +`JSON` can be returned directly instead of recreating a response each time. + +```swift +drop.get("hello") { request in + return try JSON(node: [ + "hello": "world", + "some-numbers": [ + 1, + 2, + 3 + ] + ] + ) +} +``` + +### Response + +Of course, we can also return Responses for anything not covered: + +```swift +drop.get("hello") { request in + return Response(status: .ok, headers: ["Content-Type": "text/plain"], body: "Hello, World!") +} +``` + +## Conforming + +All we need to do to return our own objects is conform them to `ResponseRepresentable`. Let's look at an example type, a simple blog post model: + +```swift +import Foundation + +struct BlogPost { + let id: String + let content: String + let createdAt: NSDate +} +``` + +And now, let's conform it to response representable. + +```swift +import HTTP +import Foundation + +extension BlogPost: ResponseRepresentable { + func makeResponse() throws -> Response { + let json = try JSON(node: + [ + "id": id, + "content": content, + "created-at": createdAt.timeIntervalSince1970 + ] + ) + return try json.makeResponse() + } +} +``` + +> Don't forget to import HTTP. + +Now that we've modeled our BlogPost, we can return it directly in route handlers. + +```swift +drop.post("post") { req in + guard let content = request.data["content"] else { throw Error.missingContent } + let post = Post(content: content) + try post.save(to: database) + return post +} +``` diff --git a/2.0/docs/http/response.md b/2.0/docs/http/response.md new file mode 100644 index 00000000..83557d1d --- /dev/null +++ b/2.0/docs/http/response.md @@ -0,0 +1,125 @@ +!!! warning + This section may contain outdated information. + +> Module: `import HTTP` + +# Response + +When building endpoints, we'll often be returning responses for requests. If we're making outgoing requests, we'll be receiving them. + +```swift +public let status: Status +public var headers: [HeaderKey: String] +public var body: Body +public var data: Content +``` + +#### Status + +The http status associated with the event, for example `.ok` == 200 ok. + +#### Headers + +These are the headers associated with the request. If you are preparing an outgoing response, this can be used to add your own keys. + +```swift +let contentType = response.headers["Content-Type"] +``` + +Or for outgoing response: + +```swift +let response = response ... +response.headers["Content-Type"] = "application/json" +response.headers["Authorization"] = ... my auth token +``` + +##### Extending Headers + +We generally seek to improve code bases by removing stringly typed code where possible. We can add variables to the headers using generic extensions. + +```swift +extension HTTP.KeyAccessible where Key == HeaderKey, Value == String { + var customKey: String? { + get { + return self["Custom-Key"] + } + set { + self["Custom-Key"] = newValue + } + } +} +``` + +With this pattern implemented, our string `"Custom-Key"` is contained in one section of our code. We can now access like this: + +```swift +let customKey = response.headers.customKey + +// or + +let request = ... +response.headers.customKey = "my custom value" +``` + +#### Body + +This is the body associated with the response and represents the general data payload. You can view more about body in the associated [docs](./body.md) + +For responses, the body is most commonly set at initialization. With two main types. + +##### BodyRepresentable + +Things that can be converted to bytes, ie: + +```swift +let response = Response(status: .ok, body: "some string") +``` + +In the above example, the `String` will be automatically converted to a body. Your own types can do this as well. + +##### Bytes Directly + +If we already have our bytes array, we can pass it into the body like so: + +```swift +let response = Response(status: .ok, body: .data(myArrayOfBytes)) +``` + +##### Chunked + +To send an `HTTP.Response` in chunks, we can pass a closure that we'll use to send our response body in parts. + +```swift +let response = Response(status: .ok) { chunker in + for name in ["joe", "pam", "cheryl"] { + sleep(1) + try chunker.send(name) + } + + try chunker.close() +} +``` + +> Make sure to call `close()` before the chunker leaves scope. + +## Content + +We can access content the same we do in a [request](./request.md). This most commonly applies to outgoing requests. + +```swift +let pokemonResponse = try drop.client.get("http://pokeapi.co/api/v2/pokemon/") +let names = pokemonResponse.data["results", "name"]?.array +``` + +## JSON + +To access JSON directly on a given response, use the following: + +```swift +let json = request.response["hello"] +``` + +## Key Paths + +For more on KeyPaths, visit [here](./request.md#key-paths) diff --git a/2.0/docs/http/server.md b/2.0/docs/http/server.md new file mode 100644 index 00000000..a70fdf94 --- /dev/null +++ b/2.0/docs/http/server.md @@ -0,0 +1,209 @@ +!!! warning + This section may contain outdated information. + +# Server + +The server is responsible for accepting connections from clients, parsing their requests, and delivering them a response. + +## Default + +Starting your Droplet with a default server is simple. + +```swift +import Vapor + +let drop = Droplet() + +drop.run() +``` + +The default server will bind to host `0.0.0.0` at port `8080`. + +## Config + +If you are using a `Config/servers.json` file, this is where you can easily change your host and port or even boot multiple servers. + +```json +{ + "default": { + "port": "$PORT:8080", + "host": "0.0.0.0", + "securityLayer": "none" + } +} +``` + +The default `servers.json` is above. The port with try to resolve the environment variable `$PORT` or fallback to `8080`. + +### Multiple + +You can start multiple servers in the same application. This is especially useful if you want to boot an `HTTP` and `HTTPS` server side by side. + +```json +{ + "plaintext": { + "port": "80", + "host": "vapor.codes", + "securityLayer": "none" + }, + "secure": { + "port": "443", + "host": "vapor.codes", + "securityLayer": "tls", + "tls": { + "certificates": "none", + "signature": "selfSigned" + } + }, +} +``` + +## TLS + +TLS (formerly SSL) can be configured with a variety of different certificate and signature types. + +### Verify + +Verificiation of hosts and certificates can be disabled. They are enabled by default. + +> Note: Be extremely careful when disabling these options. + +```json +"tls": { + "verifyHost": false, + "verifyCertificates": false +} +``` + +### Certificates + +#### None + +```json +"tls": { + "certificates": "none" +} +``` + +#### Chain + +```json +"tls": { + "certificates": "chain", + "chainFile": "/path/to/chainfile" +} +``` + +#### Files + +```json +"tls": { + "certificates": "files", + "certificateFile": "/path/to/cert.pem", + "privateKeyFile": "/path/to/key.pem" +} +``` + +#### Certificate Authority + +```json +"tls": { + "certificates": "ca" +} +``` + +### Signature + +#### Self Signed + +```json +"tls": { + "signature": "selfSigned" +} +``` + +#### Signed File + +```json +"tls": { + "signature": "signedFile", + "caCertificateFile": "/path/to/file" +} +``` + +#### Signed Directory + +```json +"tls": { + "signature": "signedDirectory", + "caCertificateDirectory": "/path/to/dir" +} +``` + +## Example + +Here is an example `servers.json` file using certificate files with a self signed signature and host verification redundantly set to `true`. + +```json +{ + "secure": { + "port": "8443", + "host": "0.0.0.0", + "securityLayer": "tls", + "tls": { + "verifyHost": true, + "certificates": "files", + "certificateFile": "/vapor/certs/cert.pem", + "privateKeyFile": "/vapor/certs/key.pem", + "signature": "selfSigned" + } + } +} +``` + +## Manual + +Servers can also be configured manually, without configuration files. + +> Note: If servers are configured programatically, they override any config settings. + +### Simple + +The `run` method on the Droplet takes a dictionary of server configuration objects. The key is the name of the server. + +```swift +import Vapor + +let drop = Droplet() + +drop.run(servers: [ + "default": (host: "vapor.codes", port: 8080, securityLayer: .none) +] +``` + +### TLS + +TLS can also be configured manually, and works similarly to the `servers.json` config files described above. + +```swift +import Vapor +import TLS + +let drop = Droplet() + +let config = try TLS.Config( + mode: .server, + certificates: .files( + certificateFile: "/Users/tanner/Desktop/certs/cert.pem", + privateKeyFile: "/Users/tanner/Desktop/certs/key.pem", + signature: .selfSigned + ), + verifyHost: true, + verifyCertificates: true +) + +drop.run(servers: [ + "plaintext": ("vapor.codes", 8080, .none), + "secure": ("vapor.codes", 8443, .tls(config)), +]) +```` \ No newline at end of file diff --git a/2.0/docs/images/droplet-color.svg b/2.0/docs/images/droplet-color.svg new file mode 100644 index 00000000..11c540fb --- /dev/null +++ b/2.0/docs/images/droplet-color.svg @@ -0,0 +1,30 @@ + + + Vapor + The Vapor droplet logo in pink and blue. + + + + + + + + + + \ No newline at end of file diff --git a/2.0/docs/images/droplet-white.svg b/2.0/docs/images/droplet-white.svg new file mode 100644 index 00000000..9f645196 --- /dev/null +++ b/2.0/docs/images/droplet-white.svg @@ -0,0 +1,18 @@ + + + Vapor + The Vapor droplet logo in white. + + + + \ No newline at end of file diff --git a/2.0/docs/index.md b/2.0/docs/index.md new file mode 100644 index 00000000..52790263 --- /dev/null +++ b/2.0/docs/index.md @@ -0,0 +1,115 @@ +# Vapor Documentation + +This is the documentation for Vapor, a Web Framework for Swift that works on iOS, macOS, and Ubuntu; and all of the packages that Vapor offers. + +Vapor is the most used web framework for Swift. It provides a beautifully expressive and easy to use foundation for your next website or API. + +## Where To Start + +If this is your first time using Vapor, head to the [Getting Started](getting-started/install-swift-3-macos.md) section to install Swift and create your first app. + +### Viewing Mediums + +You can read this guide by clicking through the folders and markdown files on [GitHub](https://github.com/vapor/documentation) or through the rendered [website](https://docs.vapor.codes). + +## Other Sources + +Here are some other great places to find information about Vapor. + +### API + +Auto-generated API documentation is located at [api.vapor.codes](http://api.vapor.codes). + +### Stack Overflow + +View or ask questions related to Vapor on Stack Overflow using the [`vapor`](http://stackoverflow.com/questions/tagged/vapor) tag. + +### GitHub + +#### Source Code + +To view the framework's source code and code documentation, visit [Vapor's GitHub](https://github.com/vapor/vapor). + +#### Issues + +To view open bug reports and feature requests, or to create one, visit the [issues](https://github.com/vapor/vapor/issues) tab on [Vapor's GitHub](https://github.com/vapor/vapor). + +## Packages + +Vapor is a modular framework built for a modular language. Code is split up into modules which are grouped to form packages. Packages can be added to your project by adding the package's Git url to your `Package.swift` file. Once a package is included, all of its modules will be available to `import`. You can read more about packages and modules in the Swift Package Manager [conceptual overview](https://swift.org/package-manager/). + +Below is a list of packages and modules that come with or can be used by Vapor projects. Packages will have a link to their respective GitHub page. + +### Included + +Here is a list of all the packages and modules included with Vapor. + +!!! tip + While these packages are included in Vapor by default, they can also be used individually. + +- [Vapor](https://github.com/vapor/vapor): Swift's most used web framework. + - Auth: User authentication and persistance. + - Sessions: Secure, ephemeral cookie based data storage. + - Cookies: HTTP cookies. + - Routing: Advanced router with type-safe parameterization. +- [Engine](https://github.com/vapor/engine): Core transport layers. + - HTTP: Pure Swift HTTP client and server. + - URI: Pure Swift URI parsing and serializing. + - WebSockets: Full-duplex communication channels over a single TCP connection. + - SMTP: Send email using Sendgrid and Gmail. +- [Multipart](https://github.com/vapor/multipart): Fast, streaming, non-blocking multipart parser and serializer. + - Multipart: Parses and serializes `multipart/mixed`. + - FormData: Parses and serializes `multipart/form-data`. +- [JSON](https://github.com/vapor/json): Conveniences for working with JSON in Swift. +- [Console](https://github.com/vapor/console): Swift wrapper for console IO and commands. +- [TLS](https://github.com/vapor/tls): Swift wrapper for CLibreSSL's new TLS. +- [Crypto](https://github.com/vapor/crypto): Cryptography from LibreSSL and Swift. + - Digests: Hashing with and without authentication. + - Ciphers: Encryption and decryption + - Random: Pseudo and cryptographically secure randomness. + - BCrypt: Pure Swift implementation. +- [Node](https://github.com/vapor/node): Data structure for easy type conversions. + - [Polymorphic](https://github.com/vapor/polymorphic): Syntax for easily accessing values from common types like JSON. + - [Path Indexable](https://github.com/vapor/path-indexable): A protocol for powerful subscript access of common types like JSON. +- [Core](https://github.com/vapor/core): Core extensions, type-aliases, and functions that facilitate common tasks. +- [Socks](https://github.com/vapor/socks): Swift C Socket API wrapper. + +### Extras + +These are officially supported packages for Vapor that are not included by default. + +- [Fluent](https://github.com/vapor/fluent): Models, relationships, and querying for NoSQL and SQL databases. +- [MySQL](https://github.com/vapor/mysql): Robust MySQL interface for Swift. + - [MySQL Driver](https://github.com/vapor/mysql-driver): MySQL driver for Fluent. + - [MySQL Provider](https://github.com/vapor/mysql-provider): MySQL provider for Vapor. +- [Leaf](https://github.com/vapor/leaf): An extensible templating language. +- [Redbird](https://github.com/vapor/redbird): Pure-Swift Redis client implemented from the original protocol spec.. + - [Redis Provider](https://github.com/vapor/redis-provider): Redis cache provider for Vapor. +- [JWT](https://github.com/vapor/jwt): JSON Web Tokens in Swift. + - [JWT Provider](https://github.com/vapor/jwt-provider): JWT conveniences for Vapor. + +### Third Party + +These are packages created by community members that work great with Vapor. + +- [PostgreSQL](https://github.com/vapor/postgresql): Robust PostgreSQL interface for Swift. + - [PostgreSQL Driver](https://github.com/vapor/postgresql-driver): PostgreSQL driver for Fluent. + - [PostgreSQL Provider](https://github.com/vapor/postgresql-provider): PostgreSQL provider for Vapor. +- [MongoKitten*](https://github.com/OpenKitten/MongoKitten): Native MongoDB driver for Swift, written in Swift + - [Mongo Driver](https://github.com/vapor/mongo-driver): MongoKitten driver for Fluent. + - [Mongo Provider](https://github.com/vapor/mongo-provider): MongoKitten provider for Vapor. + - [MainecoonVapor](https://github.com/OpenKitten/MainecoonVapor): MongoKitten ORM for Vapor. +- [Kitura Provider](https://github.com/vapor/kitura-provider): Use IBM's Kitura HTTP server in Vapor. +- [SwiftyBeaver](https://github.com/SwiftyBeaver/SwiftyBeaver-Vapor): Adds the powerful logging of SwiftyBeaver to Vapor. +- [APNS](https://github.com/matthijs2704/vapor-apns): Simple APNS Library for Vapor (Swift). +- [VaporS3Signer](https://github.com/JustinM1/VaporS3Signer): Generate V4 Auth Header/Pre-Signed URL for AWS S3 REST API +- [Flock](https://github.com/jakeheis/Flock): Automated deployment of Swift projects to servers + - [VaporFlock](https://github.com/jakeheis/VaporFlock): Use Flock to deploy Vapor applications +- [VaporForms](https://github.com/bygri/vapor-forms): Brings simple, dynamic and re-usable web form handling to Vapor. +- [Jobs](https://github.com/BrettRToomey/Jobs): A minimalistic job/background-task system for Swift. +- [Heimdall](https://github.com/himani93/heimdall): An easy to use HTTP request logger. + + +## Authors + +[Tanner Nelson](mailto:tanner@vapor.codes), [Logan Wright](mailto:logan@vapor.codes), and the hundreds of members of Vapor. diff --git a/2.0/docs/json/json.md b/2.0/docs/json/json.md new file mode 100644 index 00000000..5d6b84ea --- /dev/null +++ b/2.0/docs/json/json.md @@ -0,0 +1,52 @@ +!!! warning + This section may contain outdated information. + +# JSON + +JSON is an integral part of Vapor. It powers Vapor's [Config](../settings/config.md) and is incredibly easy to use in both requests and responses. + +## Request + +JSON is automatically available in `request.data` alongside form-urlencoded data and query data. This allows you to focus on making a great API, not worrying about what content types data will be sent in. + +```swift +drop.get("hello") { request in + guard let name = request.data["name"]?.string else { + throw Abort.badRequest + } + return "Hello, \(name)!" +} +``` + +This will return a greeting for any HTTP method or content type that the `name` is sent as, including JSON. + +### JSON Only + +To specifically target JSON, use the `request.json` property. + +```swift +drop.post("json") { request in + guard let name = request.json?["name"]?.string else { + throw Abort.badRequest + } + + return "Hello, \(name)!" +} +``` +The above snippet will only work if the request is sent with JSON data. + +## Response + +To respond with JSON, simply wrap your data structure with `JSON(node: )` + +```swift +drop.get("version") { request in + return try JSON(node: [ + "version": "1.0" + ]) +} +``` + +## Middleware + +The `JSONMiddleware` is included in the `Droplet`'s middleware by default. You can remove it if you don't want JSON to be parsed. diff --git a/2.0/docs/leaf/leaf.md b/2.0/docs/leaf/leaf.md new file mode 100644 index 00000000..38776e32 --- /dev/null +++ b/2.0/docs/leaf/leaf.md @@ -0,0 +1,184 @@ +!!! warning + This section may contain outdated information. + +# Leaf + +Welcome to Leaf. Leaf's goal is to be a simple templating language that can make generating views easier. There's a lot of great templating languages, use what's best for you, maybe that's Leaf! The goals of Leaf are as follows: + +- Small set of strictly enforced rules +- Consistency +- Parser first mentality +- Extensibility + +## Syntax +### Structure + +Leaf Tags are made up of 4 Elements: + - Token: `#` is the Token + - Name: A `string` that identifies the tag + - Parameter List: `()` May accept 0 or more arguments + - Body (optional): `{}` Must be separated from the Parameter List by a space + +There can be many different usages of these 4 elements depending on the Tag's implementation. Let's look at a few examples of how Leaf's built-in Tags might be used: + + - `#()` + - `#(variable)` + - `#import("template")` + - `#export("link") { }` + - `#index(friends, "0")` + - `#loop(friends, "friend") {
  • #(friend.name)
  • }` + - `#raw() { Anything goes!@#$%^&* }` + +### Using the `#` token in HTML + +The `#` token cannot be escaped. Use the `#()` or `#raw() {}` Tag to output a `#` in a Leaf Template. `#()` => `#` + +### Raw HTML + +All Leaf output is escaped by default. Use the `#raw() {}` Tag for unescaped output. +`#raw() { Link }` => `Link` +> IMPORTANT! Make sure you are not using the `#raw() {}` Tag with user input. + +### Chaining + +The double token: `##` indicates a chain. It can be applied to any standard Tag. If the previous Tag fails, the chained Tag will be given an opportunity to run. + +``` +#if(hasFriends) ##embed("getFriends") +``` + +### Leaf's built-in Tags + +#### Token: `#()` + +``` +#() #()hashtags #()FTW => # #Hashtags #FTW +``` + +#### Raw: `#raw() {}` + +``` +#raw() { + Do whatever w/ #'s here, this code won't be rendered as leaf document and is not escaped. + It's a great place for things like Javascript or large HTML sections. +} +``` + +#### Equal: `#equal(lhs, rhs) {}` + +``` +#equal(leaf, leaf) { Leaf == Leaf } => Leaf == Leaf +#equal(leaf, mustache) { Leaf == Mustache } => +``` + +#### Variable: `#(variable)` + +``` +Hello, #(name)! +``` + +#### Loop: `#loop(object, "index")` + +``` +#loop(friends, "friend") { + Hello, #(friend.name)! +} +``` +#### Index: `#index(object, _ index: Int|String)` + +``` +Hello, #index(friends, 0)! +Hello, #index(friends, "best")! +``` + +#### If - Else: `#if(bool) ##else() { this }` + +``` +#if(entering) { + Hello, there! +} ##if(leaving) { + Goodbye! +} ##else() { + I've been here the whole time. +} +``` + +#### Import: `#import("template")` +#### Export: `#export("template") { Leaf/HTML }` +#### Extend: `#extend("template")` +#### Embed: `#embed("template")` + +> When using these Layout Tags, omit the template file's .leaf extension. + +``` +/// base.leaf + +#import("html") + +/// html.leaf +#extend("base") + +#export("html") { #embed("body") } + +/// body.leaf + +``` + +Leaf renders `html.leaf` as: + +``` + + +``` + +### Custom Tags + +Look at the existing tags for advanced scenarios, let's look at a basic example by creating `Index` together. This tag will take two arguments, an array, and an index to access. + +```swift +class Index: BasicTag { + let name = "index" + + func run(arguments: [Argument]) throws -> Node? { + guard + arguments.count == 2, + let array = arguments[0].value?.nodeArray, + let index = arguments[1].value?.int, + index < array.count + else { return nil } + return array[index] + } +} +``` + +We can now register this Tag in our `main.swift` file with: + +```swift +if let leaf = drop.view as? LeafRenderer { + leaf.stem.register(Index()) +} +``` + +And use it just like we did [above](#index). + +> Note: Use of non-alphanumeric characters in Tag Names is **strongly discouraged** and may be disallowed in future versions of Leaf. + +## Syntax Highlighting + +### Atom + +[language-leaf](https://atom.io/packages/language-leaf) by ButkiewiczP + +### Xcode + +It is not currently possible to implement Leaf Syntax Highlighting in Xcode, however, using Xcode's HTML Syntax Coloring can help a bit. Select one or more Leaf files and then choose Editor > Syntax Coloring > HTML. Your selected Leaf files will now use Xcode's HTML Syntax Coloring. Unfortunately the usefulness of this is limited because this association will be removed when `vapor xcode` is run. + +There appears to be a way to [make Xcode file associations persist](http://stackoverflow.com/questions/9050035/how-to-make-xcode-recognize-a-custom-file-extension-as-objective-c-for-syntax-hi) but that requires a bit more kung-fu. + +### VS Code + +[html-leaf](https://marketplace.visualstudio.com/items?itemName=Francisco.html-leaf) by FranciscoAmado + +### CLion & AppCode + +Some preliminary work has been done to implement a Leaf Plugin for CLion & AppCode but lack of skill and interest in Java has slowed progress! If you have IntelliJ SDK experience and want to help with this, message Tom Holland on [Vapor Slack](http://vapor.team) diff --git a/2.0/docs/routing/basic.md b/2.0/docs/routing/basic.md new file mode 100644 index 00000000..3818838e --- /dev/null +++ b/2.0/docs/routing/basic.md @@ -0,0 +1,145 @@ +!!! warning + This section may contain outdated information. + +# Basic Routing + +Routing is one of the most critical parts of a web framework. The router decides which requests get which responses. + +Vapor has a plethora of functionality for routing including route builders, groups, and collections. In this section, we will look at the basics of routing. + +## Register + +The most basic route includes a method, path, and closure. + +```swift +drop.get("welcome") { request in + return "Hello" +} +``` + +The standard HTTP methods are available including `get`, `post`, `put`, `patch`, `delete`, and `options`. + +```swift +drop.post("form") { request in + return "Submitted with a POST request" +} +``` + +You can also use `any` to match all methods. + +## Nesting + +To nest paths (adding `/`s in the URL), simply add commas. + +```swift +drop.get("foo", "bar", "baz") { request in + return "You requested /foo/bar/baz" +} +``` + +You can also use `/`, but commas are often easier to type and work better with type safe route [parameters](parameters.md). + +## Alternate + +An alternate syntax that accepts a `Method` as the first parameter is also available. + +```swift +drop.add(.trace, "welcome") { request in + return "Hello" +} +``` + +This may be useful if you want to register routes dynamically or use a less common method. + +## Request + +Each route closure is given a single [Request](../http/request.md). This contains all of the data associated with the request that led to your route closure being called. + +## Response Representable + +A route closure can return in three ways: + +- `Response` +- `ResponseRepresentable` +- `throw` + +### Response + +A custom [Response](../http/response.md) can be returned. + +```swift +drop.get("vapor") { request in + return Response(redirect: "http://vapor.codes") +} +``` + +This is useful for creating special responses like redirects. It is also useful for cases where you want to add cookies or other items to the response. + +### Response Representable + +As you have seen in the previous examples, `String`s can be returned in route closures. This is because they conform to [ResponseRepresentable](../http/response-representable.md) + +A lot of types in Vapor conform to this protocol by default: +- String +- Int +- JSON +- Model + +```swift +drop.get("json") { request in + return try JSON(node: [ + "number": 123, + "text": "unicorns", + "bool": false + ]) +} +``` + +> If you are curious about what `node:` means, read more about [Node](https://github.com/vapor/node) + +### Throwing + +If you are unable to return a response, you may `throw` any object that conforms to `Error`. Vapor comes with a default error enum `Abort`. + +```swift +drop.get("404") { request in + throw Abort.notFound +} +``` + +You can customize the message of these errors by using `Abort` + +```swift +drop.get("error") { request in + throw Abort.custom(status: .badRequest, message: "Sorry 😱") +} +``` + +These errors are caught by default in the `AbortMiddleware` where they are turned into a JSON response like the following. + +```json +{ + error: true, + message: "" +} +``` + +If you want to override this behavior, remove the `AbortMiddleware` from the `Droplet`'s middleware and add your own. + +## Fallback + +Fallback routes allow you to match multiple layers of nesting slashes. + +```swift +app.get("anything", "*") { request in + return "Matches anything after /anything" +} +``` + +For example, the above route matches all of the following and more: + +- /anything +- /anything/foo +- /anything/foo/bar +- /anything/foo/bar/baz +- ... diff --git a/2.0/docs/routing/collection.md b/2.0/docs/routing/collection.md new file mode 100644 index 00000000..c315d5dc --- /dev/null +++ b/2.0/docs/routing/collection.md @@ -0,0 +1,81 @@ +!!! warning + This section may contain outdated information. + +# Route Collections + +Route collections allow multiple routes and route groups to be organized in different files or modules. + +## Example + +Here is an example of a route collection for the `v1` portion of an API. + +```swift +import Vapor +import HTTP +import Routing + +class V1Collection: RouteCollection { + typealias Wrapped = HTTP.Responder + func build(_ builder: B) { + let v1 = builder.grouped("v1") + let users = v1.grouped("users") + let articles = v1.grouped("articles") + + users.get { request in + return "Requested all users." + } + + articles.get(Article.self) { request, article in + return "Requested \(article.name)" + } + } +} +``` + +This class could be place in any file, and we could add it to our droplet or even another route group. + +```swift +let v1 = V1Collection() +drop.collection(v1) +``` + +The `Droplet` will then be passed to the `build(_:)` method of your route collection and have the various routes added to it. + +### Breakdown + +For those that are curious, let's break down the route collection line by line to better understand what is going on. + +```swift +typealias Wrapped = HTTP.Responder +``` + +This limits our route collection to adding HTTP responders. While the underlying router is capable of routing any type, Vapor routes HTTP responders exclusively. If we want to use this route collection with Vapor, it's wrapped type needs to match. + +```swift +func build(_ builder: B) { +``` + +This method accepts a route builder and also verifies that the route builder accepts `Wrapped` or, as defined in the last line, `HTTP.Responder`s. Vapor's `Droplet` and any route [group](group.md) created with Vapor are `RouteBuilder`s that accept HTTP responders. + +```swift +let v1 = builder.grouped("v1") +``` + +From there you can create routes with the `builder` as usual. The `builder: B` will work exactly like a `Droplet` or route [group](group.md). Any methods that work there will work on this builder. + + +## Empty Initializable + +You can even add `EmptyInitializable` to your route collection if it has an empty `init` method. This will allow you to add the route collection via its type name. + +```swift +class V1Collection: RouteCollection, EmptyInitializable { + init() { } + ... +``` + +Now we can add the collection without initializing it. + +```swift +drop.collection(V1Collection.self) +``` diff --git a/2.0/docs/routing/controller.md b/2.0/docs/routing/controller.md new file mode 100644 index 00000000..4536e225 --- /dev/null +++ b/2.0/docs/routing/controller.md @@ -0,0 +1,73 @@ +!!! warning + This section may contain outdated information. + +# Introduction + +Instead of defining all of your request handling logic as Closures in route files, you may wish to organize this behavior +using Controller classes. Controllers can group related request handling logic into a single class. Controllers are stored +in the `Sources/App/Controllers` directory. + +# Basic Controller + +## Defining Controllers + +```swift +import Vapor +import HTTP + +final class FirstController { + func index(request: Request) throws -> ResponseRepresentable { + return try JSON(node: [ + "message": "This is FirstController's index method" + ]) + } +} +``` +You can define a route to this controller action like so: + +```swift +drop.get("getindex") {request in + return try FirstController().index(request: request) +} +``` +Now, when a request matches the specified route URI, the Index method on the FirstController +class will be executed. Of course, the route parameters will also be passed to the method. + +-------- + +# Resource Controllers + +Vapor resource routing assigns the typical "CRUD" routes to a controller with a single line of code. + +```swift +drop.resource("URI", Controller()) +``` +This single route declaration creates multiple routes to handle a variety of actions on the resource. +The generated controller will already have methods stubbed for each of these actions, including +notes informing you of the HTTP verbs and URIs they handle. + +| Verb | URI | Action | +| :-------------: | :-------------: | :-----------: | +| GET | test/index | test.index | +| POST | test/create | test.create | +| GET | test/show | test.show | +| PUT | test/replace | test.replace | +| PATCH | test/destroy | test.destroy | +| DELETE | test/destroy | test.destroy | +| DELETE | test/clear | test.clear | + +You can also custom method name, add `makeResource` method in the controller + +```swift + func makeResource() -> Resource { + return Resource( + index: index, + store: create, + show: show, + replace: replace, + modify: update, + destroy: delete, + clear: clear + ) + } +``` diff --git a/2.0/docs/routing/group.md b/2.0/docs/routing/group.md new file mode 100644 index 00000000..1a8bf8ba --- /dev/null +++ b/2.0/docs/routing/group.md @@ -0,0 +1,66 @@ +!!! warning + This section may contain outdated information. + +# Route Groups + +Grouping routes together makes it easy to add common prefixes, middleware, or hosts to multiple routes. + +Route groups have two different forms: Group and Grouped. + +### Group + +Group (without the "ed" at the end) takes a closure that is passed a `GroupBuilder`. + +```swift +drop.group("v1") { v1 in + v1.get("users") { request in + // get the users + } +} +``` + +### Grouped + +Grouped returns a `GroupBuilder` that you can pass around. + +```swift +let v1 = drop.grouped("v1") +v1.get("users") { request in + // get the users +} +``` + +### Middleware + +You can add middleware to a group of routes. This is especially useful for authentication. + +```swift +drop.group(AuthMiddleware()) { authorized in + authorized.get("token") { request in + // has been authorized + } +} +``` + +### Host + +You can limit the host for a group of routes. + +```swift +drop.group(host: "vapor.codes") { vapor + vapor.get { request in + // only responds to requests to vapor.codes + } +} +``` + +### Chaining + +Groups can be chained together. + +```swift +drop.grouped(host: "vapor.codes").grouped(AuthMiddleware()).group("v1") { authedSecureV1 in + // add routes here +} +``` + diff --git a/2.0/docs/routing/parameters.md b/2.0/docs/routing/parameters.md new file mode 100644 index 00000000..c0259f81 --- /dev/null +++ b/2.0/docs/routing/parameters.md @@ -0,0 +1,133 @@ +!!! warning + This section may contain outdated information. + +# Routing Parameters + +Traditional web frameworks leave room for error in routing by using strings for route parameter names and types. Vapor takes advantage of Swift's closures to provide a safer and more intuitive method for accessing route parameters. + +## Type Safe + +To create a type safe route simply replace one of the parts of your path with a `Type`. + +```swift +drop.get("users", Int.self) { request, userId in + return "You requested User #\(userId)" +} +``` + +This creates a route that matches `users/:id` where the `:id` is an `Int`. Here's what it would look like using manual route parameters. + +```swift +drop.get("users", ":id") { request in + guard let userId = request.parameters["id"]?.int else { + throw Abort.badRequest + } + + return "You requested User #\(userId)" +} +``` + +Here you can see that type safe routing saves ~3 lines of code and also prevents runtime errors like misspelling `:id`. + +## String Initializable + +Any type that conforms to `StringInitializable` can be used as a type-safe routing parameter. By default, the following types conform: + +- String +- Int +- Model + +`String` is the most generic and always matches. `Int` only matches when the string supplied can be turned into an integer. `Model` only matches when the string, used as an identifier, can be used to find the model in the database. + +Our previous example with users can be further simplified. + +```swift +drop.get("users", User.self) { request, user in + return "You requested \(user.name)" +} +``` + +Here the identifier supplied is automatically used to lookup a user. For example, if `/users/5` is requested, the `User` model will be asked for a user with identifier `5`. If one is found, the request succeeds and the closure is called. If not, a not found error is thrown. + +Here is what this would look like if model didn't conform to `StringInitializable`. + +```swift +drop.get("users", Int.self) { request, userId in + guard let user = try User.find(userId) else { + throw Abort.notFound + } + + return "You requested User #\(userId)" +} +``` + +Altogether, type safe routing can save around 6 lines of code from each route. + +### Protocol + +Conforming your own types to `StringInitializable` is easy. + +```swift +public protocol StringInitializable { + init?(from string: String) throws +} +``` + +Here is what `Model`'s conformance looks like for those who are curious. + +```swift +extension Model { + public init?(from string: String) throws { + if let model = try Self.find(string) { + self = model + } else { + return nil + } + } +} +``` + +The `init` method can both `throw` and return `nil`. This allows you to `throw` your own errors. Or, if you want the default error and behavior, just return `nil`. + +### Limits + +Type safe routing is currently limited to three path parts. This is usually remedied by adding route [groups](group.md). + +```swift +drop.group("v1", "users") { users in + users.get(User.self, "posts", Post.self) { request, user, post in + return "Requested \(post.name) for \(user.name)" + } +} +``` + +The resulting path for the above example is `/v1/users/:userId/posts/:postId`. If you are clamoring for more type safe routing, please let us know and we can look into increasing the limit of three. + +## Manual + +As shown briefly above, you are still free to do traditional routing. This can be useful for especially complex situations. + +```swift +drop.get("v1", "users", ":userId", "posts", ":postId", "comments", ":commentId") { request in + let userId = try request.parameters.extract("userId") as Int + let postId = try request.parameters.extract("postId") as Int + let commentId = try request.parameters.extract("commentId") as Int + + return "You requested comment #\(commentId) for post #\(postId) for user #\(userId)" +} +``` + +> Property `request.parameters` is used to extract parameters encoded in the URI _path_ (for example, `/v1/users/1` has a parameter `:userId` equal to `"1"`). In case of parameters passed as a part of a _query_ (e.g. `/v1/search-user?userId=1`), the `request.data` should be used (e.g. `let userId = request.data["userId"]?.string`). + +Request parameters can be accessed either as a dictionary or using the `extract` syntax which throws instead of returning an optional. + +### Groups + +Manual request parameters also work with [groups](group.md). + +```swift +let userGroup = drop.grouped("users", ":userId") +userGroup.get("messages") { req in + let user = try req.parameters.extract("userId") as User +} +``` diff --git a/2.0/docs/routing/query-parameters.md b/2.0/docs/routing/query-parameters.md new file mode 100644 index 00000000..b10f98c0 --- /dev/null +++ b/2.0/docs/routing/query-parameters.md @@ -0,0 +1,33 @@ +!!! warning + This section may contain outdated information. + +# Query Parameters + +Request query parameters can be accessed either as a dictionary or using the `extract` syntax which throws instead of returning an optional. + +## Optional Syntax + +Optional syntax is the easiest way to handle optional query parameters. + +```swift +drop.get("comments") { request in + if let rating = request.query?["rating"]?.int { + return "You requested comments with rating greater than #\(rating)" + } + return "You requested all comments" +} +``` + +## Extract Syntax + +Extract syntax might be useful to *enforce* the presence of query parameters and throw an exception if they are not present. +To use this syntax first we need to ensure the query object is present with a `guard`. + +```swift +drop.get("comments") { request in + guard let rating = request.query?["rating"]?.int else { + throw Abort.custom(status: .preconditionFailed, message: "Please include a rating") + } + return "You requested comments with rating greater than #\(rating)" +} +``` diff --git a/2.0/docs/sessions/sessions.md b/2.0/docs/sessions/sessions.md new file mode 100644 index 00000000..4c270b12 --- /dev/null +++ b/2.0/docs/sessions/sessions.md @@ -0,0 +1,76 @@ +!!! warning + This section may contain outdated information. + +# Sessions + +Sessions help you store information about a user between requests. As long as the client supports cookies, sessions are easy to create. + +## Middleware + +Enable sessions on your `Droplet` by adding an instance of `SessionMiddleware`. + +```swift +import Sessions + +let memory = MemorySessions() +let sessions = SessionsMiddleware(sessions: memory) +``` + +Then add to the `Droplet`. + +``` +let drop = Droplet() +drop.middleware.append(sessions) +``` + +> Note: If you'd like to enable or disable the middleware based on config files, check out [middleware](../vapor/middleware.md). + +## Request + +After `SessionMiddleware` has been enabled, you can access the `req.sessions()` method to get access to session data. + +```swift +let data = try req.session().data +``` + +## Example + +Let's create an example that remembers the user's name. + +### Store + +```swift +drop.post("remember") { req in + guard let name = req.data["name"]?.string else { + throw Abort.badRequest + } + + try req.session().data["name"] = Node.string(name) + + return "Remebered name." +} +``` + +On `POST /remember`, fetch a `name` from the request input, then store this name into the session data. + +### Fetch + +On `GET /remember`, fetch the `name` from the session data and return it. + +```swift +drop.get("remember") { req in + guard let name = try req.session().data["name"]?.string else { + return throw Abort.custom(status: .badRequest, message: "Please POST the name first.") + } + + return name +} +``` + +## Cookie + +The session will be stored using the `vapor-session` cookie. + + + + diff --git a/2.0/docs/settings/config.md b/2.0/docs/settings/config.md new file mode 100644 index 00000000..514f4540 --- /dev/null +++ b/2.0/docs/settings/config.md @@ -0,0 +1,184 @@ +!!! warning + This section may contain outdated information. + +# Config + +An application's configuration settings. Cloud applications generally require complex configurations that can adjust based on their environment. Vapor intends to provide a flexible configuration interaction that can be customized for a given user. + +## QuickStart + +For Vapor applications, configuration files are expected to be nested under a top level folder named `Config`. Here's an example of a basic config featuring a single `servers` configuration. + +```bash +./ +├── Config/ +│ ├── servers.json +``` + +And an example of how this might look: + +```JSON +{ + "http": { + "host": "0.0.0.0", + "port": 8080 + } +} +``` + +What that's saying, is that our application should start a single server named 'http' serving port `8080` on host `0.0.0.0`. This represents the following url: `http://localhost:8080`. + +### Custom Keys + +Let's add a custom key to the `servers.json` file: + +```JSON +{ + "http": { + "host": "0.0.0.0", + "port": 8080, + "custom-key": "custom value" + } +} +``` + +This can be accessed from your application's config using the following. + +```swift +let customValue = drop.config["servers", "http", "custom-key"]?.string ?? "default" +``` + +That's it, feel free to add and utilize keys as necessary to make your application configuration easier. + +## Config Syntax + +You can access your config directory with the following syntax. `app.config[<#file-name#>, <#path#>, <#to#>, <#file#>]`. For example, let's hypothesize that in addition to the `servers.json` file we mentioned earlier, there is also a `keys.json` that looks like this: + +```JSON +{ + "test-names": [ + "joe", + "jane", + "sara" + ], + "mongo": { + "url" : "www.customMongoUrl.com" + } +} +``` + +We can access this file by making sure the first argument in our subscript is keys. To get the first name in our list: + +```swift +let name = drop.config["keys", "test-names", 0]?.string ?? "default" +``` + +Or our mongo url: + +```swift +let mongoUrl = drop.config["keys", "mongo", "url"]?.string ?? "default" +``` + +## Advanced Configurations + +Having the default `servers.json` is great, but what about more complex scenarios. For example, what if we want a different host in production and in development? These complex scenarios can be achieved by adding additional folders to our `Config/` directory. Here's an example of a folder structure that's setup for production and development environments. + +```bash +WorkingDirectory/ +├── Config/ +│ ├── servers.json +│ ├── production/ +│ │ └── servers.json +│ ├── development/ +│ │ └── servers.json +│ └── secrets/ +│ └── servers.json +``` + +> You can specify the environment through the command line by using --env=. Custom environments are also available, a few are provided by default: production, development, and testing. + +```bash +vapor run --env=production +``` + +### PRIORITY + +Config files will be accessed in the following priority. + +1. CLI (see below) +2. Config/secrets/ +3. Config/name-of-environment/ +4. Config/ + +What this means is that if a user calls `app.config["servers", "host"]`, the key will be searched in the CLI first, then the `secrets/` directory, then the top level default configs. + +> `secrets/` directory should very likely be added to the gitignore. + +### EXAMPLE + +Let's start with the following JSON files. + +#### `servers.json` + +```JSON +{ + "http": { + "host": "0.0.0.0", + "port": 9000 + } +} +``` + +#### `production/servers.json` + +```JSON +{ + "http": { + "host": "127.0.0.1", + "port": "$PORT" + } +} +``` + +> The `"$NAME"` syntax is available for all values to access environment variables. + +Please notice that `servers.json`, and `production/servers.json` both declare the same keys: `host`, and `port`. In our application, we'll call: + +```swift +// will load 0.0.0.0 or 127.0.0.1 based on above config +let host = drop.config["servers", "http", "host"]?.string ?? "0.0.0.0" +// will load 9000, or environment variable port. +let port = drop.config["servers", "http", "port"]?.int ?? 9000 +``` + +## COMMAND LINE + +In addition to json files nested within the `Config/` directory, we can also use the command line to pass arguments into our config. By default, these values will be set as the "cli" file, but more complex options are also available. + +#### 1. `--KEY=VALUE` + +Arguments set through the command line can be accessed through config's cli file. For example, the following CLI command: + +```bash +--mongo-password=$MONGO_PASSWORD +``` + +would be accessible within your application by using the following: + +```swift +let mongoPassword = drop.config["cli", "mongo-password"]?.string +``` + +#### 2. `--CONFIG:FILE-NAME.KEY=CUSTOM-VALUE` + +If you want command line arguments set to a file besides "cli", you can use this more advanced specification. For example, the following CLI command: + +```bash +--config:keys.analytics=124ZH61F +``` + +would be accessible within your application by using the following: + +```swift +let analyticsKey = drop.config["keys", "analytics"]?.string +``` diff --git a/2.0/docs/stylesheets/extra.css b/2.0/docs/stylesheets/extra.css new file mode 100644 index 00000000..27fff6f2 --- /dev/null +++ b/2.0/docs/stylesheets/extra.css @@ -0,0 +1,48 @@ +.md-header { + box-shadow: 0px 0px 8px #657590!important; +} + +.md-main__inner { + padding-top: 0; +} + +.md-nav__button img { + width: 90%; +} + +.md-logo { + padding: 6px; +} + +.md-sidebar__inner .md-logo { + width: 60px!important; +} + +.md-header-nav__title { + line-height: 4.6rem; +} + +@media only screen and (min-width:75em) { + .md-header-nav__button img { + width: 28px!important; + height: 28px!important; + } + + .md-main__inner { + padding-top: 1rem; + } +} + +@media only screen and (min-width:100em) { + .md-header-nav__button img { + width: 32px!important; + height: 32px!important; + } +} + +@media only screen and (min-width:125em) { + .md-header-nav__button img { + width: 38px!important; + height: 38px!important; + } +} diff --git a/2.0/docs/testing/basic.md b/2.0/docs/testing/basic.md new file mode 100644 index 00000000..c63e1edb --- /dev/null +++ b/2.0/docs/testing/basic.md @@ -0,0 +1,93 @@ +!!! warning + This section may contain outdated information. + +# Basic Testing + +Testing is a critical part of any software application, and Vapor apps should be no different. In this documentation, we'll cover some of the basic setup required to be able to test against our `Droplet`. + +## Displacing Droplet Creation Logic + +Up to this point, a lot of our documentation has centered around putting our `Droplet` creation logic in `main.swift`. Unfortunately, when testing against our application, this code becomes largely inaccessible. The first thing we'll need to do is break this out into the `AppLogic` module. + +Here's an example of my setup file. I name mine `Droplet+Setup.swift`. Here's how it might look: + +```swift +import Vapor + +public func load(_ drop: Droplet) throws { + drop.preparations.append(Todo.self) + + drop.get { _ in return "put my droplet's logic in this `load` function" } + + drop.post("form") { req in + ... + return Response(body: "Successfully posted form.") + } + + // etc. +} +``` + +> [WARNING] Do **not** call `run()` anywhere within the `load` function as `run()` is a blocking call. + +## Updated `main.swift` + +Now that we've abstracted our loading logic, we'll need to update our `main.swift` **in the `App` module** to reflect those changes. Here's how it should look after: + +```swift +let drop = Droplet(...) +try load(drop) +drop.run() +``` + +> The reason we still initialize `Droplet` outside of the scope of `load` is so that we can have the option to initialize differently for testing. We'll cover that soon. + +## Testable Droplet + +The first thing we'll do is in my testing target, add a file called `Droplet+Test.swift`. It will look like this: + +```swift +@testable import Vapor + +func makeTestDroplet() throws -> Droplet { + let drop = Droplet(arguments: ["dummy/path/", "prepare"], ...) + try load(drop) + try drop.runCommands() + return drop +} +``` + +This looks a lot like our initializer in `main.swift`, but there are 3 very key differences. + +### Droplet(arguments: ["dummy/path/", "prepare"], ... + +The `arguments:` parameter in our `Droplet` creation. This is rarely used except for advanced situations, but we'll use it here in testing to ensure that our `Droplet` doesn't try to automatically `serve` and block our thread. You can use arguments besides `"prepare"`, but unless you're doing something specific for an advanced situation, these arguments should suffice. + +### try drop.runCommands() + +You'll notice here that we're calling `runCommands()` instead of `run()`. This allows the `Droplet` to do all the setup it would normally do before booting without actually binding to a socket or exiting. + +### `@testable import Vapor` + +We'll need to import the testable compilation of Vapor to access the `runCommands` function. This is currently not public as a protection against accidental bugs in live apps. + +## Test Our Droplet + +Now that all of this has been created, we're ready to start testing our application's `Droplet`. Here's how a really basic test might look: + +```swift +@testable import AppLogic + +func testEndpoint() throws { + let drop = try makeTestDroplet() + let request = ... + let expectedBody = ... + + let response = try drop.respond(to: request) + XCTAssertEqual(expectedBody, response.body.bytes) +} +``` + +Notice that now you can use `CMD-U` to run your tests in Xcode with in-line results. In addition, you can run `vapor test` to test your code from the command line. If you choose to use `swift build` instead and you are using MySQL in your app, make sure you add the correct build flags to the call. + +Good luck, and happy testing! diff --git a/2.0/docs/testing/modules.md b/2.0/docs/testing/modules.md new file mode 100644 index 00000000..7704b983 --- /dev/null +++ b/2.0/docs/testing/modules.md @@ -0,0 +1,39 @@ +!!! warning + This section may contain outdated information. + +# Using Multiple Modules For Testing + +Testing a Vapor app gets tricky, and requires some maneuvering of your app targets. + +> [WARNING] Technically this is only necessary if you plan to run your tests on Linux. You can keep your tests in the same module if you want to only run your tests from the command line using `vapor test` + +## **Step 1:** Update Package.swift + +To start, you need to split up your Vapor project into a target called `App`, and a target called `AppLogic`. The App module will only include a `main.swift`, and your `AppLogic` will contain the actual logic for the app. + +```swift +import PackageDescription + +let package = Package( + name: “ProjectName”, + targets: [ + Target(name: "App", dependencies: ["AppLogic"]) + ], + dependencies: [ + .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 3) + ], + exclude: [ + "Config", + "Database", + "Localization", + "Public", + "Resources" + ] +) +``` + +## **Step 2:** Update Tests Folder + +Make sure that your tests folder has a file called `LinuxMain.swift` and a folder called `AppLogicTests`. In your `AppLogicTests`, you can add your testing files like `UserTests.swift`. + +As always, make sure that you regenerate with `vapor xcode -y` diff --git a/2.0/docs/vapor/commands.md b/2.0/docs/vapor/commands.md new file mode 100644 index 00000000..d287dfb3 --- /dev/null +++ b/2.0/docs/vapor/commands.md @@ -0,0 +1,44 @@ +!!! warning + This section may contain outdated information. + +# Commands +Custom console commands on Vapor are a breeze. + +## Example +To make a custom console command we must first create a new `.swift` file, import `Vapor` and `Console`, and implement the `Command` protocol. + +```swift +import Vapor +import Console + +final class MyCustomCommand: Command { + public let id = "command" + public let help = ["This command does things, like foo, and bar."] + public let console: ConsoleProtocol + + public init(console: ConsoleProtocol) { + self.console = console + } + + public func run(arguments: [String]) throws { + console.print("running custom command...") + } +} +``` + + - The **id** property is the string you will type in the console to access the command. `.build/debug/App command` will run the Custom Command. + - The **help** property is the help message that will give your custom command's users some idea of how to access it. + - The **console** property is the object passed to your custom command that adheres to the console protocol, allowing manipulation of the console. + - The **run** method is where you put the logic relating to your command. + +After we work our magic in the Custom Command file, we switch over to our `main.swift` file and add the custom command to the droplet like so. +```swift +drop.commands.append(MyCustomCommand(console: drop.console)) +``` +This allows Vapor access to our custom command and lets it know to display it in the `--help` section of the program. + +After compiling the application we can run our custom command like so. + +``` +.build/debug/App command +``` diff --git a/2.0/docs/vapor/controllers.md b/2.0/docs/vapor/controllers.md new file mode 100644 index 00000000..73d52182 --- /dev/null +++ b/2.0/docs/vapor/controllers.md @@ -0,0 +1,142 @@ +# Controllers + +Controllers help you organize related functionality into a single place. They can also be used to create RESTful resources. + +## Basic + +A basic controller looks like the following: + +```swift +import Vapor +import HTTP + +final class HelloController { + func sayHello(_ req: Request) throws -> ResponseRepresentable { + guard let name = req.data["name"]?.string else { + throw Abort(.badRequest) + } + + return "Hello, \(name)" + } +} +``` + +Simple controllers don't need to conform to any protocols. You are free to design them however you see fit. + +### Registering + +The only required structure is the signature of each method in the controller. In order to register this method into the router, it must have a signature like `(Request) throws -> ResponseRepresentable`. `Request` and `ResponseRepresentable` are made available by importing the `HTTP` module. + +```swift +import Vapor +let drop = try Droplet() + +let hc = HelloController() +drop.get("hello", handler: hc.sayHello) +``` + +Since the signature of our `sayHello` method matches the signature of the closure for the `drop.get` method, we can pass it directly. + +### Type Safe + +You can also use controller methods with type-safe routing. + +```swift +final class HelloController { + ... + + func sayHelloAlternate(_ req: Request, _ name: String) -> ResponseRepresentable { + return "Hello, \(name)" + } +} +``` + +We add a new method called `sayHelloAlternate` to the `HelloController` that accepts a second parameter `name: String`. + +```swift +let hc = HelloController() +drop.get("hello", String.self, handler: hc.sayHelloAlternate) +``` + +Since this type-safe `drop.get` accepts a signature `(Request, String) throws -> ResponseRepresentable`, our method can now be used as the closure for this route. + +## Resources + +Controllers that conform to `ResourceRepresentable` can be easily registered into a router as a RESTful resource. Let's look at an example of a `UserController`. + +```swift +final class UserController { + func index(_ request: Request) throws -> ResponseRepresentable { + return try User.all().makeNode().converted(to: JSON.self) + } + + func show(_ request: Request, _ user: User) -> ResponseRepresentable { + return user + } +} +``` + +Here is a typical user controller with an `index` and `show` route. Indexing returns a JSON list of all users and showing returns a JSON representation of a single user. + +We _could_ register the controller like so: + +```swift +let users = UserController() +drop.get("users", handler: users.index) +drop.get("users", User.self, handler: users.show) +``` + +But `ResourceRepresentable` makes this standard RESTful structure easy. + +```swift +extension UserController: ResourceRepresentable { + func makeResource() -> Resource { + return Resource( + index: index, + show: show + ) + } +} +``` + +Conforming `UserController` to `ResourceRepresentable` requires that the signatures of the `index` and `show` methods match what the `Resource` is expecting. + +Here is a peek into the `Resource` class. + +```swift +final class Resource { + typealias Multiple = (Request) throws -> ResponseRepresentable + typealias Item = (Request, Model) throws -> ResponseRepresentable + + var index: Multiple? + var store: Multiple? + var show: Item? + var replace: Item? + var modify: Item? + var destroy: Item? + var clear: Multiple? + var aboutItem: Item? + var aboutMultiple: Multiple? + + ... +} +``` + +Now that `UserController` conforms to `ResourceRepresentable`, registering the routes is easy. + +```swift +let users = UserController() +drop.resource("users", users) +``` + + `drop.resource` will take care of registering only the routes that have been supplied by the call to `makeResource()`. In this case, only the `index` and `show` routes will be supplied. + +!!! note + `drop.resource` also adds useful defaults for OPTIONS requests. These can be overriden. + +## Folder + +Controllers can go anywhere in your application, but they are most often stored in the `App/Controllers/` directory. + +!!! tip + If you are building a large application, you may want to create your controllers in a separate module. This will allow you to perform unit tests on your controllers. For more information on creating modules, see the [modules](../advanced/modules.md) section in Advanced. diff --git a/2.0/docs/vapor/droplet.md b/2.0/docs/vapor/droplet.md new file mode 100644 index 00000000..2132653b --- /dev/null +++ b/2.0/docs/vapor/droplet.md @@ -0,0 +1,218 @@ +# Droplet + +The `Droplet` is a service container that gives you access to many of Vapor's facilities. It is responsible for registering routes, starting the server, appending middleware, and more. + +!!! tip + Normally applications will only have one Droplet. However, for advanced use cases, it is possible to create more than one. + +## Initialization + +As you have probably already seen, the only thing required to create an instance of `Droplet` is to import Vapor. + +```swift +import Vapor + +let drop = try Droplet() + +// your magic here + +drop.run() +``` + +Creation of the `Droplet` normally happens in the `main.swift` file. + +!!! note + For the sake of simplicity, most of the documentations sample code uses just the `main.swift` file. See the [modules](../advanced/modules.md) section in Advanced to learn more about using multiple modules. + +## Environment + +The `environment` property contains the current environment your application is running in. Usually development, testing, or production. + +```swift +if drop.environment == .production { + ... +} +``` + +The environment affects [Config](../settings/config.md) and [Logging](log.md). The environment is `development` by default. To change it, pass the `--env=` flag as an argument. + +```sh +vapor run serve --env=production +``` + +If you are in Xcode, you can pass arguments through the scheme editor. + +!!! warning + Debug logs can reduce the number of requests your application can handle per second. Enable production mode to silence non-critical logs. + +## Working Directory + +The `workDir` property contains a path to the current working directory of the application. Vapor uses this property to find the folders related to your project, such as `Resources`, `Public`, and `Config`. + +```swift +print(drop.workDir) // /var/www/my-project/ +``` + +Vapor automatically determines the working directory in most situations. However, you may need to manually set it for advanced use cases. + +You can override the working directory through the `Droplet`'s initializer, or by passing the `--workdir` argument. + +```sh +vapor run serve --workdir="/var/www/my-project" +``` + +## Modifying Properties + +The `Droplet`'s properties can be changed programmatically or through configuration. + +### Programmatic + +Properties on the `Droplet` can be changed after it is initialized. + +```swift +let drop = Droplet() + +drop.server = MyServerType.self +``` + +Here the type of server the `Droplet` uses is changed to a custom type. When the `Droplet` is run, this custom server type will be booted instead of the default server. + +### Configurable + +If you want to modify a property of the `Droplet` only in certain cases, you can use `addConfigurable`. Say for example you want to email error logs to yourself in production, but you don't want to spam your inbox while developing. + +```swift +let drop = Droplet() + +drop.addConfigurable(log: MyEmailLogger.self, name: "email") +``` + +The `Droplet` will continue to use the default logger until you modify the `Config/droplet.json` file to point to your email logger. If this is done in `Config/production/droplet.json`, then your logger will only be used in production. + +```json +{ + "log": "email" +} +``` + +#### Supported Properties + +| Property | Type | `droplet.json` key | Config Initializable | +|------------|---------------------|----------------------------|----------------------| +| server | ServerProtocol.Type | server | no | +| client | ClientProtocol.Type | client | no | +| log | LogProtocol | log | yes | +| hash | HashProtocol | hash | yes | +| cipher | CipherProtocol | cipher | yes | +| middleware | Middleware | middleware.[server,client] | no | +| console | ConsoleProtocol | console | yes | +| cache | CacheProtocol | cache | yes | + +#### Example + +Let's create a custom logger to demonstrate Vapor's configurable properties. + +`AllCapsLogger.swift` +```swift +final class AllCapsLogger: LogProtocol { + var enabled: [LogLevel] = [] + func log(_ level: LogLevel, message: String, file: String, function: String, line: Int) { + print(message.uppercased + "!!!") + } +} +``` + +Now add the logger to the Droplet using the `addConfigurable` method for logs. + +`main.swift` +```swift +let drop = try Droplet() + +drop.addConfigurable(log: AllCapsLogger(), name: "all-caps") +``` + +Whenever the `"log"` property is set to `"all-caps"` in the `droplet.json`, our new logger will be used. + +`Config/development/droplet.json` +```json +{ + "log": "all-caps" +} +``` + +Here we are setting our logger only in the `development` environment. All other environments will use Vapor's default logger. + +#### Config Initializable + +For an added layer of convenience, you can allow your custom types to be initialized from configuration files. + +In our previous example, we initialized an `AllCapsLogger` before adding it to the Droplet. + +Let's say we want to allow our project to configure how many exclamation points get added with each log message. + +`AllCapsLogger.swift` +```swift +final class AllCapsLogger: LogProtocol { + var enabled: [LogLevel] = [] + let exclamationCount: Int + + init(exclamationCount: Int) { + self.exclamationCount = exclamationCount + } + + func log(_ level: LogLevel, message: String, file: String, function: String, line: Int) { + print(message.uppercased + String(repeating: "!", count: exclamationCount)) + } +} + +extension AllCapsLogger: ConfigInitializable { + init(config: Config) throws { + let count = config["allCaps", "exclamationCount"]?.int ?? 3 + self.init(exclamationCount: count) + } +} +``` + +!!! note + The first parameter to `config` is the name of the file. + +Now that we have conformed our logger to `ConfigInitializable`, we can pass just the type name to `addConfigurable`. + + +`main.swift` +```swift +let drop = try Droplet() + +drop.addConfigurable(log: AllCapsLogger.self, name: "all-caps") +``` + +Now if you add a file named `allCaps.json` to the `Config` folder, you can configure the logger. + +`allCaps.json` +```json +{ + "exclamationCount": 5 +} +``` + +With this configurable abstraction, you can easily change how your application functions in different environments without needing to hard code these values into your source code. + +## Initialization + +The `Droplet` init method is fairly simple since most properties are variable and can be changed after initialization. + +Most plugins for Vapor come with a [Provider](provider.md), these take care of configuration details for you. + +```swift +Droplet( + arguments: [String]?, + workDir workDirProvided: String?, + config configProvided: Config?, + localization localizationProvided: Localization?, +) +``` + +!!! warning + Remember that the Droplet's properties are initialized with usable defaults. This means that if you change a property, you must be sure to change it _before_ other parts of your code use it. + + diff --git a/2.0/docs/vapor/folder-structure.md b/2.0/docs/vapor/folder-structure.md new file mode 100644 index 00000000..102f00a1 --- /dev/null +++ b/2.0/docs/vapor/folder-structure.md @@ -0,0 +1,85 @@ +# Folder Structure + +The first step to creating an awesome application is knowing where things are. If you created your project using the [Toolbox](../getting-started/install-toolbox.md) or from a template, you will already have the folder structure created. + +If you are making a Vapor application from scratch, this will show you exactly how to set it up. + +## Minimum Folder Structure + +We recommend putting all of your Swift code inside of the `App/` folder. This will allow you to create subfolders in `App/` to organize your models and resources. + +This works best with the Swift package manager's restrictions on how packages should be structured. + +``` +. +├── App +│ └── main.swift +├── Public +└── Package.swift +``` + +The `Public` folder is where all publicly accessible files should go. This folder will be automatically checked every time a URL is requested that is not found in your routes. + +!!! note + The `FileMiddleware` is responsible for accessing files from the `Public` folder. + +## Models + +The `Models` folder is a recommendation of where you can put your database and other models. + +``` +. +├── App +. └── Models +. └── User.swift +``` + +## Controllers + +The `Controllers` folder is a recommendation of where you can put your route controllers. + +``` +. +├── App +. └── Controllers +. └── UserController.swift +``` + +## Views + +The `Views` folder in `Resources` is where Vapor will look when you render views. + +``` +. +├── App +└── Resources + └── Views + └── user.html +``` + +The following code would load the `user.html` file. + +```swift +drop.view.make("user.html") +``` + +## Config + +Vapor has a sophisticated configuration system that involves a hierarchy of configuration importance. + +``` +. +├── App +└── Config + └── app.json // default app.json + └── development + └── app.json // overrides app.json when in development environment + └── production + └── app.json // overrides app.json when in production environment + └── secrets + └── app.json // overrides app.json in all environments, ignored by git +``` + +`.json` files are structured in the `Config` folder as shown above. The configuration will be applied dependant on where the `.json` file exists in the hierarchy. Learn more in [Config](../settings/config.md). + +Learn about changing environments (the `--env=` flag) in the [Droplet](droplet.md) section. diff --git a/2.0/docs/vapor/hash.md b/2.0/docs/vapor/hash.md new file mode 100644 index 00000000..6780b2c2 --- /dev/null +++ b/2.0/docs/vapor/hash.md @@ -0,0 +1,165 @@ +# Hash + +Hashing is a one way method of converting arbitrary data into a fixed size format. Unlike ciphers, data that is hashed cannot be retrieved from the resulting digest. Hashes can be used to create keys, file identifiers, or store credentials. + +Hash function diagram + +> Hash function diagram from [Wikipedia](https://en.wikipedia.org/wiki/Hash_function). + +!!! warning + Avoid storing password hashes if possible. If you must, please make sure to research the state of the art before continuing. + +## Make + +To hash a string, use the `hash` property on `Droplet`. + +```swift +let digest = try drop.hash.make("vapor") +print(digest.string) +``` + +### Checking + +Some hashing algorithms create different hash digests for the same message. Because of this, it is necessary to check your hashes using the `check` method. + +```swift +let matches = try drop.hash.check("vapor", matchesHash: digest) +``` + +## CryptoHasher + +By default, Vapor uses a SHA-256 hasher. You can change this in the configuration files or by giving the `Droplet` a different hasher. + +### Configuration + +`Config/crypto.json` +```json +{ + "hash": { + "method": "sha256", + "encoding": "hex", + "key": "password" + }, + ... +} +``` + +#### Encoding + +The CryptoHasher supports three methods of encoding. + +- `hex` +- `base64` +- `plain` + +#### Key + +Supplying a key will cause the hasher to produce _keyed_ hashes using HMAC. Some hashers require a key. + +#### Supported + +| Name | Method | Requires Key | +|--------------|-------------|--------------| +| SHA-1 | sha1 | no | +| SHA-224 | sha224 | no | +| SHA-256 | sha256 | no | +| SHA-384 | sha384 | no | +| SHA-512 | sha512 | no | +| MD4 | md4 | no | +| MD5 | md5 | no | +| RIPEMD-160 | ripemd160 | no | +| Whirlpool | whirlpool | yes | +| Streebog-256 | streebog256 | yes | +| Streebog-512 | streebog512 | yes | +| GostR341194 | gostr341194 | yes | + +### Manual + +Hashers can be swapped without the use of configuration files. + +#### Hash + +```swift +let drop = try Droplet() + +drop.hash = CryptoHasher( + hash: .sha256, + encoding: .hex +) +``` + +#### HMAC + +```swift +let drop = try Droplet() + +drop.hash = CryptoHasher( + hmac: .sha256, + encoding: .hex, + key: "password".makeBytes() +) +``` + +## BCryptHasher + +BCrypt is a password hashing function that automatically incorporates salts and offers a configurable work factor. The work factor can be used to increase the computation required to generate a hash + +!!! seealso + Learn more about [key stretching](https://en.wikipedia.org/wiki/Key_stretching) on Wikipedia. + +### Configuration + +To use the BCryptHasher instead of the CryptoHasher, change the `"hash"` key in the `droplet.json` configuration file. + +`Config/droplet.json` +```json +{ + ..., + "hash": "bcrypt", + ... +} +``` + +To configure the work factor, add a `bcrypt.json` file. + +`Config/bcrypt.json` +```json +{ + "workFactor": 8 +} +``` + +!!! tip + You can use different BCrypt work factors for production and development modes to keep password hashing fast while working on a project. + +### Manual + +You can manually assign a `BCryptHasher` to `drop.hash`. + +```swift +let drop = try Droplet() + +drop.hash = BCryptHasher(workFactor: 8) +``` + +## Advanced + +### Custom + +You can also create your own hasher. You just need to conform to the `Hash` protocol. + +```swift +/// Creates hash digests +public protocol HashProtocol { + /// Given a message, this method + /// returns a hashed digest of that message. + func make(_ message: Bytes) throws -> Bytes + + /// Checks whether a given digest was created + /// by the supplied message. + /// + /// Returns true if the digest was created + /// by the supplied message, false otherwise. + func check(_ message: Bytes, matchesHash: Bytes) throws -> Bool +} +``` diff --git a/2.0/docs/vapor/log.md b/2.0/docs/vapor/log.md new file mode 100644 index 00000000..7edad27b --- /dev/null +++ b/2.0/docs/vapor/log.md @@ -0,0 +1 @@ +Logging... \ No newline at end of file diff --git a/2.0/docs/vapor/middleware.md b/2.0/docs/vapor/middleware.md new file mode 100644 index 00000000..e5a1596d --- /dev/null +++ b/2.0/docs/vapor/middleware.md @@ -0,0 +1,276 @@ +--- +currentMenu: guide-middleware +--- + +# Middleware + +Middleware is an essential part of any modern web framework. It allows you to modify requests and responses as they pass between the client and your server. + +You can imagine middleware as a chain of logic connecting your server to the client requesting your web app. + +## Version Middleware + +As an example, let's create a middleware that will add the version of our API to each response. The middleware would look something like this: + +```swift +final class VersionMiddleware: Middleware { + func respond(to request: Request, chainingTo next: Responder) throws -> Response { + let response = try next.respond(to: request) + + response.headers["Version"] = "API v1.0" + + return response + } +} +``` + +We then supply this middleware to our `Droplet`. + +```swift +let drop = Droplet() +drop.middleware.append(VersionMiddleware()) +``` + +You can imagine our `VersionMiddleware` sitting in the middle of a chain that connects the client and our server. Every request and response that hits our server must go through this chain of middleware. + +![Middleware](https://cloud.githubusercontent.com/assets/1342803/17382676/0b51d6d6-59a0-11e6-9cbb-7585b9ab9803.png) + + +### Breakdown + +Let's break down the middleware line by line. + +```swift +let response = try next.respond(to: request) +``` + +Since the `VersionMiddleware` in this example is not interested in modifying the request, we immediately ask the next middleware in the chain to respond to the request. This goes all the way down the chain to the `Droplet` and comes back with the response that should be sent to the client. + +```swift +response.headers["Version"] = "API v1.0" +``` + +We then _modify_ the response to contain a Version header. + +```swift +return response +``` + +The response is returned and will chain back up any remaining middleware and back to the client. + +## Request + +The middleware can also modify or interact with the request. + +```swift +func respond(to request: Request, chainingTo next: Responder) throws -> Response { + guard request.cookies["token"] == "secret" else { + throw Abort(.badRequest) + } + + return try next.respond(to: request) +} +``` + +This middleware will require that the request has a cookie named `token` that equals `secret` or else the request will be aborted. + +## Errors + +Middleware is the perfect place to catch errors thrown from anywhere in your application. When you let the middleware catch errors, you can remove a lot of duplicated logic from your route closures. Take a look at the following example: + +```swift +enum FooError: Error { + case fooServiceUnavailable +} +``` + +Say there is a custom error that either you defined or one of the APIs you are using `throws`. This error must be caught when thrown, or else it will end up as an internal server error (500) which may be unexpected to a user. The most obvious solution is to catch the error in the route closure. + +```swift +app.get("foo") { request in + let foo: Foo + do { + foo = try getFooFromService() + } catch { + throw Abort(.badRequest) + } + + // continue with Foo object +} +``` + +This solution works, but it would get repetitive if multiple routes need to handle the error. Luckily, this error could be caught in a middleware instead. + +```swift +final class FooErrorMiddleware: Middleware { + func respond(to request: Request, chainingTo next: Responder) throws -> Response { + do { + return try next.respond(to: request) + } catch FooError.fooServiceUnavailable { + throw Abort( + .badRequest, + reason: "Sorry, we were unable to query the Foo service." + ) + } + } +} +``` + +We just need to append this middleware to the `Droplet`. + +```swift +drop.middleware.append(FooErrorMiddleware()) +``` + +Now our route closures look a lot better and we don't have to worry about code duplication. + +```swift +app.get("foo") { request in + let foo = try getFooFromService() + + // continue with Foo object +} +``` + +## Route Groups + +For more granularity, Middleware can be applied to specific route groups. + +```swift +let authed = drop.grouped(AuthMiddleware()) +authed.get("secure") { req in + return Secrets.all().makeJSON() +} +``` + +Anything added to the `authed` group must pass through `AuthMiddleware`. Because of this, we can assume all traffic to `/secure` has been authorized. Learn more in [Routing](../routing/group). + +## Configuration + +Appending middleware to the `drop.middleware` array is the simplest way to add middleware--it will be used every time the application starts. + +You can also use the [configuration](../settings/config.md) files to enabled or disable middleware for more control. This is especially useful if you have middleware that should, for example, run only in production. + +Appending configurable middleware looks like the following: + +```swift +let drop = Droplet() +drop.addConfigurable(middleware: myMiddleware, name: "my-middleware") +``` + +Then, in the `Config/droplet.json` file, add `my-middleware` to the appropriate `middleware` array. + +```json +{ + ... + "middleware": { + "server": [ + ... + "my-middleware", + ... + ], + "client": [ + ... + ] + }, + ... +} +``` + +If the name of the added middleware appears in the `server` array for the loaded configuration, it will be added to the server's middleware when the application boots. + +Likewise, if the middleware appears in the `client` array for the loaded configuration, it will be added to the client's middleware. + +One middleware can be appended to both the Client and the Server, and can be added multiple times. The ordering of middleware is respected. + +## Advanced + +### Extensions + +Middleware pairs great with request/response extensions and storage. This example shows you how to dynamically return either HTML or JSON responses for a Model depending on the type of client. + +#### Middleware + +```swift +final class PokemonMiddleware: Middleware { + let view: ViewProtocol + init(_ view: ViewProtocol) { + self.view = view + } + + func respond(to request: Request, chainingTo next: Responder) throws -> Response { + let response = try next.respond(to: request) + + if let pokemon = response.pokemon { + if request.accept.prefers("html") { + response.view = try view.make("pokemon.mustache", pokemon) + } else { + response.json = try pokemon.makeJSON() + } + } + + return response + } +} +``` + +#### Response + +And the extension to `Response`. + +```swift +extension Response { + var pokemon: Pokemon? { + get { return storage["pokemon"] as? Pokemon } + set { storage["pokemon"] = newValue } + } +} +``` + +In this example, we added a new property to response capable of holding a Pokémon object. If the middleware finds a response with one of these Pokémon objects, it will dynamically check whether the client prefers HTML. If the client is a browser like Safari and prefers HTML, it will return a Mustache view. If the client does not prefer HTML, it will return JSON. + +#### Usage + +Your closures can now look something like this: + +```swift +import Vapor +import HTTP + +let drop = try Droplet() + +let pokemonMiddleware = PokemonMiddleware(drop.view) +drop.middleware.append(pokemonMiddleware) + +drop.get("pokemon", Pokemon.self) { request, pokemon in + let response = Response() + response.pokemon = pokemon + return response +} +``` + +#### Response Representable + +If you want to go a step further, you can make `Pokemon` conform to `ResponseRepresentable`. + +```swift +import HTTP + +extension Pokemon: ResponseRepresentable { + func makeResponse() throws -> Response { + let response = Response() + response.pokemon = self + return response + } +} +``` + +Now your route closures are greatly simplified. + +```swift +drop.get("pokemon", Pokemon.self) { request, pokemon in + return pokemon +} +``` + +Middleware is incredibly powerful. Combined with extensions, it allows you to add functionality that feels native to the framework. diff --git a/2.0/docs/vapor/provider.md b/2.0/docs/vapor/provider.md new file mode 100644 index 00000000..9fd754fe --- /dev/null +++ b/2.0/docs/vapor/provider.md @@ -0,0 +1,122 @@ +# Provider + +The `Provider` protocol creates a simple and predictable way for adding functionality and third party packages to your Vapor project. + +## Adding a Provider + +Adding a provider to your application takes 2-3 steps. + +### Add Package + +All of Vapor's providers end with the `-provider` syntax. You can see a list of [available providers](https://github.com/vapor?utf8=✓&q=-provider) by searching on our GitHub. + +To add the provider to your package, add it as a dependency in your `Package.swift` file. + +```swift +let package = Package( + name: "MyApp", + dependencies: [ + .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2), + .Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 2) + ] +) +``` + +!!! warning + Always run `vapor update` or `vapor clean` after editing your `Package.swift` file. + +### Import + +Once the provider has been added, you can import it using `import VaporFoo` where `Foo` is the name of the provider. + +Here is what importing the MySQL provider looks like: + +```swift +import Vapor +import VaporMySQL +``` + +### Add to Droplet + +Every provider comes with a class named `Provider`. Add this class to your Droplet using the `addProvider` method. + +```swift +let drop = Droplet() + +try drop.addProvider(VaporMySQL.Provider.self) + +// ... + +drop.run() +``` + +### Configuration + +Some drivers may require a configuration file. For example, `VaporMySQL` requires a `Config/mysql.json` file like the following: + +```json +{ + "host": "localhost", + "user": "root", + "password": "", + "database": "vapor" +} +``` + +You will receive an error during the `Droplet`'s initialization if a configuration file is required. + +!!! tip + Storing sensitive configuration files (ones that contain passwords) in the `Config/secrets` folder will prevent them from being tracked by git. + +### Manual + +Some providers can be configured manually by using the Provider's init method. This method can be used instead of configuration files. + +```swift +let mysqlProvider = VaporMySQL.Provider(host: "localhost", user: "root", password: "", database: "vapor") +try drop.addProvider(mysqlProvider) +``` + +## Create a Provider + +Creating a provider is easy, you just need to create a package with a class `Provider` that conforms to `Vapor.Provider`. + +### Example + +Here is what a provider for an example `Foo` package would look like. All the provider does is take a message, then print the message when the `Droplet` starts. + +```swift +import Vapor + +public final class Provider: Vapor.Provider { + public let message: String + + public convenience init(config: Config) throws { + guard let message = config["foo", "message"].string else { + throw ConfigError.missing(key: ["message"], file: "foo", desiredType: String.self) + } + + self.init(message: message) + } + + public init(message: String) { + self.message = message + } + + public func boot(_ drop: Droplet) { } + + public func beforeRun(_ drop: Droplet) { + drop.console.info(message) + } +} +``` + +This provider wil require a `Config/foo.json` file that looks like: + +```json +{ + "message": "The message to output" +} +``` + +The provider can also be initialized manually with the `init(message: String)` init. diff --git a/2.0/docs/vapor/validation.md b/2.0/docs/vapor/validation.md new file mode 100644 index 00000000..cec1949d --- /dev/null +++ b/2.0/docs/vapor/validation.md @@ -0,0 +1,105 @@ +!!! warning + This section may contain outdated information. + +# Validation + +Vapor provides a few different ways to validate data coming into your application. Let's start by looking at the most common. + +## Common Usage + +Several useful convenience validators are included by default. You can use these to validate data coming into your application, or combine them and create your own. + +Let's look at the most common way to validate data. + +```swift +class Employee { + var email: Valid + var name: Valid + + init(request: Request) throws { + name = try request.data["name"].validated() + email = try request.data["email"].validated() + } +} +``` + +Here we have a typical Employee model with an `email` and `name` property. By declaring both of these properties as `Valid<>`, you are ensuring that these properties can only ever contain valid data. The Swift type checking system will prevent anything that does not pass validation from being stored. + +To store something in a `Valid<>` property, you must use the `.validated()` method. This is available for any data returned by `request.data`. + +`Email` is a real `validator` included with Vapor, but `Name` is not. Let's take a look at how you can create a Validator. + +```swift +Valid +Valid +Valid> +Valid> +Valid> +Valid> +Valid> +``` + +## Validators vs. ValidationSuites + +Validators, like `Count` or `Contains` can have multiple configurations. For example: + +```swift +let name: Valid> = try "Vapor".validated(by: Count.max(5)) +``` + +Here we are validating that the `String` is at most 5 characters long. The type of `Valid` tells us that the string has been validated to be a certain count, but it does not tell us exactly what that count was. The string could have been validated to be less than three characters or more than one million. + +Because of this, `Validators` themselves are not as type safe as some applications might desire. `ValidationSuites` fix this. They combine multiple `Validators` and/or `ValidationSuites` together to represent exactly what type of data should be considered valid. + +## Custom Validator + +Here is how to create a custom `ValidationSuite`. + +```swift +class Name: ValidationSuite { + static func validate(input value: String) throws { + let evaluation = OnlyAlphanumeric.self + && Count.min(5) + && Count.max(20) + + try evaluation.validate(input: value) + } +} +``` + +You only have to implement one method. In this method, use any other validators or logic to create your custom validator. Here we are defining a `Name` as only accepting alphanumeric Strings that are between 5 and 20 characters. + +Now we can be sure that anything of type `Valid` follows these rules. + +## Combining Validators + +In the `Name` validator, you can see that `&&` is being used to combine validators. You can use `&&` as well as `||` to combine any validator as you would boolean values with an `if` statement. + +You can also use `!` to invert the validator. + +```swift +let symbols = input.validated(by: !OnlyAlphanumeric.self) +``` + +## Testing Validity + +While `validated() throw` is the most common method for validating, there are two others. + +```swift +let passed = input.passes(Count.min(5)) +let valid = try input.tested(Count.min(5)) +``` + +`passes()` returns a boolean indicating whether or not the test passed. `tested()` will throw if the validation does not pass. But unlike `validated()` which returns a `Valid<>` type, `tested()` returns the original type of the item it was called on. + +## Validation Failures + +Vapor will automatically catch validation failures in the `ValidationMiddleware`. But you can catch them on your own, or customize responses for certain types of failures. + +```swift +do { + //validation here +} catch let error as ValidationErrorProtocol { + print(error.message) +} +``` diff --git a/2.0/docs/vapor/views.md b/2.0/docs/vapor/views.md new file mode 100644 index 00000000..3c979a14 --- /dev/null +++ b/2.0/docs/vapor/views.md @@ -0,0 +1,54 @@ +# Views + +Views return HTML data from your application. They can be created from pure HTML documents or passed through renderers such as [Leaf](../leaf/leaf.md). + +## Views Directory + +Views are stored in `Resources/Views`. They are created by calling the `view` method on `Droplet`. + +## HTML + +Returning HTML, or any other non-rendered document, is simple. Just use the path of the document relative to the views directory. + +```swift +drop.get("html") { request in + return try drop.view.make("index.html") +} +``` + +## Templating + +Templated documents like [Leaf](../leaf/leaf.md) can take a `Context`. + +```swift +drop.get("template") { request in + return try drop.view.make("welcome", [ + "message": "Hello, world!" + ]) +} +``` + +This context will be rendered in the view dynamically based on the `ViewRenderer` used. + +## Public Resources + +Any resources that your views need, such as images, styles, and scripts, should be placed in the `Public` folder at the root of your application. + +## View Renderer + +Any class that conforms to `ViewRenderer` can be added to our droplet. + +```swift +import Vapor +import VaporLeaf + +let drop = Droplet() + +drop.view = LeafRenderer(viewsDir: drop.viewsDir) +``` + +## Available Renderers + +These renderers can be added to your application through [Providers](provider.md). + +- [Leaf](https://github.com/vapor/leaf) diff --git a/2.0/docs/websockets/custom.md b/2.0/docs/websockets/custom.md new file mode 100644 index 00000000..6dac1b57 --- /dev/null +++ b/2.0/docs/websockets/custom.md @@ -0,0 +1,57 @@ +!!! warning + This section may contain outdated information. + +# Custom WebSockets + +Below are some examples of WebSockets using the underlying Engine package. + +## Client + +```Swift +import WebSockets + +try WebSocket.connect(to: url) { ws in + print("Connected to \(url)") + + ws.onText = { ws, text in + print("[event] - \(text)") + } + + ws.onClose = { ws, _, _, _ in + print("\n[CLOSED]\n") + } +} +``` + +## Server + +```Swift +import HTTP +import WebSockets +import Transport + +final class MyResponder: Responder { + func respond(to request: Request) throws -> Response { + return try request.upgradeToWebSocket { ws in + print("[ws connected]") + + ws.onText = { ws, text in + print("[ws text] \(text)") + try ws.send("🎙 \(text)") + } + + ws.onClose = { _, code, reason, clean in + print("[ws close] \(clean ? "clean" : "dirty") \(code?.description ?? "") \(reason ?? "")") + } + } + } +} + +let port = 8080 +let server = try Server, Serializer>(port: port) + +print("Connect websocket to http://localhost:\(port)/") +try server.start(responder: MyResponder()) { error in + print("Got server error: \(error)") +} +``` diff --git a/2.0/docs/websockets/droplet.md b/2.0/docs/websockets/droplet.md new file mode 100644 index 00000000..aa57d206 --- /dev/null +++ b/2.0/docs/websockets/droplet.md @@ -0,0 +1,58 @@ +!!! warning + This section may contain outdated information. + +# Droplet WebSockets + +Creating a WebSocket server with the Droplet is easy. WebSockets work by upgrading an HTTP request to a WebSocket connection. + +Because of this, you should pick a URL for your WebSocket server to reside at. In this case, we use `/ws`. + +```swift +import Vapor + +let drop = Droplet() + +drop.socket("ws") { req, ws in + print("New WebSocket connected: \(ws)") + + // ping the socket to keep it open + try background { + while ws.state == .open { + try? ws.ping() + drop.console.wait(seconds: 10) // every 10 seconds + } + } + + ws.onText = { ws, text in + print("Text received: \(text)") + + // reverse the characters and send back + let rev = String(text.characters.reversed()) + try ws.send(rev) + } + + ws.onClose = { ws, code, reason, clean in + print("Closed.") + } +} + +drop.run() +``` + +To connect with a WebSocket client, you would open a connection to `ws:///ws`. + +Here is an example using JavaScript. + +```swift +var ws = new WebSocket("ws://0.0.0.0:8080/ws") + +ws.onmessage = function(msg) { + console.log(msg) +} + +ws.onopen = function(event) { + ws.send("test") +} +``` + +The above will log `tset` (`test` reversed). diff --git a/2.0/mkdocs.yml b/2.0/mkdocs.yml new file mode 100644 index 00000000..1cc59d63 --- /dev/null +++ b/2.0/mkdocs.yml @@ -0,0 +1,87 @@ +site_name: 'Vapor Docs' +copyright: 'Copyright © 2017 Qutheory, LLC' + +pages: +- Overview: 'index.md' +- Getting started: + - 'Install Swift 3.1: macOS': 'getting-started/install-swift-3-macos.md' + - 'Install Swift 3.1: Ubuntu': 'getting-started/install-swift-3-ubuntu.md' + - 'Install Toolbox': 'getting-started/install-toolbox.md' + - 'Hello, World': 'getting-started/hello-world.md' + - 'Manual': 'getting-started/manual.md' + - 'Xcode': 'getting-started/xcode.md' +- Vapor: + - 'Folder Structure': 'vapor/folder-structure.md' + - 'Droplet': 'vapor/droplet.md' + - 'Views': 'vapor/views.md' + - 'Controllers': 'vapor/controllers.md' + - 'Middleware': 'vapor/middleware.md' + - 'Validation': 'vapor/validation.md' + - 'Provider': 'vapor/provider.md' + - 'Hash': 'vapor/hash.md' + - 'Log': 'vapor/log.md' + - 'Commands': 'vapor/commands.md' +- Settings: + - 'Config': 'settings/config.md' +- JSON: + - 'JSON': 'json/json.md' +- Routing: + - 'Basic': 'routing/basic.md' + - 'Route Parameters': 'routing/parameters.md' + - 'Query Parameters': 'routing/query-parameters.md' + - 'Group': 'routing/group.md' + - 'Collection': 'routing/collection.md' +- Fluent: + - 'Driver': 'fluent/driver.md' + - 'Model': 'fluent/model.md' + - 'Query': 'fluent/query.md' + - 'Relation': 'fluent/relation.md' +- Auth: + - 'User': 'auth/user.md' + - 'Middleware': 'auth/middleware.md' + - 'Request': 'auth/request.md' + - 'Protect': 'auth/protect.md' +- Sessions: + - 'Sessions': 'sessions/sessions.md' +- HTTP: + - 'Request': 'http/request.md' + - 'Response': 'http/response.md' + - 'Body': 'http/body.md' + - 'ResponseRepresentable': 'http/response-representable.md' + - 'Responder': 'http/responder.md' + - 'Client': 'http/client.md' + - 'Server': 'http/server.md' + - 'CORS': 'http/cors.md' +- Leaf: + - 'Overview': 'leaf/leaf.md' +- Advanced: + - 'Modules': 'advanced/modules.md' + +markdown_extensions: + - admonition + - codehilite(guess_lang=false) + - footnotes + - meta + - toc(permalink=true) + +theme: 'material' +theme_dir: 'vapor-material' +repo_url: https://github.com/vapor/documentation + +extra_css: + - 'stylesheets/extra.css' +edit_uri: edit/master/2.0/docs/ +extra: + logo: 'images/droplet-white.svg' + social: + - type: 'twitter' + link: 'https://twitter.com/@codevapor' + - type: 'slack' + link: 'http://vapor.team/' + font: + text: 'Roboto Slab' + code: 'Source Code Pro' + +google_analytics: + - 'UA-76177358-4' + - 'auto' diff --git a/2.0/vapor-material/404.html b/2.0/vapor-material/404.html new file mode 100644 index 00000000..52beb3b8 --- /dev/null +++ b/2.0/vapor-material/404.html @@ -0,0 +1,4 @@ +{% extends "base.html" %} +{% block content %} +

    404 - Not found

    +{% endblock %} diff --git a/2.0/vapor-material/__init__.py b/2.0/vapor-material/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/2.0/vapor-material/assets/images/favicon.ico b/2.0/vapor-material/assets/images/favicon.ico new file mode 100644 index 00000000..e85006a3 Binary files /dev/null and b/2.0/vapor-material/assets/images/favicon.ico differ diff --git a/2.0/vapor-material/assets/images/favicon.png b/2.0/vapor-material/assets/images/favicon.png new file mode 100644 index 00000000..23ccc2ba Binary files /dev/null and b/2.0/vapor-material/assets/images/favicon.png differ diff --git a/2.0/vapor-material/assets/images/icons/bitbucket-670608a71a.svg b/2.0/vapor-material/assets/images/icons/bitbucket-670608a71a.svg new file mode 100644 index 00000000..7d95cb22 --- /dev/null +++ b/2.0/vapor-material/assets/images/icons/bitbucket-670608a71a.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/2.0/vapor-material/assets/images/icons/github-1da075986e.svg b/2.0/vapor-material/assets/images/icons/github-1da075986e.svg new file mode 100644 index 00000000..3cacb2e0 --- /dev/null +++ b/2.0/vapor-material/assets/images/icons/github-1da075986e.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/2.0/vapor-material/assets/images/icons/gitlab-5ad3f9f9e5.svg b/2.0/vapor-material/assets/images/icons/gitlab-5ad3f9f9e5.svg new file mode 100644 index 00000000..b036a9b5 --- /dev/null +++ b/2.0/vapor-material/assets/images/icons/gitlab-5ad3f9f9e5.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/2.0/vapor-material/assets/javascripts/application-f6cd941c96.js b/2.0/vapor-material/assets/javascripts/application-f6cd941c96.js new file mode 100644 index 00000000..d7eae4d6 --- /dev/null +++ b/2.0/vapor-material/assets/javascripts/application-f6cd941c96.js @@ -0,0 +1 @@ +window.app=function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=94)}([function(t,e,n){"use strict";var r=n(30)("wks"),o=n(22),i=n(1).Symbol,a="function"==typeof i;(t.exports=function(t){return r[t]||(r[t]=a&&i[t]||(a?i:o)("Symbol."+t))}).store=r},function(t,e,n){"use strict";var r=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(t,e,n){"use strict";var r=n(11);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e,n){"use strict";var r=n(12),o=n(29);t.exports=n(5)?function(t,e,n){return r.f(t,e,o(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){"use strict";var r=t.exports={version:"2.4.0"};"number"==typeof __e&&(__e=r)},function(t,e,n){"use strict";t.exports=!n(25)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){"use strict";var r={}.hasOwnProperty;t.exports=function(t,e){return r.call(t,e)}},function(t,e,n){"use strict";t.exports={}},function(t,e,n){"use strict";var r=n(1),o=n(3),i=n(6),a=n(22)("src"),s="toString",c=Function[s],u=(""+c).split(s);n(4).inspectSource=function(t){return c.call(t)},(t.exports=function(t,e,n,s){var c="function"==typeof n;c&&(i(n,"name")||o(n,"name",e)),t[e]!==n&&(c&&(i(n,a)||o(n,a,t[e]?""+t[e]:u.join(String(e)))),t===r?t[e]=n:s?t[e]?t[e]=n:o(t,e,n):(delete t[e],o(t,e,n)))})(Function.prototype,s,function(){return"function"==typeof this&&this[a]||c.call(this)})},function(t,e,n){"use strict";var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,e,n){"use strict";var r=n(14);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports=function(t){return"object"===(void 0===t?"undefined":r(t))?null!==t:"function"==typeof t}},function(t,e,n){"use strict";var r=n(2),o=n(43),i=n(63),a=Object.defineProperty;e.f=n(5)?Object.defineProperty:function(t,e,n){if(r(t),e=i(e,!0),r(n),o)try{return a(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={createElement:function(t,e){var n=document.createElement(t);e&&Array.prototype.forEach.call(Object.keys(e),function(t){n.setAttribute(t,e[t])});for(var r=function t(e){Array.prototype.forEach.call(e,function(e){"string"==typeof e||"number"==typeof e?n.textContent+=e:Array.isArray(e)?t(e):n.appendChild(e)})},o=arguments.length,i=Array(o>2?o-2:0),a=2;a0?o:r)(t)}},function(t,e,n){"use strict";var r=n(45),o=n(16);t.exports=function(t){return r(o(t))}},function(t,e,n){"use strict";var r=0,o=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++r+o).toString(36))}},function(t,e,n){"use strict";t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){"use strict";var r=n(1),o=n(4),i=n(3),a=n(8),s=n(10),c="prototype",u=function t(e,n,u){var l,f,h,d,p=e&t.F,v=e&t.G,m=e&t.S,y=e&t.P,g=e&t.B,w=v?r:m?r[n]||(r[n]={}):(r[n]||{})[c],b=v?o:o[n]||(o[n]={}),_=b[c]||(b[c]={});v&&(u=n);for(l in u)f=!p&&w&&void 0!==w[l],h=(f?w:u)[l],d=g&&f?s(h,r):y&&"function"==typeof h?s(Function.call,h):h,w&&a(w,l,h,e&t.U),b[l]!=h&&i(b,l,d),y&&_[l]!=h&&(_[l]=h)};r.core=o,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e,n){"use strict";t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,n){"use strict";t.exports=n(1).document&&document.documentElement},function(t,e,n){"use strict";var r=n(28),o=n(24),i=n(8),a=n(3),s=n(6),c=n(7),u=n(48),l=n(18),f=n(54),h=n(0)("iterator"),d=!([].keys&&"next"in[].keys()),p="keys",v="values",m=function(){return this};t.exports=function(t,e,n,y,g,w,b){u(n,e,y);var _,E,S,x=function(t){if(!d&&t in C)return C[t];switch(t){case p:return function(){return new n(this,t)};case v:return function(){return new n(this,t)}}return function(){return new n(this,t)}},k=e+" Iterator",T=g==v,O=!1,C=t.prototype,A=C[h]||C["@@iterator"]||g&&C[g],M=A||x(g),L=g?T?x("entries"):M:void 0,P="Array"==e?C.entries||A:A;if(P&&(S=f(P.call(new t)),S!==Object.prototype&&(l(S,k,!0),r||s(S,h)||a(S,h,m))),T&&A&&A.name!==v&&(O=!0,M=function(){return A.call(this)}),r&&!b||!d&&!O&&C[h]||a(C,h,M),c[e]=M,c[k]=m,g)if(_={values:T?M:x(v),keys:w?M:x(p),entries:L},b)for(E in _)E in C||i(C,E,_[E]);else o(o.P+o.F*(d||O),e,_);return _}},function(t,e,n){"use strict";t.exports=!1},function(t,e,n){"use strict";t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){"use strict";var r=n(1),o="__core-js_shared__",i=r[o]||(r[o]={});t.exports=function(t){return i[t]||(i[t]={})}},function(t,e,n){"use strict";var r,o,i,a=n(10),s=n(44),c=n(26),u=n(17),l=n(1),f=l.process,h=l.setImmediate,d=l.clearImmediate,p=l.MessageChannel,v=0,m={},y="onreadystatechange",g=function(){var t=+this;if(m.hasOwnProperty(t)){var e=m[t];delete m[t],e()}},w=function(t){g.call(t.data)};h&&d||(h=function(t){for(var e=[],n=1;arguments.length>n;)e.push(arguments[n++]);return m[++v]=function(){s("function"==typeof t?t:Function(t),e)},r(v),v},d=function(t){delete m[t]},"process"==n(9)(f)?r=function(t){f.nextTick(a(g,t,1))}:p?(o=new p,i=o.port2,o.port1.onmessage=w,r=a(i.postMessage,i,1)):l.addEventListener&&"function"==typeof postMessage&&!l.importScripts?(r=function(t){l.postMessage(t+"","*")},l.addEventListener("message",w,!1)):r=y in u("script")?function(t){c.appendChild(u("script"))[y]=function(){c.removeChild(this),g.call(t)}}:function(t){setTimeout(a(g,t,1),0)}),t.exports={set:h,clear:d}},function(t,e,n){"use strict";var r=n(20),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var o=function(){function t(t,e){for(var n=0;n-1?e:t}function d(t,e){e=e||{};var n=e.body;if(t instanceof d){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new o(t.headers)),this.method=t.method,this.mode=t.mode,n||null==t._bodyInit||(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new o(e.headers)),this.method=h(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n)}function p(t){var e=new FormData;return t.trim().split("&").forEach(function(t){if(t){var n=t.split("="),r=n.shift().replace(/\+/g," "),o=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(r),decodeURIComponent(o))}}),e}function v(t){var e=new o;return t.split(/\r?\n/).forEach(function(t){var n=t.split(":"),r=n.shift().trim();if(r){var o=n.join(":").trim();e.append(r,o)}}),e}function m(t,e){e||(e={}),this.type="default",this.status="status"in e?e.status:200,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new o(e.headers),this.url=e.url||"",this._initBody(t)}if(!t.fetch){var y={searchParams:"URLSearchParams"in t,iterable:"Symbol"in t&&"iterator"in Symbol,blob:"FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in t,arrayBuffer:"ArrayBuffer"in t};if(y.arrayBuffer)var g=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],w=function(t){return t&&DataView.prototype.isPrototypeOf(t)},b=ArrayBuffer.isView||function(t){return t&&g.indexOf(Object.prototype.toString.call(t))>-1};o.prototype.append=function(t,r){t=e(t),r=n(r);var o=this.map[t];this.map[t]=o?o+","+r:r},o.prototype.delete=function(t){delete this.map[e(t)]},o.prototype.get=function(t){return t=e(t),this.has(t)?this.map[t]:null},o.prototype.has=function(t){return this.map.hasOwnProperty(e(t))},o.prototype.set=function(t,r){this.map[e(t)]=n(r)},o.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)},o.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),r(t)},o.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),r(t)},o.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),r(t)},y.iterable&&(o.prototype[Symbol.iterator]=o.prototype.entries);var _=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];d.prototype.clone=function(){return new d(this,{body:this._bodyInit})},f.call(d.prototype),f.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new o(this.headers),url:this.url})},m.error=function(){var t=new m(null,{status:0,statusText:""});return t.type="error",t};var E=[301,302,303,307,308];m.redirect=function(t,e){if(E.indexOf(e)===-1)throw new RangeError("Invalid status code");return new m(null,{status:e,headers:{location:t}})},t.Headers=o,t.Request=d,t.Response=m,t.fetch=function(t,e){return new Promise(function(n,r){var o=new d(t,e),i=new XMLHttpRequest;i.onload=function(){var t={status:i.status,statusText:i.statusText,headers:v(i.getAllResponseHeaders()||"")};t.url="responseURL"in i?i.responseURL:t.headers.get("X-Request-URL"),n(new m("response"in i?i.response:i.responseText,t))},i.onerror=function(){r(new TypeError("Network request failed"))},i.ontimeout=function(){r(new TypeError("Network request failed"))},i.open(o.method,o.url,!0),"include"===o.credentials&&(i.withCredentials=!0),"responseType"in i&&y.blob&&(i.responseType="blob"),o.headers.forEach(function(t,e){i.setRequestHeader(e,t)}),i.send(void 0===o._bodyInit?null:o._bodyInit)})},t.fetch.polyfill=!0}}("undefined"!=typeof self?self:void 0)},function(t,e,n){"use strict";(function(t){function r(e){new a.a.Event.Listener(document,"DOMContentLoaded",function(){if(!(document.body instanceof HTMLElement))throw new ReferenceError;i.a.attach(document.body),Modernizr.addTest("ios",function(){return!!navigator.userAgent.match(/(iPad|iPhone|iPod)/g)});var e=document.querySelectorAll("table:not([class])");if(Array.prototype.forEach.call(e,function(e){var n=t.createElement("div",{class:"md-typeset__scrollwrap"},t.createElement("div",{class:"md-typeset__table"}));e.nextSibling?e.parentNode.insertBefore(n,e.nextSibling):e.parentNode.appendChild(n),n.children[0].appendChild(e)}),Modernizr.ios){var n=document.querySelectorAll("[data-md-scrollfix]");Array.prototype.forEach.call(n,function(t){t.addEventListener("touchstart",function(){var e=t.scrollTop;0===e?t.scrollTop=1:e+t.offsetHeight===t.scrollHeight&&(t.scrollTop=e-1)})})}}).listen(),new a.a.Event.MatchMedia("(min-width: 1220px)",new a.a.Event.Listener(window,["scroll","resize","orientationchange"],new a.a.Header.Shadow("[data-md-component=container]"))),document.querySelector("[data-md-component=tabs]")&&new a.a.Event.Listener(window,["scroll","resize","orientationchange"],new a.a.Tabs.Toggle("[data-md-component=tabs]")).listen(),new a.a.Event.MatchMedia("(min-width: 1220px)",new a.a.Event.Listener(window,["scroll","resize","orientationchange"],new a.a.Sidebar.Position("[data-md-component=navigation]"))),new a.a.Event.MatchMedia("(min-width: 960px) and (max-width: 1219px)",new a.a.Event.Listener(window,["scroll","resize","orientationchange"],new a.a.Sidebar.Position("[data-md-component=toc]"))),new a.a.Event.MatchMedia("(min-width: 1220px)",new a.a.Event.Listener(window,["scroll","resize","orientationchange"],new a.a.Sidebar.Position("[data-md-component=toc]"))),new a.a.Event.MatchMedia("(min-width: 960px)",new a.a.Event.Listener(window,"scroll",new a.a.Nav.Blur("[data-md-component=toc] [href]")));var n=document.querySelectorAll("[data-md-component=collapsible]");Array.prototype.forEach.call(n,function(t){new a.a.Event.MatchMedia("(min-width: 1220px)",new a.a.Event.Listener(t.previousElementSibling,"click",new a.a.Nav.Collapse(t)))}),new a.a.Event.MatchMedia("(max-width: 1219px)",new a.a.Event.Listener("[data-md-component=navigation] [data-md-toggle]","change",new a.a.Nav.Scrolling("[data-md-component=navigation] nav"))),new a.a.Event.MatchMedia("(max-width: 959px)",new a.a.Event.Listener("[data-md-toggle=search]","change",new a.a.Search.Lock("[data-md-toggle=search]"))),new a.a.Event.Listener("[data-md-component=query]",["focus","keyup"],new a.a.Search.Result("[data-md-component=result]",function(){return fetch(e.url.base+"/mkdocs/search_index.json",{credentials:"same-origin"}).then(function(t){return t.json()}).then(function(t){return t.docs.map(function(t){return t.location=e.url.base+t.location,t})})})).listen(),new a.a.Event.MatchMedia("(max-width: 1219px)",new a.a.Event.Listener("[data-md-component=overlay]","touchstart",function(t){return t.preventDefault()})),new a.a.Event.MatchMedia("(max-width: 959px)",new a.a.Event.Listener("[data-md-component=navigation] [href^='#']","click",function(){var t=document.querySelector("[data-md-toggle=drawer]");if(!(t instanceof HTMLInputElement))throw new ReferenceError;t.checked&&(t.checked=!1,t.dispatchEvent(new CustomEvent("change")))})),new a.a.Event.Listener("[data-md-toggle=search]","change",function(t){setTimeout(function(t){if(!(t instanceof HTMLInputElement))throw new ReferenceError;if(t.checked){var e=document.querySelector("[data-md-component=query]");if(!(e instanceof HTMLInputElement))throw new ReferenceError;e.focus()}},400,t.target)}).listen(),new a.a.Event.MatchMedia("(min-width: 960px)",new a.a.Event.Listener("[data-md-component=query]","focus",function(){var t=document.querySelector("[data-md-toggle=search]");if(!(t instanceof HTMLInputElement))throw new ReferenceError;t.checked||(t.checked=!0,t.dispatchEvent(new CustomEvent("change")))})),new a.a.Event.MatchMedia("(min-width: 960px)",new a.a.Event.Listener(document.body,"click",function(){var t=document.querySelector("[data-md-toggle=search]");if(!(t instanceof HTMLInputElement))throw new ReferenceError;t.checked&&(t.checked=!1,t.dispatchEvent(new CustomEvent("change")))})),new a.a.Event.Listener(window,"keyup",function(t){if(27===(t.keyCode||t.which)){var e=document.querySelector("[data-md-toggle=search]");if(!(e instanceof HTMLInputElement))throw new ReferenceError;if(e.checked){e.checked=!1,e.dispatchEvent(new CustomEvent("change"));var n=document.querySelector("[data-md-component=query]");if(!(n instanceof HTMLInputElement))throw new ReferenceError;n.focus()}}}).listen(),new a.a.Event.MatchMedia("(min-width: 960px)",new a.a.Event.Listener("[data-md-toggle=search]","click",function(t){return t.stopPropagation()})),new a.a.Event.MatchMedia("(min-width: 960px)",new a.a.Event.Listener("[data-md-component=search]","click",function(t){return t.stopPropagation()})),function(){var t=document.querySelector("[data-md-source]");if(!t)return Promise.resolve([]);if(!(t instanceof HTMLAnchorElement))throw new ReferenceError;switch(t.dataset.mdSource){case"github":return new a.a.Source.Adapter.GitHub(t).fetch();default:return Promise.resolve([])}}().then(function(t){var e=document.querySelectorAll("[data-md-source]");Array.prototype.forEach.call(e,function(e){new a.a.Source.Repository(e).initialize(t)})})}Object.defineProperty(e,"__esModule",{value:!0});var o=n(70),i=n.n(o),a=n(73);n.d(e,"initialize",function(){return r})}).call(e,n(13))},function(t,e,n){"use strict";var r=n(0)("unscopables"),o=Array.prototype;void 0==o[r]&&n(3)(o,r,{}),t.exports=function(t){o[r][t]=!0}},function(t,e,n){"use strict";t.exports=function(t,e,n,r){if(!(t instanceof e)||void 0!==r&&r in t)throw TypeError(n+": incorrect invocation!");return t}},function(t,e,n){"use strict";var r=n(21),o=n(32),i=n(61);t.exports=function(t){return function(e,n,a){var s,c=r(e),u=o(c.length),l=i(a,u);if(t&&n!=n){for(;u>l;)if(s=c[l++],s!=s)return!0}else for(;u>l;l++)if((t||l in c)&&c[l]===n)return t||l||0;return!t&&-1}}},function(t,e,n){"use strict";var r=n(10),o=n(47),i=n(46),a=n(2),s=n(32),c=n(64),u={},l={},f=t.exports=function(t,e,n,f,h){var d,p,v,m,y=h?function(){return t}:c(t),g=r(n,f,e?2:1),w=0;if("function"!=typeof y)throw TypeError(t+" is not iterable!");if(i(y)){for(d=s(t.length);d>w;w++)if(m=e?g(a(p=t[w])[0],p[1]):g(t[w]),m===u||m===l)return m}else for(v=y.call(t);!(p=v.next()).done;)if(m=o(v,g,p.value,e),m===u||m===l)return m};f.BREAK=u,f.RETURN=l},function(t,e,n){"use strict";t.exports=!n(5)&&!n(25)(function(){return 7!=Object.defineProperty(n(17)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){"use strict";t.exports=function(t,e,n){var r=void 0===n;switch(e.length){case 0:return r?t():t.call(n);case 1:return r?t(e[0]):t.call(n,e[0]);case 2:return r?t(e[0],e[1]):t.call(n,e[0],e[1]);case 3:return r?t(e[0],e[1],e[2]):t.call(n,e[0],e[1],e[2]);case 4:return r?t(e[0],e[1],e[2],e[3]):t.call(n,e[0],e[1],e[2],e[3])}return t.apply(n,e)}},function(t,e,n){"use strict";var r=n(9);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){"use strict";var r=n(7),o=n(0)("iterator"),i=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||i[o]===t)}},function(t,e,n){"use strict";var r=n(2);t.exports=function(t,e,n,o){try{return o?e(r(n)[0],n[1]):e(n)}catch(e){var i=t.return;throw void 0!==i&&r(i.call(t)),e}}},function(t,e,n){"use strict";var r=n(52),o=n(29),i=n(18),a={};n(3)(a,n(0)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(a,{next:o(1,n)}),i(t,e+" Iterator")}},function(t,e,n){"use strict";var r=n(0)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},t(i)}catch(t){}return n}},function(t,e,n){"use strict";t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){"use strict";var r=n(1),o=n(31).set,i=r.MutationObserver||r.WebKitMutationObserver,a=r.process,s=r.Promise,c="process"==n(9)(a);t.exports=function(){var t,e,n,u=function(){var r,o;for(c&&(r=a.domain)&&r.exit();t;){o=t.fn,t=t.next;try{o()}catch(r){throw t?n():e=void 0,r}}e=void 0,r&&r.enter()};if(c)n=function(){a.nextTick(u)};else if(i){var l=!0,f=document.createTextNode("");new i(u).observe(f,{characterData:!0}),n=function(){f.data=l=!l}}else if(s&&s.resolve){var h=s.resolve();n=function(){h.then(u)}}else n=function(){o.call(r,u)};return function(r){var o={fn:r,next:void 0};e&&(e.next=o),t||(t=o,n()),e=o}}},function(t,e,n){"use strict";var r=n(2),o=n(53),i=n(23),a=n(19)("IE_PROTO"),s=function(){},c="prototype",u=function(){var t,e=n(17)("iframe"),r=i.length,o="<",a=">";for(e.style.display="none",n(26).appendChild(e),e.src="javascript:",t=e.contentWindow.document,t.open(),t.write(o+"script"+a+"document.F=Object"+o+"/script"+a),t.close(),u=t.F;r--;)delete u[c][i[r]];return u()};t.exports=Object.create||function(t,e){var n;return null!==t?(s[c]=r(t),n=new s,s[c]=null,n[a]=t):n=u(),void 0===e?n:o(n,e)}},function(t,e,n){"use strict";var r=n(12),o=n(2),i=n(56);t.exports=n(5)?Object.defineProperties:function(t,e){o(t);for(var n,a=i(e),s=a.length,c=0;s>c;)r.f(t,n=a[c++],e[n]);return t}},function(t,e,n){"use strict";var r=n(6),o=n(62),i=n(19)("IE_PROTO"),a=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=o(t),r(t,i)?t[i]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?a:null}},function(t,e,n){"use strict";var r=n(6),o=n(21),i=n(41)(!1),a=n(19)("IE_PROTO");t.exports=function(t,e){var n,s=o(t),c=0,u=[];for(n in s)n!=a&&r(s,n)&&u.push(n);for(;e.length>c;)r(s,n=e[c++])&&(~i(u,n)||u.push(n));return u}},function(t,e,n){"use strict";var r=n(55),o=n(23);t.exports=Object.keys||function(t){return r(t,o)}},function(t,e,n){"use strict";var r=n(8);t.exports=function(t,e,n){for(var o in e)r(t,o,e[o],n);return t}},function(t,e,n){"use strict";var r=n(1),o=n(12),i=n(5),a=n(0)("species");t.exports=function(t){var e=r[t];i&&e&&!e[a]&&o.f(e,a,{configurable:!0,get:function(){return this}})}},function(t,e,n){"use strict";var r=n(2),o=n(14),i=n(0)("species");t.exports=function(t,e){var n,a=r(t).constructor;return void 0===a||void 0==(n=r(a)[i])?e:o(n)}},function(t,e,n){"use strict";var r=n(20),o=n(16);t.exports=function(t){return function(e,n){var i,a,s=String(o(e)),c=r(n),u=s.length;return c<0||c>=u?t?"":void 0:(i=s.charCodeAt(c),i<55296||i>56319||c+1===u||(a=s.charCodeAt(c+1))<56320||a>57343?t?s.charAt(c):i:t?s.slice(c,c+2):(i-55296<<10)+(a-56320)+65536)}}},function(t,e,n){"use strict";var r=n(20),o=Math.max,i=Math.min;t.exports=function(t,e){return t=r(t),t<0?o(t+e,0):i(t,e)}},function(t,e,n){"use strict";var r=n(16);t.exports=function(t){return Object(r(t))}},function(t,e,n){"use strict";var r=n(11);t.exports=function(t,e){if(!r(t))return t;var n,o;if(e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;if("function"==typeof(n=t.valueOf)&&!r(o=n.call(t)))return o;if(!e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){"use strict";var r=n(15),o=n(0)("iterator"),i=n(7);t.exports=n(4).getIteratorMethod=function(t){if(void 0!=t)return t[o]||t["@@iterator"]||i[r(t)]}},function(t,e,n){"use strict";var r=n(39),o=n(50),i=n(7),a=n(21);t.exports=n(27)(Array,"Array",function(t,e){this._t=a(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,o(1)):"keys"==e?o(0,n):"values"==e?o(0,t[n]):o(0,[n,t[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(t,e,n){"use strict";var r=n(15),o={};o[n(0)("toStringTag")]="z",o+""!="[object z]"&&n(8)(Object.prototype,"toString",function(){return"[object "+r(this)+"]"},!0)},function(t,e,n){"use strict";var r,o,i,a=n(28),s=n(1),c=n(10),u=n(15),l=n(24),f=n(11),h=n(14),d=n(40),p=n(42),v=n(59),m=n(31).set,y=n(51)(),g="Promise",w=s.TypeError,b=s.process,_=s[g],b=s.process,E="process"==u(b),S=function(){},x=!!function(){try{var t=_.resolve(1),e=(t.constructor={})[n(0)("species")]=function(t){t(S,S)};return(E||"function"==typeof PromiseRejectionEvent)&&t.then(S)instanceof e}catch(t){}}(),k=function(t,e){return t===e||t===_&&e===i},T=function(t){var e;return!(!f(t)||"function"!=typeof(e=t.then))&&e},O=function(t){return k(_,t)?new C(t):new o(t)},C=o=function(t){var e,n;this.promise=new t(function(t,r){if(void 0!==e||void 0!==n)throw w("Bad Promise constructor");e=t,n=r}),this.resolve=h(e),this.reject=h(n)},A=function(t){try{t()}catch(t){return{error:t}}},M=function(t,e){if(!t._n){t._n=!0;var n=t._c;y(function(){for(var r=t._v,o=1==t._s,i=0,a=function(e){var n,i,a=o?e.ok:e.fail,s=e.resolve,c=e.reject,u=e.domain;try{a?(o||(2==t._h&&j(t),t._h=1),a===!0?n=r:(u&&u.enter(),n=a(r),u&&u.exit()),n===e.promise?c(w("Promise-chain cycle")):(i=T(n))?i.call(n,s,c):s(n)):c(r)}catch(t){c(t)}};n.length>i;)a(n[i++]);t._c=[],t._n=!1,e&&!t._h&&L(t)})}},L=function(t){m.call(s,function(){var e,n,r,o=t._v;if(P(t)&&(e=A(function(){E?b.emit("unhandledRejection",o,t):(n=s.onunhandledrejection)?n({promise:t,reason:o}):(r=s.console)&&r.error&&r.error("Unhandled promise rejection",o)}),t._h=E||P(t)?2:1),t._a=void 0,e)throw e.error})},P=function t(e){if(1==e._h)return!1;for(var n,r=e._a||e._c,o=0;r.length>o;)if(n=r[o++],n.fail||!t(n.promise))return!1;return!0},j=function(t){m.call(s,function(){var e;E?b.emit("rejectionHandled",t):(e=s.onrejectionhandled)&&e({promise:t,reason:t._v})})},N=function(t){var e=this;e._d||(e._d=!0,e=e._w||e,e._v=t,e._s=2,e._a||(e._a=e._c.slice()),M(e,!0))},R=function t(e){var n,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===e)throw w("Promise can't be resolved itself");(n=T(e))?y(function(){var o={_w:r,_d:!1};try{n.call(e,c(t,o,1),c(N,o,1))}catch(t){N.call(o,t)}}):(r._v=e,r._s=1,M(r,!1))}catch(t){N.call({_w:r,_d:!1},t)}}};x||(_=function(t){d(this,_,g,"_h"),h(t),r.call(this);try{t(c(R,this,1),c(N,this,1))}catch(t){N.call(this,t)}},r=function(t){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},r.prototype=n(57)(_.prototype,{then:function(t,e){var n=O(v(this,_));return n.ok="function"!=typeof t||t,n.fail="function"==typeof e&&e,n.domain=E?b.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&M(this,!1),n.promise},catch:function(t){return this.then(void 0,t)}}),C=function(){var t=new r;this.promise=t,this.resolve=c(R,t,1),this.reject=c(N,t,1)}),l(l.G+l.W+l.F*!x,{Promise:_}),n(18)(_,g),n(58)(g),i=n(4)[g],l(l.S+l.F*!x,g,{reject:function(t){var e=O(this);return(0,e.reject)(t),e.promise}}),l(l.S+l.F*(a||!x),g,{resolve:function(t){if(t instanceof _&&k(t.constructor,this))return t;var e=O(this);return(0,e.resolve)(t),e.promise}}),l(l.S+l.F*!(x&&n(49)(function(t){_.all(t).catch(S)})),g,{all:function(t){var e=this,n=O(e),r=n.resolve,o=n.reject,i=A(function(){var n=[],i=0,a=1;p(t,!1,function(t){var s=i++,c=!1;n.push(void 0),a++,e.resolve(t).then(function(t){c||(c=!0,n[s]=t,--a||r(n))},o)}),--a||r(n)});return i&&o(i.error),n.promise},race:function(t){var e=this,n=O(e),r=n.reject,o=A(function(){p(t,!1,function(t){e.resolve(t).then(n.resolve,r)})});return o&&r(o.error),n.promise}})},function(t,e,n){"use strict";var r=n(60)(!0);n(27)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){"use strict";for(var r=n(65),o=n(8),i=n(1),a=n(3),s=n(7),c=n(0),u=c("iterator"),l=c("toStringTag"),f=s.Array,h=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],d=0;d<5;d++){var p,v=h[d],m=i[v],y=m&&m.prototype;if(y){y[u]||a(y,u,f),y[l]||a(y,l,v),s[v]=f;for(p in r)y[p]||o(y,p,r[p],!0)}}},function(t,e,n){"use strict";var r,o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(){function i(t,e){function n(t,e){return function(){return t.apply(e,arguments)}}var r;if(e=e||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=e.touchBoundary||10,this.layer=t,this.tapDelay=e.tapDelay||200,this.tapTimeout=e.tapTimeout||700,!i.notNeeded(t)){for(var o=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],a=this,c=0,u=o.length;c=0,s=navigator.userAgent.indexOf("Android")>0&&!a,c=/iP(ad|hone|od)/.test(navigator.userAgent)&&!a,u=c&&/OS 4_\d(_\d)?/.test(navigator.userAgent),l=c&&/OS [6-7]_\d/.test(navigator.userAgent),f=navigator.userAgent.indexOf("BB10")>0;i.prototype.needsClick=function(t){switch(t.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(t.disabled)return!0;break;case"input":if(c&&"file"===t.type||t.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(t.className)},i.prototype.needsFocus=function(t){switch(t.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!s;case"input":switch(t.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!t.disabled&&!t.readOnly;default:return/\bneedsfocus\b/.test(t.className)}},i.prototype.sendClick=function(t,e){var n,r;document.activeElement&&document.activeElement!==t&&document.activeElement.blur(),r=e.changedTouches[0],n=document.createEvent("MouseEvents"),n.initMouseEvent(this.determineEventType(t),!0,!0,window,1,r.screenX,r.screenY,r.clientX,r.clientY,!1,!1,!1,!1,0,null),n.forwardedTouchEvent=!0,t.dispatchEvent(n)},i.prototype.determineEventType=function(t){return s&&"select"===t.tagName.toLowerCase()?"mousedown":"click"},i.prototype.focus=function(t){var e;c&&t.setSelectionRange&&0!==t.type.indexOf("date")&&"time"!==t.type&&"month"!==t.type?(e=t.value.length,t.setSelectionRange(e,e)):t.focus()},i.prototype.updateScrollParent=function(t){var e,n;if(e=t.fastClickScrollParent,!e||!e.contains(t)){n=t;do{if(n.scrollHeight>n.offsetHeight){e=n,t.fastClickScrollParent=n;break}n=n.parentElement}while(n)}e&&(e.fastClickLastScrollTop=e.scrollTop)},i.prototype.getTargetElementFromEventTarget=function(t){return t.nodeType===Node.TEXT_NODE?t.parentNode:t},i.prototype.onTouchStart=function(t){var e,n,r;if(t.targetTouches.length>1)return!0;if(e=this.getTargetElementFromEventTarget(t.target),n=t.targetTouches[0],c){if(r=window.getSelection(),r.rangeCount&&!r.isCollapsed)return!0;if(!u){if(n.identifier&&n.identifier===this.lastTouchIdentifier)return t.preventDefault(),!1;this.lastTouchIdentifier=n.identifier,this.updateScrollParent(e)}}return this.trackingClick=!0,this.trackingClickStart=t.timeStamp,this.targetElement=e,this.touchStartX=n.pageX,this.touchStartY=n.pageY,t.timeStamp-this.lastClickTimen||Math.abs(e.pageY-this.touchStartY)>n},i.prototype.onTouchMove=function(t){return!this.trackingClick||((this.targetElement!==this.getTargetElementFromEventTarget(t.target)||this.touchHasMoved(t))&&(this.trackingClick=!1,this.targetElement=null),!0)},i.prototype.findControl=function(t){return void 0!==t.control?t.control:t.htmlFor?document.getElementById(t.htmlFor):t.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},i.prototype.onTouchEnd=function(t){var e,n,r,o,i,a=this.targetElement;if(!this.trackingClick)return!0;if(t.timeStamp-this.lastClickTimethis.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=t.timeStamp,n=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,l&&(i=t.changedTouches[0],a=document.elementFromPoint(i.pageX-window.pageXOffset,i.pageY-window.pageYOffset)||a,a.fastClickScrollParent=this.targetElement.fastClickScrollParent),r=a.tagName.toLowerCase(),"label"===r){if(e=this.findControl(a)){if(this.focus(a),s)return!1;a=e}}else if(this.needsFocus(a))return t.timeStamp-n>100||c&&window.top!==window&&"input"===r?(this.targetElement=null,!1):(this.focus(a),this.sendClick(a,t),c&&"select"===r||(this.targetElement=null,t.preventDefault()),!1);return!(!c||u||(o=a.fastClickScrollParent,!o||o.fastClickLastScrollTop===o.scrollTop))||(this.needsClick(a)||(t.preventDefault(),this.sendClick(a,t)),!1)},i.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},i.prototype.onMouse=function(t){return!this.targetElement||(!!t.forwardedTouchEvent||(!t.cancelable||(!(!this.needsClick(this.targetElement)||this.cancelNextClick)||(t.stopImmediatePropagation?t.stopImmediatePropagation():t.propagationStopped=!0,t.stopPropagation(),t.preventDefault(),!1))))},i.prototype.onClick=function(t){var e;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===t.target.type&&0===t.detail||(e=this.onMouse(t),e||(this.targetElement=null),e)},i.prototype.destroy=function(){var t=this.layer;s&&(t.removeEventListener("mouseover",this.onMouse,!0),t.removeEventListener("mousedown",this.onMouse,!0),t.removeEventListener("mouseup",this.onMouse,!0)),t.removeEventListener("click",this.onClick,!0),t.removeEventListener("touchstart",this.onTouchStart,!1),t.removeEventListener("touchmove",this.onTouchMove,!1),t.removeEventListener("touchend",this.onTouchEnd,!1),t.removeEventListener("touchcancel",this.onTouchCancel,!1)},i.notNeeded=function(t){var e,n,r,o;if(void 0===window.ontouchstart)return!0;if(n=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!s)return!0;if(e=document.querySelector("meta[name=viewport]")){if(e.content.indexOf("user-scalable=no")!==-1)return!0;if(n>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(f&&(r=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),r[1]>=10&&r[2]>=3&&(e=document.querySelector("meta[name=viewport]")))){if(e.content.indexOf("user-scalable=no")!==-1)return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===t.style.msTouchAction||"manipulation"===t.style.touchAction||(o=+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1],!!(o>=27&&(e=document.querySelector("meta[name=viewport]"),e&&(e.content.indexOf("user-scalable=no")!==-1||document.documentElement.scrollWidth<=window.outerWidth)))||("none"===t.style.touchAction||"manipulation"===t.style.touchAction))},i.attach=function(t,e){return new i(t,e)},"object"===o(n(34))&&n(34)?(r=function(){return i}.call(e,n,e,t),void 0!==r&&(t.exports=r)):void 0!==t&&t.exports?(t.exports=i.attach,t.exports.FastClick=i):window.FastClick=i}()},function(t,e,n){"use strict";var r,o,i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(a){var s=!1;if(r=a,o="function"==typeof r?r.call(e,n,e,t):r,void 0!==o&&(t.exports=o),s=!0,"object"===i(e)&&(t.exports=a(),s=!0),!s){var c=window.Cookies,u=window.Cookies=a();u.noConflict=function(){return window.Cookies=c,u}}}(function(){function t(){for(var t=0,e={};t1){if(i=t({path:"/"},r.defaults,i),"number"==typeof i.expires){var s=new Date;s.setMilliseconds(s.getMilliseconds()+864e5*i.expires),i.expires=s}try{a=JSON.stringify(o),/^[\{\[]/.test(a)&&(o=a)}catch(t){}return o=n.write?n.write(o,e):encodeURIComponent(String(o)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),e=encodeURIComponent(String(e)),e=e.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),e=e.replace(/[\(\)]/g,escape),document.cookie=[e,"=",o,i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}e||(a={});for(var c=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,l=0;ln.idx?n=n.next:(r+=e.val*n.val,e=e.next,n=n.next);return r},i.Vector.prototype.similarity=function(t){return this.dot(t)/(this.magnitude()*t.magnitude())},i.SortedSet=function(){this.length=0,this.elements=[]},i.SortedSet.load=function(t){var e=new this;return e.elements=t,e.length=t.length,e},i.SortedSet.prototype.add=function(){var t,e;for(t=0;t1;){if(i===t)return o;it&&(n=o),r=n-e,o=e+Math.floor(r/2),i=this.elements[o]}return i===t?o:-1},i.SortedSet.prototype.locationFor=function(t){for(var e=0,n=this.elements.length,r=n-e,o=e+Math.floor(r/2),i=this.elements[o];r>1;)it&&(n=o),r=n-e,o=e+Math.floor(r/2),i=this.elements[o];return i>t?o:io-1||r>a-1)break;s[n]!==c[r]?s[n]c[r]&&r++:(e.add(s[n]),n++,r++)}return e},i.SortedSet.prototype.clone=function(){var t=new i.SortedSet;return t.elements=this.toArray(),t.length=t.elements.length,t},i.SortedSet.prototype.union=function(t){var e,n,r;this.length>=t.length?(e=this,n=t):(e=t,n=this),r=e.clone();for(var o=0,i=n.toArray();o0&&(r=1+Math.log(this.documentStore.length/n)),this._idfCache[e]=r},i.Index.prototype.search=function(t){var e=this.pipeline.run(this.tokenizerFn(t)),n=new i.Vector,r=[],o=this._fields.reduce(function(t,e){return t+e.boost},0);return e.some(function(t){return this.tokenStore.has(t)},this)?(e.forEach(function(t,e,a){var s=1/a.length*this._fields.length*o,c=this,u=this.tokenStore.expand(t).reduce(function(e,r){var o=c.corpusTokens.indexOf(r),a=c.idf(r),u=1,l=new i.SortedSet;if(r!==t){var f=Math.max(3,r.length-t.length);u=1/Math.log(f)}o>-1&&n.insert(o,s*a*u);for(var h=c.tokenStore.get(r),d=Object.keys(h),p=d.length,v=0;v=this.height_;t!==this.active_&&(this.header_.dataset.mdState=(this.active_=t)?"shadow":"")}},{key:"reset",value:function(){this.header_.dataset.mdState="",this.height_=0,this.active_=!1}}]),t}();e.a=i},function(t,e,n){"use strict";var r=n(79),o=n(80),i=n(81);e.a={Blur:r.a,Collapse:o.a,Scrolling:i.a}},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var o=function(){function t(t,e){for(var n=0;n0&&(this.els_[n-1].dataset.mdState="blur"),this.index_=n;else for(var r=this.index_;r>=0;r--){if(!(this.anchors_[r].offsetTop-80>t)){this.index_=r;break}r>0&&(this.els_[r-1].dataset.mdState="")}this.offset_=t,this.dir_=e}}},{key:"reset",value:function(){Array.prototype.forEach.call(this.els_,function(t){t.dataset.mdState=""}),this.index_=0,this.offset_=window.pageYOffset}}]),t}();e.a=i},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var o=function(){function t(t,e){for(var n=0;nn){for(;" "!==t[n]&&--n>0;);return t.substring(0,n)+"..."}return t}},{key:"update",value:function(e){var n=this;if("focus"!==e.type||this.index_){if("keyup"===e.type){var r=e.target;if(!(r instanceof HTMLInputElement))throw new ReferenceError;for(;this.list_.firstChild;)this.list_.removeChild(this.list_.firstChild);var o=this.index_.search(r.value);o.forEach(function(e){var r=n.docs_[e.ref],o=r.location.split("#"),i=a(o,1),s=i[0];s=s.replace(/^(\/?\.{2})+/g,""),n.list_.appendChild(t.createElement("li",{class:"md-search-result__item"},t.createElement("a",{href:r.location,title:r.title,class:"md-search-result__link","data-md-rel":s===document.location.pathname?"anchor":""},t.createElement("article",{class:"md-search-result__article"},t.createElement("h1",{class:"md-search-result__title"},r.title),t.createElement("p",{class:"md-search-result__teaser"},n.truncate_(r.text,140))))))});var s=this.list_.querySelectorAll("[data-md-rel=anchor]");Array.prototype.forEach.call(s,function(t){t.addEventListener("click",function(e){var n=document.querySelector("[data-md-toggle=search]");if(!(n instanceof HTMLInputElement))throw new ReferenceError;n.checked&&(n.checked=!1,n.dispatchEvent(new CustomEvent("change"))),e.preventDefault(),setTimeout(function(){document.location.href=t.href},100)})}),this.meta_.textContent=o.length+" search result"+(1!==o.length?"s":"")}}else{var c=function(t){n.index_=i()(function(){this.field("title",{boost:10}),this.field("text"),this.ref("location")}),n.docs_=t.reduce(function(t,e){return n.index_.add(e),t[e.location]=e,t},{})};setTimeout(function(){return"function"==typeof n.data_?n.data_().then(c):c(n.data_)},250)}}}]),e}();e.a=c}).call(e,n(13))},function(t,e,n){"use strict";var r=n(86);e.a={Position:r.a}},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var o=function(){function t(t,e){for(var n=0;n=this.offset_?"lock"!==this.el_.dataset.mdState&&(this.el_.dataset.mdState="lock"):"lock"===this.el_.dataset.mdState&&(this.el_.dataset.mdState="")}},{key:"reset",value:function(){this.el_.dataset.mdState="",this.el_.style.height="",this.height_=0}}]),t}();e.a=i},function(t,e,n){"use strict";var r=n(88),o=n(91);e.a={Adapter:r.a,Repository:o.a}},function(t,e,n){"use strict";var r=n(90);e.a={GitHub:r.a}},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var o=n(71),i=n.n(o),a=function(){function t(t,e){for(var n=0;n1e4?(t/1e3).toFixed(0)+"k":t>1e3?(t/1e3).toFixed(1)+"k":""+t}},{key:"hash_",value:function(t){var e=0;if(0===t.length)return e;for(var n=0,r=t.length;n=this.offset_;t!==this.active_&&(this.el_.dataset.mdState=(this.active_=t)?"hidden":"")}},{key:"reset",value:function(){this.el_.dataset.mdState="",this.active_=!1}}]),t}();e.a=i},function(t,e,n){n(35),n(36),n(37),t.exports=n(38)}]); \ No newline at end of file diff --git a/2.0/vapor-material/assets/javascripts/modernizr-56ade86843.js b/2.0/vapor-material/assets/javascripts/modernizr-56ade86843.js new file mode 100644 index 00000000..cffa5835 --- /dev/null +++ b/2.0/vapor-material/assets/javascripts/modernizr-56ade86843.js @@ -0,0 +1 @@ +!function(e,n,t){function r(e,n){return typeof e===n}function o(){var e,n,t,o,i,s,f;for(var a in w)if(w.hasOwnProperty(a)){if(e=[],n=w[a],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t.md-nav__link,[data-md-color-primary=red] .md-nav__link:active{color:#ef5350}[data-md-color-primary=red] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=pink]{background-color:#e91e63}[data-md-color-primary=pink] .md-typeset a{color:#e91e63}[data-md-color-primary=pink] .md-header{background-color:#e91e63}[data-md-color-primary=pink] .md-nav__item--active>.md-nav__link,[data-md-color-primary=pink] .md-nav__link:active{color:#e91e63}[data-md-color-primary=pink] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=purple]{background-color:#ab47bc}[data-md-color-primary=purple] .md-typeset a{color:#ab47bc}[data-md-color-primary=purple] .md-header{background-color:#ab47bc}[data-md-color-primary=purple] .md-nav__item--active>.md-nav__link,[data-md-color-primary=purple] .md-nav__link:active{color:#ab47bc}[data-md-color-primary=purple] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=deep-purple]{background-color:#7e57c2}[data-md-color-primary=deep-purple] .md-typeset a{color:#7e57c2}[data-md-color-primary=deep-purple] .md-header{background-color:#7e57c2}[data-md-color-primary=deep-purple] .md-nav__item--active>.md-nav__link,[data-md-color-primary=deep-purple] .md-nav__link:active{color:#7e57c2}[data-md-color-primary=deep-purple] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=indigo]{background-color:#3f51b5}[data-md-color-primary=indigo] .md-typeset a{color:#3f51b5}[data-md-color-primary=indigo] .md-header{background-color:#3f51b5}[data-md-color-primary=indigo] .md-nav__item--active>.md-nav__link,[data-md-color-primary=indigo] .md-nav__link:active{color:#3f51b5}[data-md-color-primary=indigo] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=blue]{background-color:#2196f3}[data-md-color-primary=blue] .md-typeset a{color:#2196f3}[data-md-color-primary=blue] .md-header{background-color:#2196f3}[data-md-color-primary=blue] .md-nav__item--active>.md-nav__link,[data-md-color-primary=blue] .md-nav__link:active{color:#2196f3}[data-md-color-primary=blue] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=light-blue]{background-color:#03a9f4}[data-md-color-primary=light-blue] .md-typeset a{color:#03a9f4}[data-md-color-primary=light-blue] .md-header{background-color:#03a9f4}[data-md-color-primary=light-blue] .md-nav__item--active>.md-nav__link,[data-md-color-primary=light-blue] .md-nav__link:active{color:#03a9f4}[data-md-color-primary=light-blue] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=cyan]{background-color:#00bcd4}[data-md-color-primary=cyan] .md-typeset a{color:#00bcd4}[data-md-color-primary=cyan] .md-header{background-color:#00bcd4}[data-md-color-primary=cyan] .md-nav__item--active>.md-nav__link,[data-md-color-primary=cyan] .md-nav__link:active{color:#00bcd4}[data-md-color-primary=cyan] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=teal]{background-color:#009688}[data-md-color-primary=teal] .md-typeset a{color:#009688}[data-md-color-primary=teal] .md-header{background-color:#009688}[data-md-color-primary=teal] .md-nav__item--active>.md-nav__link,[data-md-color-primary=teal] .md-nav__link:active{color:#009688}[data-md-color-primary=teal] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=green]{background-color:#4caf50}[data-md-color-primary=green] .md-typeset a{color:#4caf50}[data-md-color-primary=green] .md-header{background-color:#4caf50}[data-md-color-primary=green] .md-nav__item--active>.md-nav__link,[data-md-color-primary=green] .md-nav__link:active{color:#4caf50}[data-md-color-primary=green] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=light-green]{background-color:#7cb342}[data-md-color-primary=light-green] .md-typeset a{color:#7cb342}[data-md-color-primary=light-green] .md-header{background-color:#7cb342}[data-md-color-primary=light-green] .md-nav__item--active>.md-nav__link,[data-md-color-primary=light-green] .md-nav__link:active{color:#7cb342}[data-md-color-primary=light-green] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=lime]{background-color:#c0ca33}[data-md-color-primary=lime] .md-typeset a{color:#c0ca33}[data-md-color-primary=lime] .md-header{background-color:#c0ca33}[data-md-color-primary=lime] .md-nav__item--active>.md-nav__link,[data-md-color-primary=lime] .md-nav__link:active{color:#c0ca33}[data-md-color-primary=lime] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=yellow]{background-color:#f9a825}[data-md-color-primary=yellow] .md-typeset a{color:#f9a825}[data-md-color-primary=yellow] .md-header{background-color:#f9a825}[data-md-color-primary=yellow] .md-nav__item--active>.md-nav__link,[data-md-color-primary=yellow] .md-nav__link:active{color:#f9a825}[data-md-color-primary=yellow] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=amber]{background-color:#ffb300}[data-md-color-primary=amber] .md-typeset a{color:#ffb300}[data-md-color-primary=amber] .md-header{background-color:#ffb300}[data-md-color-primary=amber] .md-nav__item--active>.md-nav__link,[data-md-color-primary=amber] .md-nav__link:active{color:#ffb300}[data-md-color-primary=amber] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=orange]{background-color:#fb8c00}[data-md-color-primary=orange] .md-typeset a{color:#fb8c00}[data-md-color-primary=orange] .md-header{background-color:#fb8c00}[data-md-color-primary=orange] .md-nav__item--active>.md-nav__link,[data-md-color-primary=orange] .md-nav__link:active{color:#fb8c00}[data-md-color-primary=orange] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=deep-orange]{background-color:#ff7043}[data-md-color-primary=deep-orange] .md-typeset a{color:#ff7043}[data-md-color-primary=deep-orange] .md-header{background-color:#ff7043}[data-md-color-primary=deep-orange] .md-nav__item--active>.md-nav__link,[data-md-color-primary=deep-orange] .md-nav__link:active{color:#ff7043}[data-md-color-primary=deep-orange] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=brown]{background-color:#795548}[data-md-color-primary=brown] .md-typeset a{color:#795548}[data-md-color-primary=brown] .md-header{background-color:#795548}[data-md-color-primary=brown] .md-nav__item--active>.md-nav__link,[data-md-color-primary=brown] .md-nav__link:active{color:#795548}[data-md-color-primary=brown] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=grey]{background-color:#757575}[data-md-color-primary=grey] .md-typeset a{color:#757575}[data-md-color-primary=grey] .md-header{background-color:#757575}[data-md-color-primary=grey] .md-nav__item--active>.md-nav__link,[data-md-color-primary=grey] .md-nav__link:active{color:#757575}[data-md-color-primary=grey] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-primary=blue-grey]{background-color:#546e7a}[data-md-color-primary=blue-grey] .md-typeset a{color:#546e7a}[data-md-color-primary=blue-grey] .md-header{background-color:#546e7a}[data-md-color-primary=blue-grey] .md-nav__item--active>.md-nav__link,[data-md-color-primary=blue-grey] .md-nav__link:active{color:#546e7a}[data-md-color-primary=blue-grey] .md-nav__item--nested>.md-nav__link{color:inherit}button[data-md-color-accent=red]{background-color:#ff1744}[data-md-color-accent=red] .md-typeset a:active,[data-md-color-accent=red] .md-typeset a:hover{color:#ff1744}[data-md-color-accent=red] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=red] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#ff1744}[data-md-color-accent=red] .md-nav__link:hover,[data-md-color-accent=red] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=red] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=red] .md-typeset [id] .headerlink:focus,[data-md-color-accent=red] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=red] .md-typeset [id]:target .headerlink{color:#ff1744}[data-md-color-accent=red] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ff1744}[data-md-color-accent=red] .md-search-result__link:hover{background-color:rgba(255,23,68,.1)}[data-md-color-accent=red] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ff1744}button[data-md-color-accent=pink]{background-color:#f50057}[data-md-color-accent=pink] .md-typeset a:active,[data-md-color-accent=pink] .md-typeset a:hover{color:#f50057}[data-md-color-accent=pink] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=pink] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#f50057}[data-md-color-accent=pink] .md-nav__link:hover,[data-md-color-accent=pink] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=pink] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=pink] .md-typeset [id] .headerlink:focus,[data-md-color-accent=pink] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=pink] .md-typeset [id]:target .headerlink{color:#f50057}[data-md-color-accent=pink] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#f50057}[data-md-color-accent=pink] .md-search-result__link:hover{background-color:rgba(245,0,87,.1)}[data-md-color-accent=pink] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#f50057}button[data-md-color-accent=purple]{background-color:#e040fb}[data-md-color-accent=purple] .md-typeset a:active,[data-md-color-accent=purple] .md-typeset a:hover{color:#e040fb}[data-md-color-accent=purple] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=purple] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#e040fb}[data-md-color-accent=purple] .md-nav__link:hover,[data-md-color-accent=purple] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=purple] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=purple] .md-typeset [id] .headerlink:focus,[data-md-color-accent=purple] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=purple] .md-typeset [id]:target .headerlink{color:#e040fb}[data-md-color-accent=purple] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#e040fb}[data-md-color-accent=purple] .md-search-result__link:hover{background-color:rgba(224,64,251,.1)}[data-md-color-accent=purple] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#e040fb}button[data-md-color-accent=deep-purple]{background-color:#7c4dff}[data-md-color-accent=deep-purple] .md-typeset a:active,[data-md-color-accent=deep-purple] .md-typeset a:hover{color:#7c4dff}[data-md-color-accent=deep-purple] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=deep-purple] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#7c4dff}[data-md-color-accent=deep-purple] .md-nav__link:hover,[data-md-color-accent=deep-purple] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=deep-purple] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=deep-purple] .md-typeset [id] .headerlink:focus,[data-md-color-accent=deep-purple] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=deep-purple] .md-typeset [id]:target .headerlink{color:#7c4dff}[data-md-color-accent=deep-purple] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#7c4dff}[data-md-color-accent=deep-purple] .md-search-result__link:hover{background-color:rgba(124,77,255,.1)}[data-md-color-accent=deep-purple] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#7c4dff}button[data-md-color-accent=indigo]{background-color:#536dfe}[data-md-color-accent=indigo] .md-typeset a:active,[data-md-color-accent=indigo] .md-typeset a:hover{color:#536dfe}[data-md-color-accent=indigo] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=indigo] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#536dfe}[data-md-color-accent=indigo] .md-nav__link:hover,[data-md-color-accent=indigo] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=indigo] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=indigo] .md-typeset [id] .headerlink:focus,[data-md-color-accent=indigo] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=indigo] .md-typeset [id]:target .headerlink{color:#536dfe}[data-md-color-accent=indigo] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#536dfe}[data-md-color-accent=indigo] .md-search-result__link:hover{background-color:rgba(83,109,254,.1)}[data-md-color-accent=indigo] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#536dfe}button[data-md-color-accent=blue]{background-color:#448aff}[data-md-color-accent=blue] .md-typeset a:active,[data-md-color-accent=blue] .md-typeset a:hover{color:#448aff}[data-md-color-accent=blue] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=blue] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#448aff}[data-md-color-accent=blue] .md-nav__link:hover,[data-md-color-accent=blue] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=blue] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=blue] .md-typeset [id] .headerlink:focus,[data-md-color-accent=blue] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=blue] .md-typeset [id]:target .headerlink{color:#448aff}[data-md-color-accent=blue] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#448aff}[data-md-color-accent=blue] .md-search-result__link:hover{background-color:rgba(68,138,255,.1)}[data-md-color-accent=blue] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#448aff}button[data-md-color-accent=light-blue]{background-color:#0091ea}[data-md-color-accent=light-blue] .md-typeset a:active,[data-md-color-accent=light-blue] .md-typeset a:hover{color:#0091ea}[data-md-color-accent=light-blue] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=light-blue] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#0091ea}[data-md-color-accent=light-blue] .md-nav__link:hover,[data-md-color-accent=light-blue] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=light-blue] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=light-blue] .md-typeset [id] .headerlink:focus,[data-md-color-accent=light-blue] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=light-blue] .md-typeset [id]:target .headerlink{color:#0091ea}[data-md-color-accent=light-blue] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#0091ea}[data-md-color-accent=light-blue] .md-search-result__link:hover{background-color:rgba(0,145,234,.1)}[data-md-color-accent=light-blue] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#0091ea}button[data-md-color-accent=cyan]{background-color:#00b8d4}[data-md-color-accent=cyan] .md-typeset a:active,[data-md-color-accent=cyan] .md-typeset a:hover{color:#00b8d4}[data-md-color-accent=cyan] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=cyan] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#00b8d4}[data-md-color-accent=cyan] .md-nav__link:hover,[data-md-color-accent=cyan] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=cyan] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=cyan] .md-typeset [id] .headerlink:focus,[data-md-color-accent=cyan] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=cyan] .md-typeset [id]:target .headerlink{color:#00b8d4}[data-md-color-accent=cyan] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#00b8d4}[data-md-color-accent=cyan] .md-search-result__link:hover{background-color:rgba(0,184,212,.1)}[data-md-color-accent=cyan] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#00b8d4}button[data-md-color-accent=teal]{background-color:#00bfa5}[data-md-color-accent=teal] .md-typeset a:active,[data-md-color-accent=teal] .md-typeset a:hover{color:#00bfa5}[data-md-color-accent=teal] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=teal] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#00bfa5}[data-md-color-accent=teal] .md-nav__link:hover,[data-md-color-accent=teal] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=teal] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=teal] .md-typeset [id] .headerlink:focus,[data-md-color-accent=teal] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=teal] .md-typeset [id]:target .headerlink{color:#00bfa5}[data-md-color-accent=teal] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#00bfa5}[data-md-color-accent=teal] .md-search-result__link:hover{background-color:rgba(0,191,165,.1)}[data-md-color-accent=teal] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#00bfa5}button[data-md-color-accent=green]{background-color:#00c853}[data-md-color-accent=green] .md-typeset a:active,[data-md-color-accent=green] .md-typeset a:hover{color:#00c853}[data-md-color-accent=green] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=green] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#00c853}[data-md-color-accent=green] .md-nav__link:hover,[data-md-color-accent=green] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=green] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=green] .md-typeset [id] .headerlink:focus,[data-md-color-accent=green] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=green] .md-typeset [id]:target .headerlink{color:#00c853}[data-md-color-accent=green] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#00c853}[data-md-color-accent=green] .md-search-result__link:hover{background-color:rgba(0,200,83,.1)}[data-md-color-accent=green] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#00c853}button[data-md-color-accent=light-green]{background-color:#64dd17}[data-md-color-accent=light-green] .md-typeset a:active,[data-md-color-accent=light-green] .md-typeset a:hover{color:#64dd17}[data-md-color-accent=light-green] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=light-green] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#64dd17}[data-md-color-accent=light-green] .md-nav__link:hover,[data-md-color-accent=light-green] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=light-green] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=light-green] .md-typeset [id] .headerlink:focus,[data-md-color-accent=light-green] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=light-green] .md-typeset [id]:target .headerlink{color:#64dd17}[data-md-color-accent=light-green] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#64dd17}[data-md-color-accent=light-green] .md-search-result__link:hover{background-color:rgba(100,221,23,.1)}[data-md-color-accent=light-green] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#64dd17}button[data-md-color-accent=lime]{background-color:#aeea00}[data-md-color-accent=lime] .md-typeset a:active,[data-md-color-accent=lime] .md-typeset a:hover{color:#aeea00}[data-md-color-accent=lime] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=lime] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#aeea00}[data-md-color-accent=lime] .md-nav__link:hover,[data-md-color-accent=lime] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=lime] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=lime] .md-typeset [id] .headerlink:focus,[data-md-color-accent=lime] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=lime] .md-typeset [id]:target .headerlink{color:#aeea00}[data-md-color-accent=lime] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#aeea00}[data-md-color-accent=lime] .md-search-result__link:hover{background-color:rgba(174,234,0,.1)}[data-md-color-accent=lime] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#aeea00}button[data-md-color-accent=yellow]{background-color:#ffd600}[data-md-color-accent=yellow] .md-typeset a:active,[data-md-color-accent=yellow] .md-typeset a:hover{color:#ffd600}[data-md-color-accent=yellow] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=yellow] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#ffd600}[data-md-color-accent=yellow] .md-nav__link:hover,[data-md-color-accent=yellow] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=yellow] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=yellow] .md-typeset [id] .headerlink:focus,[data-md-color-accent=yellow] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=yellow] .md-typeset [id]:target .headerlink{color:#ffd600}[data-md-color-accent=yellow] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ffd600}[data-md-color-accent=yellow] .md-search-result__link:hover{background-color:rgba(255,214,0,.1)}[data-md-color-accent=yellow] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ffd600}button[data-md-color-accent=amber]{background-color:#ffab00}[data-md-color-accent=amber] .md-typeset a:active,[data-md-color-accent=amber] .md-typeset a:hover{color:#ffab00}[data-md-color-accent=amber] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=amber] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#ffab00}[data-md-color-accent=amber] .md-nav__link:hover,[data-md-color-accent=amber] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=amber] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=amber] .md-typeset [id] .headerlink:focus,[data-md-color-accent=amber] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=amber] .md-typeset [id]:target .headerlink{color:#ffab00}[data-md-color-accent=amber] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ffab00}[data-md-color-accent=amber] .md-search-result__link:hover{background-color:rgba(255,171,0,.1)}[data-md-color-accent=amber] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ffab00}button[data-md-color-accent=orange]{background-color:#ff9100}[data-md-color-accent=orange] .md-typeset a:active,[data-md-color-accent=orange] .md-typeset a:hover{color:#ff9100}[data-md-color-accent=orange] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=orange] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#ff9100}[data-md-color-accent=orange] .md-nav__link:hover,[data-md-color-accent=orange] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=orange] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=orange] .md-typeset [id] .headerlink:focus,[data-md-color-accent=orange] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=orange] .md-typeset [id]:target .headerlink{color:#ff9100}[data-md-color-accent=orange] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ff9100}[data-md-color-accent=orange] .md-search-result__link:hover{background-color:rgba(255,145,0,.1)}[data-md-color-accent=orange] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ff9100}button[data-md-color-accent=deep-orange]{background-color:#ff6e40}[data-md-color-accent=deep-orange] .md-typeset a:active,[data-md-color-accent=deep-orange] .md-typeset a:hover{color:#ff6e40}[data-md-color-accent=deep-orange] .md-typeset .codehilite::-webkit-scrollbar-thumb:hover,[data-md-color-accent=deep-orange] .md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#ff6e40}[data-md-color-accent=deep-orange] .md-nav__link:hover,[data-md-color-accent=deep-orange] .md-typeset .footnote li:hover .footnote-backref:hover,[data-md-color-accent=deep-orange] .md-typeset .footnote li:target .footnote-backref,[data-md-color-accent=deep-orange] .md-typeset [id] .headerlink:focus,[data-md-color-accent=deep-orange] .md-typeset [id]:hover .headerlink:hover,[data-md-color-accent=deep-orange] .md-typeset [id]:target .headerlink{color:#ff6e40}[data-md-color-accent=deep-orange] .md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ff6e40}[data-md-color-accent=deep-orange] .md-search-result__link:hover{background-color:rgba(255,110,64,.1)}[data-md-color-accent=deep-orange] .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#ff6e40}@media only screen and (max-width:59.9375em){[data-md-color-primary=red] .md-nav__source{background-color:rgba(190,66,64,.9675)}[data-md-color-primary=pink] .md-nav__source{background-color:rgba(185,24,79,.9675)}[data-md-color-primary=purple] .md-nav__source{background-color:rgba(136,57,150,.9675)}[data-md-color-primary=deep-purple] .md-nav__source{background-color:rgba(100,69,154,.9675)}[data-md-color-primary=indigo] .md-nav__source{background-color:rgba(50,64,144,.9675)}[data-md-color-primary=blue] .md-nav__source{background-color:rgba(26,119,193,.9675)}[data-md-color-primary=light-blue] .md-nav__source{background-color:rgba(2,134,194,.9675)}[data-md-color-primary=cyan] .md-nav__source{background-color:rgba(0,150,169,.9675)}[data-md-color-primary=teal] .md-nav__source{background-color:rgba(0,119,108,.9675)}[data-md-color-primary=green] .md-nav__source{background-color:rgba(60,139,64,.9675)}[data-md-color-primary=light-green] .md-nav__source{background-color:rgba(99,142,53,.9675)}[data-md-color-primary=lime] .md-nav__source{background-color:rgba(153,161,41,.9675)}[data-md-color-primary=yellow] .md-nav__source{background-color:rgba(198,134,29,.9675)}[data-md-color-primary=amber] .md-nav__source{background-color:rgba(203,142,0,.9675)}[data-md-color-primary=orange] .md-nav__source{background-color:rgba(200,111,0,.9675)}[data-md-color-primary=deep-orange] .md-nav__source{background-color:rgba(203,89,53,.9675)}[data-md-color-primary=brown] .md-nav__source{background-color:rgba(96,68,57,.9675)}[data-md-color-primary=grey] .md-nav__source{background-color:rgba(93,93,93,.9675)}[data-md-color-primary=blue-grey] .md-nav__source{background-color:rgba(67,88,97,.9675)}}@media only screen and (max-width:76.1875em){html [data-md-color-primary=red] .md-nav--primary .md-nav__title--site{background-color:#ef5350}html [data-md-color-primary=pink] .md-nav--primary .md-nav__title--site{background-color:#e91e63}html [data-md-color-primary=purple] .md-nav--primary .md-nav__title--site{background-color:#ab47bc}html [data-md-color-primary=deep-purple] .md-nav--primary .md-nav__title--site{background-color:#7e57c2}html [data-md-color-primary=indigo] .md-nav--primary .md-nav__title--site{background-color:#3f51b5}html [data-md-color-primary=blue] .md-nav--primary .md-nav__title--site{background-color:#2196f3}html [data-md-color-primary=light-blue] .md-nav--primary .md-nav__title--site{background-color:#03a9f4}html [data-md-color-primary=cyan] .md-nav--primary .md-nav__title--site{background-color:#00bcd4}html [data-md-color-primary=teal] .md-nav--primary .md-nav__title--site{background-color:#009688}html [data-md-color-primary=green] .md-nav--primary .md-nav__title--site{background-color:#4caf50}html [data-md-color-primary=light-green] .md-nav--primary .md-nav__title--site{background-color:#7cb342}html [data-md-color-primary=lime] .md-nav--primary .md-nav__title--site{background-color:#c0ca33}html [data-md-color-primary=yellow] .md-nav--primary .md-nav__title--site{background-color:#f9a825}html [data-md-color-primary=amber] .md-nav--primary .md-nav__title--site{background-color:#ffb300}html [data-md-color-primary=orange] .md-nav--primary .md-nav__title--site{background-color:#fb8c00}html [data-md-color-primary=deep-orange] .md-nav--primary .md-nav__title--site{background-color:#ff7043}html [data-md-color-primary=brown] .md-nav--primary .md-nav__title--site{background-color:#795548}html [data-md-color-primary=grey] .md-nav--primary .md-nav__title--site{background-color:#757575}html [data-md-color-primary=blue-grey] .md-nav--primary .md-nav__title--site{background-color:#546e7a}}@media only screen and (min-width:60em){[data-md-color-primary=red] .md-nav--secondary{border-left:.4rem solid #ef5350}[data-md-color-primary=pink] .md-nav--secondary{border-left:.4rem solid #e91e63}[data-md-color-primary=purple] .md-nav--secondary{border-left:.4rem solid #ab47bc}[data-md-color-primary=deep-purple] .md-nav--secondary{border-left:.4rem solid #7e57c2}[data-md-color-primary=indigo] .md-nav--secondary{border-left:.4rem solid #3f51b5}[data-md-color-primary=blue] .md-nav--secondary{border-left:.4rem solid #2196f3}[data-md-color-primary=light-blue] .md-nav--secondary{border-left:.4rem solid #03a9f4}[data-md-color-primary=cyan] .md-nav--secondary{border-left:.4rem solid #00bcd4}[data-md-color-primary=teal] .md-nav--secondary{border-left:.4rem solid #009688}[data-md-color-primary=green] .md-nav--secondary{border-left:.4rem solid #4caf50}[data-md-color-primary=light-green] .md-nav--secondary{border-left:.4rem solid #7cb342}[data-md-color-primary=lime] .md-nav--secondary{border-left:.4rem solid #c0ca33}[data-md-color-primary=yellow] .md-nav--secondary{border-left:.4rem solid #f9a825}[data-md-color-primary=amber] .md-nav--secondary{border-left:.4rem solid #ffb300}[data-md-color-primary=orange] .md-nav--secondary{border-left:.4rem solid #fb8c00}[data-md-color-primary=deep-orange] .md-nav--secondary{border-left:.4rem solid #ff7043}[data-md-color-primary=brown] .md-nav--secondary{border-left:.4rem solid #795548}[data-md-color-primary=grey] .md-nav--secondary{border-left:.4rem solid #757575}[data-md-color-primary=blue-grey] .md-nav--secondary{border-left:.4rem solid #546e7a}}@media only screen and (min-width:76.25em){[data-md-color-primary=red] .md-tabs{background:rgba(190,66,64,.9675)}[data-md-color-primary=red] .md-tabs[data-md-state=hidden]{background:#ef5350}[data-md-color-primary=pink] .md-tabs{background:rgba(185,24,79,.9675)}[data-md-color-primary=pink] .md-tabs[data-md-state=hidden]{background:#e91e63}[data-md-color-primary=purple] .md-tabs{background:rgba(136,57,150,.9675)}[data-md-color-primary=purple] .md-tabs[data-md-state=hidden]{background:#ab47bc}[data-md-color-primary=deep-purple] .md-tabs{background:rgba(100,69,154,.9675)}[data-md-color-primary=deep-purple] .md-tabs[data-md-state=hidden]{background:#7e57c2}[data-md-color-primary=indigo] .md-tabs{background:rgba(50,64,144,.9675)}[data-md-color-primary=indigo] .md-tabs[data-md-state=hidden]{background:#3f51b5}[data-md-color-primary=blue] .md-tabs{background:rgba(26,119,193,.9675)}[data-md-color-primary=blue] .md-tabs[data-md-state=hidden]{background:#2196f3}[data-md-color-primary=light-blue] .md-tabs{background:rgba(2,134,194,.9675)}[data-md-color-primary=light-blue] .md-tabs[data-md-state=hidden]{background:#03a9f4}[data-md-color-primary=cyan] .md-tabs{background:rgba(0,150,169,.9675)}[data-md-color-primary=cyan] .md-tabs[data-md-state=hidden]{background:#00bcd4}[data-md-color-primary=teal] .md-tabs{background:rgba(0,119,108,.9675)}[data-md-color-primary=teal] .md-tabs[data-md-state=hidden]{background:#009688}[data-md-color-primary=green] .md-tabs{background:rgba(60,139,64,.9675)}[data-md-color-primary=green] .md-tabs[data-md-state=hidden]{background:#4caf50}[data-md-color-primary=light-green] .md-tabs{background:rgba(99,142,53,.9675)}[data-md-color-primary=light-green] .md-tabs[data-md-state=hidden]{background:#7cb342}[data-md-color-primary=lime] .md-tabs{background:rgba(153,161,41,.9675)}[data-md-color-primary=lime] .md-tabs[data-md-state=hidden]{background:#c0ca33}[data-md-color-primary=yellow] .md-tabs{background:rgba(198,134,29,.9675)}[data-md-color-primary=yellow] .md-tabs[data-md-state=hidden]{background:#f9a825}[data-md-color-primary=amber] .md-tabs{background:rgba(203,142,0,.9675)}[data-md-color-primary=amber] .md-tabs[data-md-state=hidden]{background:#ffb300}[data-md-color-primary=orange] .md-tabs{background:rgba(200,111,0,.9675)}[data-md-color-primary=orange] .md-tabs[data-md-state=hidden]{background:#fb8c00}[data-md-color-primary=deep-orange] .md-tabs{background:rgba(203,89,53,.9675)}[data-md-color-primary=deep-orange] .md-tabs[data-md-state=hidden]{background:#ff7043}[data-md-color-primary=brown] .md-tabs{background:rgba(96,68,57,.9675)}[data-md-color-primary=brown] .md-tabs[data-md-state=hidden]{background:#795548}[data-md-color-primary=grey] .md-tabs{background:rgba(93,93,93,.9675)}[data-md-color-primary=grey] .md-tabs[data-md-state=hidden]{background:#757575}[data-md-color-primary=blue-grey] .md-tabs{background:rgba(67,88,97,.9675)}[data-md-color-primary=blue-grey] .md-tabs[data-md-state=hidden]{background:#546e7a}} \ No newline at end of file diff --git a/2.0/vapor-material/assets/stylesheets/application-e5b48ab351.css b/2.0/vapor-material/assets/stylesheets/application-e5b48ab351.css new file mode 100644 index 00000000..f6ce61aa --- /dev/null +++ b/2.0/vapor-material/assets/stylesheets/application-e5b48ab351.css @@ -0,0 +1 @@ +html{box-sizing:border-box}*,:after,:before{box-sizing:inherit}html{-webkit-text-size-adjust:none;-ms-text-size-adjust:none;text-size-adjust:none}body{margin:0}hr{overflow:visible;box-sizing:content-box}a{-webkit-text-decoration-skip:objects}a,button,input,label{-webkit-tap-highlight-color:transparent}a{color:inherit;text-decoration:none}a:active,a:hover{outline-width:0}small,sub,sup{font-size:80%}sub,sup{position:relative;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}table{border-collapse:collapse;border-spacing:0}td,th{font-weight:400;vertical-align:top}button{padding:0;background:transparent;font-size:inherit}button,input{border:0;outline:0}.admonition:before,.md-icon,.md-nav__button,.md-nav__link:after,.md-nav__title:before,.md-typeset .critic.comment:before,.md-typeset .footnote-backref,.md-typeset .task-list-control .task-list-indicator:before{font-family:Material Icons;font-style:normal;font-variant:normal;font-weight:400;line-height:1;text-transform:none;white-space:nowrap;speak:none;word-wrap:normal;direction:ltr}.md-content__edit,.md-footer-nav__button,.md-header-nav__button,.md-nav__button,.md-nav__title:before{display:inline-block;margin:.4rem;padding:.8rem;font-size:2.4rem;cursor:pointer}.md-icon--arrow-back:before{content:"arrow_back"}.md-icon--arrow-forward:before{content:"arrow_forward"}.md-icon--menu:before{content:"menu"}.md-icon--search:before{content:"search"}.md-icon--home:before{content:"school"}body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}body,input{color:#181818;-webkit-font-feature-settings:"kern","onum","liga";font-feature-settings:"kern","onum","liga";font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-weight:400}code,kbd,pre{color:rgba(0,0,0,.87);-webkit-font-feature-settings:"kern","onum","liga";font-feature-settings:"kern","onum","liga";font-family:Courier New,Courier,monospace;font-weight:400}.md-typeset{font-size:1.6rem;line-height:1.6;-webkit-print-color-adjust:exact}.md-typeset blockquote,.md-typeset ol,.md-typeset p,.md-typeset ul{margin:1em 0}.md-typeset h1{margin:0 0 4rem;color:rgba(0,0,0,.54);font-size:3.125rem;line-height:1.3}.md-typeset h1,.md-typeset h2{font-weight:300;letter-spacing:-.01em}.md-typeset h2{margin:4rem 0 1.6rem;font-size:2.5rem;line-height:1.4}.md-typeset h3{margin:3.2rem 0 1.6rem;font-size:2rem;font-weight:400;letter-spacing:-.01em;line-height:1.5}.md-typeset h2+h3{margin-top:1.6rem}.md-typeset h4{font-size:1.6rem}.md-typeset h4,.md-typeset h5,.md-typeset h6{margin:1.6rem 0;font-weight:700;letter-spacing:-.01em}.md-typeset h5,.md-typeset h6{color:rgba(0,0,0,.54);font-size:1.28rem}.md-typeset h5{text-transform:uppercase}.md-typeset hr{margin:1.5em 0;border-bottom:.1rem dotted rgba(0,0,0,.26)}.md-typeset a{color:#7b8eb0;word-break:break-word}.md-typeset a,.md-typeset a:before{-webkit-transition:color .125s;transition:color .125s}.md-typeset a:active,.md-typeset a:hover{color:#fca9a8}.md-typeset code,.md-typeset pre{background-color:hsla(0,0%,93%,.5);color:#37474f;font-size:85%}.md-typeset code{margin:0 .29412em;padding:.07353em 0;border-radius:.2rem;box-shadow:.29412em 0 0 hsla(0,0%,93%,.5),-.29412em 0 0 hsla(0,0%,93%,.5);word-break:break-word;-webkit-box-decoration-break:clone;box-decoration-break:clone}.md-typeset h1 code,.md-typeset h2 code,.md-typeset h3 code,.md-typeset h4 code,.md-typeset h5 code,.md-typeset h6 code{margin:0;background-color:transparent;box-shadow:none}.md-typeset a>code{margin:inherit;padding:inherit;border-radius:none;background-color:inherit;color:inherit;box-shadow:none}.md-typeset pre{margin:1em 0;padding:1rem 1.2rem;border-radius:.2rem;line-height:1.4;overflow:auto;-webkit-overflow-scrolling:touch}.md-typeset pre::-webkit-scrollbar{width:.4rem;height:.4rem}.md-typeset pre::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.26)}.md-typeset pre::-webkit-scrollbar-thumb:hover{background-color:#fca9a8}.md-typeset pre>code{margin:0;background-color:transparent;font-size:inherit;box-shadow:none;-webkit-box-decoration-break:none;box-decoration-break:none}.md-typeset kbd{padding:0 .29412em;border:.1rem solid #c9c9c9;border-radius:.2rem;border-bottom-color:#bcbcbc;background-color:#fcfcfc;color:#555;font-size:85%;box-shadow:0 .1rem 0 #b0b0b0;word-break:break-word}.md-typeset mark{margin:0 .25em;padding:.0625em 0;border-radius:.2rem;background-color:rgba(255,235,59,.5);box-shadow:.25em 0 0 rgba(255,235,59,.5),-.25em 0 0 rgba(255,235,59,.5);word-break:break-word;-webkit-box-decoration-break:clone;box-decoration-break:clone}.md-typeset abbr{border-bottom:.1rem dotted rgba(0,0,0,.54);cursor:help}.md-typeset small{opacity:.75}.md-typeset sub,.md-typeset sup{margin-left:.07812em}.md-typeset blockquote{padding-left:1.2rem;border-left:.4rem solid rgba(0,0,0,.26);color:rgba(0,0,0,.54)}.md-typeset ul{list-style-type:disc}.md-typeset ol,.md-typeset ul{margin-left:.625em;padding:0}.md-typeset ol ol,.md-typeset ul ol{list-style-type:lower-alpha}.md-typeset ol ol ol,.md-typeset ul ol ol{list-style-type:lower-roman}.md-typeset ol li,.md-typeset ul li{margin-bottom:.5em;margin-left:1.25em}.md-typeset ol li blockquote,.md-typeset ol li p,.md-typeset ul li blockquote,.md-typeset ul li p{margin:.5em 0}.md-typeset ol li:last-child,.md-typeset ul li:last-child{margin-bottom:0}.md-typeset ol li ol,.md-typeset ol li ul,.md-typeset ul li ol,.md-typeset ul li ul{margin:.5em 0 .5em .625em}.md-typeset dd{margin:1em 0 1em 1.875em}.md-typeset iframe,.md-typeset img,.md-typeset svg{max-width:100%}.md-typeset table:not([class]){box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2);display:inline-block;max-width:100%;border-radius:.2rem;font-size:1.28rem;overflow:auto;-webkit-overflow-scrolling:touch}.md-typeset table:not([class])+*{margin-top:1.5em}.md-typeset table:not([class]) td:not([align]),.md-typeset table:not([class]) th:not([align]){text-align:left}.md-typeset table:not([class]) th{min-width:10rem;padding:1.2rem 1.6rem;background-color:rgba(0,0,0,.54);color:#fff;vertical-align:top}.md-typeset table:not([class]) td{padding:1.2rem 1.6rem;border-top:.1rem solid rgba(0,0,0,.07);vertical-align:top}.md-typeset table:not([class]) tr:first-child td{border-top:0}.md-typeset table:not([class]) a{word-break:normal}.md-typeset__scrollwrap{margin:1em -1.6rem;overflow-x:auto;-webkit-overflow-scrolling:touch}.md-typeset .md-typeset__table{display:inline-block;margin-bottom:.5em;padding:0 1.6rem}.md-typeset .md-typeset__table table{display:table;width:100%;margin:0;overflow:hidden}html{font-size:62.5%}body,html{height:100%}body{position:relative}hr{display:block;height:.1rem;padding:0;border:0}.md-svg{display:none}.md-grid{max-width:122rem;margin-right:auto;margin-left:auto}.md-container,.md-main{overflow:auto}.md-container{display:table;width:100%;height:100%;padding-top:5.6rem;table-layout:fixed}.md-main{display:table-row;height:100%}.md-main__inner{min-height:100%;padding-top:3rem;overflow:auto}.md-toggle{display:none}.md-overlay{position:fixed;top:0;width:0;height:0;-webkit-transition:width 0s .25s,height 0s .25s,opacity .25s;transition:width 0s .25s,height 0s .25s,opacity .25s;background-color:rgba(0,0,0,.54);opacity:0;z-index:2}.md-flex{display:table}.md-flex__cell{display:table-cell;position:relative;vertical-align:top}.md-flex__cell--shrink{width:0}.md-flex__cell--stretch{display:table;width:100%;table-layout:fixed}.md-flex__ellipsis{display:table-cell;text-overflow:ellipsis;white-space:nowrap;overflow:hidden}@page{margin:25mm}.md-content__inner{margin:2.4rem 1.6rem}.md-content__inner>:last-child{margin-bottom:0}.md-content__edit{float:right}.md-header{position:fixed;top:0;right:0;left:0;height:5.6rem;-webkit-transition:background-color .25s;transition:background-color .25s;background-color:#7b8eb0;color:#fff;z-index:1}.md-header,.no-js .md-header{box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2)}.md-header-nav{padding:.4rem}.md-header-nav__button{position:relative;-webkit-transition:opacity .25s;transition:opacity .25s;z-index:1}.md-header-nav__button:hover{opacity:.7}.md-header-nav__button.md-logo img{display:block}.no-js .md-header-nav__button.md-icon--search{display:none}.md-header-nav__title{padding:0 2rem;font-size:1.8rem;line-height:4.8rem}.md-header-nav__parent{color:hsla(0,0%,100%,.7)}.md-header-nav__parent:after{display:inline;color:hsla(0,0%,100%,.3);content:"/"}.md-header-nav__source{display:none}.md-footer-nav{background-color:#3b4752;color:#fff}.md-footer-nav__inner{padding:.4rem;overflow:auto}.md-footer-nav__link{padding-top:2.8rem;padding-bottom:.8rem;-webkit-transition:opacity .25s;transition:opacity .25s}.md-footer-nav__link:hover{opacity:.7}.md-footer-nav__link--prev{width:25%;float:left}.md-footer-nav__link--next{width:75%;float:right;text-align:right}.md-footer-nav__button{-webkit-transition:background .25s;transition:background .25s}.md-footer-nav__title{position:relative;padding:0 2rem;font-size:1.8rem;line-height:4.8rem}.md-footer-nav__direction{position:absolute;right:0;left:0;margin-top:-2rem;padding:0 2rem;color:hsla(0,0%,100%,.7);font-size:1.5rem}.md-footer-meta{background:#292f34}.md-footer-meta__inner{padding:.4rem;overflow:auto}html .md-footer-meta.md-typeset a{color:hsla(0,0%,100%,.7)}.md-footer-copyright{margin:0 1.2rem;padding:.8rem 0;color:hsla(0,0%,100%,.3);font-size:1.28rem}.md-footer-copyright__highlight{color:hsla(0,0%,100%,.7)}.md-footer-social{margin:0 .8rem;padding:.4rem 0 1.2rem}.md-footer-social__link{display:inline-block;width:3.2rem;height:3.2rem;border:.1rem solid hsla(0,0%,100%,.12);border-radius:100%;color:hsla(0,0%,100%,.7);font-size:1.6rem;text-align:center}.md-footer-social__link:before{line-height:1.9}.md-nav{font-size:1.4rem;line-height:1.3}.md-nav--secondary{-webkit-transition:border-left .25s;transition:border-left .25s;border-left:.4rem solid #7b8eb0}.md-nav__title{display:block;padding:1.2rem 1.2rem 0;font-weight:700;text-overflow:ellipsis;overflow:hidden}.md-nav__title:before{display:none;content:"arrow_back"}.md-nav__title .md-nav__button{display:none}.md-nav__list{margin:0;padding:0;list-style:none}.md-nav__item{padding:0 1.2rem}.md-nav__item:last-child{padding-bottom:1.2rem}.md-nav__item .md-nav__item{padding-right:0}.md-nav__item .md-nav__item:last-child{padding-bottom:0}.md-nav__button img{width:100%;height:auto}.md-nav__link{display:block;margin-top:.625em;-webkit-transition:color .125s;transition:color .125s;text-overflow:ellipsis;cursor:pointer;overflow:hidden}.md-nav__item--nested>.md-nav__link:after{content:"keyboard_arrow_down"}html .md-nav__link[for=toc],html .md-nav__link[for=toc]+.md-nav__link:after,html .md-nav__link[for=toc]~.md-nav{display:none}.md-nav__link[data-md-state=blur]{color:rgba(0,0,0,.54);font-style:italic}.md-nav__item--active>.md-nav__link,.md-nav__link:active{color:#7b8eb0}.md-nav__item--nested>.md-nav__link{color:inherit}.md-nav__link:focus,.md-nav__link:hover{color:#fca9a8}.md-nav__source,.no-js .md-search{display:none}.md-search__overlay{display:none;pointer-events:none}.md-search__inner{width:100%}.md-search__form{position:relative}.md-search__input{position:relative;padding:0 1.6rem 0 7.2rem;text-overflow:ellipsis;z-index:1}.md-search__input+.md-search__icon,.md-search__input::-webkit-input-placeholder{color:rgba(0,0,0,.54)}.md-search__input+.md-search__icon,.md-search__input::-moz-placeholder{color:rgba(0,0,0,.54)}.md-search__input+.md-search__icon,.md-search__input:-ms-input-placeholder{color:rgba(0,0,0,.54)}.md-search__input+.md-search__icon,.md-search__input::placeholder{color:rgba(0,0,0,.54)}.md-search__input::-ms-clear{display:none}.md-search__icon{position:absolute;top:.8rem;left:1.2rem;-webkit-transition:color .25s;transition:color .25s;font-size:2.4rem;cursor:pointer;z-index:1}.md-search__icon:before{content:"search"}.md-search__output{position:absolute;width:100%;border-radius:0 0 .2rem .2rem;overflow:hidden}.md-search__scrollwrap{height:100%;background:-webkit-linear-gradient(top,#fff 10%,hsla(0,0%,100%,0)),-webkit-linear-gradient(top,rgba(0,0,0,.26),rgba(0,0,0,.07) 35%,transparent 60%);background:linear-gradient(180deg,#fff 10%,hsla(0,0%,100%,0)),linear-gradient(180deg,rgba(0,0,0,.26),rgba(0,0,0,.07) 35%,transparent 60%);background-attachment:local,scroll;background-color:#fff;background-repeat:no-repeat;background-size:100% 2rem,100% 1rem;box-shadow:inset 0 .1rem 0 rgba(0,0,0,.07);overflow-y:auto;-webkit-overflow-scrolling:touch}.md-search-result__meta{padding:0 1.6rem;background-color:rgba(0,0,0,.07);color:rgba(0,0,0,.54);font-size:1.28rem;line-height:4rem}.md-search-result__list{margin:0;padding:0;border-top:.1rem solid rgba(0,0,0,.07);list-style:none}.md-search-result__item{box-shadow:0 -.1rem 0 rgba(0,0,0,.07)}.md-search-result__link{display:block;padding:0 1.6rem;-webkit-transition:background .25s;transition:background .25s;overflow:auto}.md-search-result__link:hover{background-color:hsla(1,93%,82%,.1)}.md-search-result__article{margin:1em 0}.md-search-result__title{margin-top:.5em;margin-bottom:0;color:rgba(0,0,0,.87);font-size:1.6rem;font-weight:400;line-height:1.4}.md-search-result__teaser{margin:.5em 0;color:rgba(0,0,0,.54);font-size:1.28rem;line-height:1.4;word-break:break-word}.md-sidebar{position:relative;width:24.2rem;padding:2.4rem 0;float:left;overflow:visible}.md-sidebar[data-md-state=lock]{position:fixed;top:5.6rem;-webkit-backface-visibility:hidden;backface-visibility:hidden}.md-sidebar--secondary{display:none}.md-sidebar__scrollwrap{max-height:100%;margin:0 .4rem;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden}.md-sidebar__scrollwrap::-webkit-scrollbar{width:.4rem;height:.4rem}.md-sidebar__scrollwrap::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.26)}.md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#fca9a8}@-webkit-keyframes a{0%{height:0}to{height:1.3rem}}@keyframes a{0%{height:0}to{height:1.3rem}}@-webkit-keyframes b{0%{-webkit-transform:translateY(100%);transform:translateY(100%);opacity:0}50%{opacity:0}to{-webkit-transform:translateY(0);transform:translateY(0);opacity:1}}@keyframes b{0%{-webkit-transform:translateY(100%);transform:translateY(100%);opacity:0}50%{opacity:0}to{-webkit-transform:translateY(0);transform:translateY(0);opacity:1}}.md-source{display:block;-webkit-transition:opacity .25s;transition:opacity .25s;font-size:1.3rem;line-height:1.2;white-space:nowrap}.md-source:hover{opacity:.7}.md-source:after,.md-source__icon{display:inline-block;height:4.8rem;content:"";vertical-align:middle}.md-source__icon{width:4.8rem}.md-source__icon svg{margin-top:1.2rem;margin-left:1.2rem}.md-source__icon+.md-source__repository{margin-left:-4.4rem;padding-left:4rem}.md-source__repository{display:inline-block;max-width:100%;margin-left:1.2rem;font-weight:700;text-overflow:ellipsis;overflow:hidden;vertical-align:middle}.md-source__facts{margin:0;padding:0;font-size:1.1rem;font-weight:700;list-style-type:none;opacity:.75;overflow:hidden}[data-md-state=done] .md-source__facts{-webkit-animation:a .25s ease-in;animation:a .25s ease-in}.md-source__fact{float:left}[data-md-state=done] .md-source__fact{-webkit-animation:b .4s ease-out;animation:b .4s ease-out}.md-source__fact:before{margin:0 .2rem;content:"\00B7"}.md-source__fact:first-child:before{display:none}.md-tabs{width:100%;-webkit-transition:background .25s;transition:background .25s;background:rgba(98,113,140,.9675);overflow:auto}.md-tabs__list{margin:0;margin-left:.4rem;padding:0;list-style:none;white-space:nowrap}.md-tabs__item{display:inline-block;height:4.8rem;padding-right:1.2rem;padding-left:1.2rem}.md-tabs__link{display:block;margin-top:1.6rem;-webkit-transition:color .25s,opacity .1s,-webkit-transform .4s cubic-bezier(.1,.7,.1,1);transition:color .25s,opacity .1s,-webkit-transform .4s cubic-bezier(.1,.7,.1,1);transition:color .25s,transform .4s cubic-bezier(.1,.7,.1,1),opacity .1s;transition:color .25s,transform .4s cubic-bezier(.1,.7,.1,1),opacity .1s,-webkit-transform .4s cubic-bezier(.1,.7,.1,1);color:hsla(0,0%,100%,.7);font-size:1.4rem}.md-tabs__link--active,.md-tabs__link:hover{color:#fff}.md-tabs__item:nth-child(2) .md-tabs__link{-webkit-transition-delay:.02s;transition-delay:.02s}.md-tabs__item:nth-child(3) .md-tabs__link{-webkit-transition-delay:.04s;transition-delay:.04s}.md-tabs__item:nth-child(4) .md-tabs__link{-webkit-transition-delay:.06s;transition-delay:.06s}.md-tabs__item:nth-child(5) .md-tabs__link{-webkit-transition-delay:.08s;transition-delay:.08s}.md-tabs__item:nth-child(6) .md-tabs__link{-webkit-transition-delay:.1s;transition-delay:.1s}.md-tabs__item:nth-child(7) .md-tabs__link{-webkit-transition-delay:.12s;transition-delay:.12s}.md-tabs__item:nth-child(8) .md-tabs__link{-webkit-transition-delay:.14s;transition-delay:.14s}.md-tabs__item:nth-child(9) .md-tabs__link{-webkit-transition-delay:.16s;transition-delay:.16s}.md-tabs__item:nth-child(10) .md-tabs__link{-webkit-transition-delay:.18s;transition-delay:.18s}.md-tabs__item:nth-child(11) .md-tabs__link{-webkit-transition-delay:.2s;transition-delay:.2s}.md-tabs__item:nth-child(12) .md-tabs__link{-webkit-transition-delay:.22s;transition-delay:.22s}.md-tabs__item:nth-child(13) .md-tabs__link{-webkit-transition-delay:.24s;transition-delay:.24s}.md-tabs__item:nth-child(14) .md-tabs__link{-webkit-transition-delay:.26s;transition-delay:.26s}.md-tabs__item:nth-child(15) .md-tabs__link{-webkit-transition-delay:.28s;transition-delay:.28s}.md-tabs__item:nth-child(16) .md-tabs__link{-webkit-transition-delay:.3s;transition-delay:.3s}.md-tabs[data-md-state=hidden]{background:#7b8eb0}.md-tabs[data-md-state=hidden] .md-tabs__link{-webkit-transform:translateY(50%);transform:translateY(50%);-webkit-transition:color .25s,opacity .1s,-webkit-transform 0s .4s;transition:color .25s,opacity .1s,-webkit-transform 0s .4s;transition:color .25s,transform 0s .4s,opacity .1s;transition:color .25s,transform 0s .4s,opacity .1s,-webkit-transform 0s .4s;opacity:0}.admonition{position:relative;margin:1.5625em 0;padding:.8rem 1.2rem;border-left:3.2rem solid rgba(68,138,255,.4);border-radius:.2rem;background-color:rgba(68,138,255,.15);font-size:1.28rem}.admonition:before{position:absolute;left:-2.6rem;color:#fff;font-size:2rem;content:"edit";vertical-align:-.25em}.admonition :first-child{margin-top:0}.admonition :last-child{margin-bottom:0}.admonition.summary,.admonition.tldr{border-color:rgba(0,176,255,.4);background-color:rgba(0,176,255,.15)}.admonition.summary:before,.admonition.tldr:before{content:"subject"}.admonition.hint,.admonition.important,.admonition.tip{border-color:rgba(0,191,165,.4);background-color:rgba(0,191,165,.15)}.admonition.hint:before,.admonition.important:before,.admonition.tip:before{content:"whatshot"}.admonition.check,.admonition.done,.admonition.success{border-color:rgba(0,230,118,.4);background-color:rgba(0,230,118,.15)}.admonition.check:before,.admonition.done:before,.admonition.success:before{content:"done"}.admonition.attention,.admonition.caution,.admonition.warning{border-color:rgba(255,145,0,.4);background-color:rgba(255,145,0,.15)}.admonition.attention:before,.admonition.caution:before,.admonition.warning:before{content:"warning"}.admonition.fail,.admonition.failure,.admonition.missing{border-color:rgba(255,82,82,.4);background-color:rgba(255,82,82,.15)}.admonition.fail:before,.admonition.failure:before,.admonition.missing:before{content:"clear"}.admonition.danger,.admonition.error{border-color:rgba(255,23,68,.4);background-color:rgba(255,23,68,.15)}.admonition.danger:before,.admonition.error:before{content:"flash_on"}.admonition.bug{border-color:rgba(245,0,87,.4);background-color:rgba(245,0,87,.15)}.admonition.bug:before{content:"bug_report"}.admonition.cite,.admonition.quote{border-color:hsla(0,0%,62%,.4);background-color:hsla(0,0%,62%,.15)}.admonition.cite:before,.admonition.quote:before{content:"format_quote"}.admonition-title{font-weight:700}html .admonition-title{margin-bottom:0}html .admonition-title+*{margin-top:0}.codehilite .o,.codehilite .ow{color:inherit}.codehilite .ge{color:#000}.codehilite .gr{color:#a00}.codehilite .gh{color:#999}.codehilite .go{color:#888}.codehilite .gp{color:#555}.codehilite .gs{color:inherit}.codehilite .gu{color:#aaa}.codehilite .gt{color:#a00}.codehilite .gd{background-color:#fdd}.codehilite .gi{background-color:#dfd}.codehilite .k{color:#3b78e7}.codehilite .kc{color:#a71d5d}.codehilite .kd,.codehilite .kn{color:#3b78e7}.codehilite .kp{color:#a71d5d}.codehilite .kr,.codehilite .kt{color:#3e61a2}.codehilite .c,.codehilite .cm{color:#999}.codehilite .cp{color:#666}.codehilite .c1,.codehilite .ch,.codehilite .cs{color:#999}.codehilite .na,.codehilite .nb{color:#c2185b}.codehilite .bp{color:#3e61a2}.codehilite .nc{color:#c2185b}.codehilite .no{color:#3e61a2}.codehilite .nd,.codehilite .ni{color:#666}.codehilite .ne,.codehilite .nf{color:#c2185b}.codehilite .nl{color:#3b5179}.codehilite .nn{color:#ec407a}.codehilite .nt{color:#3b78e7}.codehilite .nv,.codehilite .vc,.codehilite .vg,.codehilite .vi{color:#3e61a2}.codehilite .nx{color:#ec407a}.codehilite .il,.codehilite .m,.codehilite .mf,.codehilite .mh,.codehilite .mi,.codehilite .mo{color:#e74c3c}.codehilite .s,.codehilite .sb,.codehilite .sc{color:#0d904f}.codehilite .sd{color:#999}.codehilite .s2{color:#0d904f}.codehilite .se,.codehilite .sh,.codehilite .si,.codehilite .sx{color:#183691}.codehilite .sr{color:#009926}.codehilite .s1,.codehilite .ss{color:#0d904f}.codehilite .err{color:#a61717}.codehilite .w{color:transparent}.codehilite .hll{display:block;margin:0 -1.2rem;padding:0 1.2rem;background-color:rgba(255,235,59,.5)}.md-typeset .codehilite{margin:1em 0;padding:1rem 1.2rem .8rem;border-radius:.2rem;background-color:hsla(0,0%,93%,.5);color:#37474f;line-height:1.4;overflow:auto;-webkit-overflow-scrolling:touch}.md-typeset .codehilite::-webkit-scrollbar{width:.4rem;height:.4rem}.md-typeset .codehilite::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.26)}.md-typeset .codehilite::-webkit-scrollbar-thumb:hover{background-color:#fca9a8}.md-typeset .codehilite pre{display:inline-block;min-width:100%;margin:0;padding:0;background-color:transparent;overflow:visible;vertical-align:top}.md-typeset .codehilitetable{display:block;margin:1em 0;border-radius:.2em;font-size:1.6rem;overflow:hidden}.md-typeset .codehilitetable tbody,.md-typeset .codehilitetable td{display:block;padding:0}.md-typeset .codehilitetable tr{display:-webkit-box;display:-ms-flexbox;display:flex}.md-typeset .codehilitetable .codehilite,.md-typeset .codehilitetable .linenodiv{margin:0;border-radius:0}.md-typeset .codehilitetable .linenodiv{padding:1rem 1.2rem .8rem}.md-typeset .codehilitetable .linenodiv,.md-typeset .codehilitetable .linenodiv>pre{height:100%}.md-typeset .codehilitetable .linenos{background-color:rgba(0,0,0,.07);color:rgba(0,0,0,.26);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.md-typeset .codehilitetable .linenos pre{margin:0;padding:0;background-color:transparent;color:inherit;text-align:right}.md-typeset .codehilitetable .code{-webkit-box-flex:1;-ms-flex:1;flex:1;overflow:hidden}.md-typeset>.codehilitetable{box-shadow:none}.md-typeset .footnote{color:rgba(0,0,0,.54);font-size:1.28rem}.md-typeset .footnote ol{margin-left:0}.md-typeset .footnote li{-webkit-transition:color .25s;transition:color .25s}.md-typeset .footnote li:before{display:block;height:0}.md-typeset .footnote li:target{color:rgba(0,0,0,.87)}.md-typeset .footnote li:target:before{margin-top:-9rem;padding-top:9rem;pointer-events:none}.md-typeset .footnote li :first-child{margin-top:0}.md-typeset .footnote li:hover .footnote-backref,.md-typeset .footnote li:target .footnote-backref{-webkit-transform:translateX(0);transform:translateX(0);opacity:1}.md-typeset .footnote li:hover .footnote-backref:hover,.md-typeset .footnote li:target .footnote-backref{color:#fca9a8}.md-typeset .footnote-backref{display:inline-block;-webkit-transform:translateX(.5rem);transform:translateX(.5rem);-webkit-transition:color .25s,opacity .125s .125s,-webkit-transform .25s .125s;transition:color .25s,opacity .125s .125s,-webkit-transform .25s .125s;transition:transform .25s .125s,color .25s,opacity .125s .125s;transition:transform .25s .125s,color .25s,opacity .125s .125s,-webkit-transform .25s .125s;color:rgba(0,0,0,.26);font-size:0;opacity:0;vertical-align:text-bottom}.md-typeset .footnote-backref:before{font-size:1.6rem;content:"keyboard_return"}.md-typeset .headerlink{display:inline-block;margin-left:1rem;-webkit-transform:translateY(.5rem);transform:translateY(.5rem);-webkit-transition:color .25s,opacity .125s .25s,-webkit-transform .25s .25s;transition:color .25s,opacity .125s .25s,-webkit-transform .25s .25s;transition:transform .25s .25s,color .25s,opacity .125s .25s;transition:transform .25s .25s,color .25s,opacity .125s .25s,-webkit-transform .25s .25s;opacity:0}html body .md-typeset .headerlink{color:rgba(0,0,0,.26)}.md-typeset [id]:before{display:inline-block;content:""}.md-typeset [id]:target:before{margin-top:-9.8rem;padding-top:9.8rem}.md-typeset [id] .headerlink:focus,.md-typeset [id]:hover .headerlink,.md-typeset [id]:target .headerlink{-webkit-transform:translate(0);transform:translate(0);opacity:1}.md-typeset [id] .headerlink:focus,.md-typeset [id]:hover .headerlink:hover,.md-typeset [id]:target .headerlink{color:#fca9a8}.md-typeset h1[id]{padding-top:.8rem}.md-typeset h1[id] .headerlink{display:none}.md-typeset h2[id]:before{display:block;margin-top:-.4rem;padding-top:.4rem}.md-typeset h2[id]:target:before{margin-top:-8.4rem;padding-top:8.4rem}.md-typeset h3[id]:before{display:block;margin-top:-.7rem;padding-top:.7rem}.md-typeset h3[id]:target:before{margin-top:-8.7rem;padding-top:8.7rem}.md-typeset h4[id]:before{display:block;margin-top:-.8rem;padding-top:.8rem}.md-typeset h4[id]:target:before{margin-top:-8.8rem;padding-top:8.8rem}.md-typeset h5[id]:before{display:block;margin-top:-1.1rem;padding-top:1.1rem}.md-typeset h5[id]:target:before{margin-top:-9.1rem;padding-top:9.1rem}.md-typeset h6[id]:before{display:block;margin-top:-1.1rem;padding-top:1.1rem}.md-typeset h6[id]:target:before{margin-top:-9.1rem;padding-top:9.1rem}.md-typeset .MJXc-display{margin:.75em 0;padding:.25em 0;overflow:auto;-webkit-overflow-scrolling:touch}.md-typeset .MathJax_CHTML{outline:0}.md-typeset .comment.critic,.md-typeset del.critic,.md-typeset ins.critic{margin:0 .25em;padding:.0625em 0;border-radius:.2rem;-webkit-box-decoration-break:clone;box-decoration-break:clone}.md-typeset del.critic{background-color:#fdd;box-shadow:.25em 0 0 #fdd,-.25em 0 0 #fdd}.md-typeset ins.critic{background-color:#dfd;box-shadow:.25em 0 0 #dfd,-.25em 0 0 #dfd}.md-typeset .critic.comment{background-color:hsla(0,0%,93%,.5);color:#37474f;box-shadow:.25em 0 0 hsla(0,0%,93%,.5),-.25em 0 0 hsla(0,0%,93%,.5)}.md-typeset .critic.comment:before{padding-right:.125em;color:rgba(0,0,0,.26);content:"chat";vertical-align:-.125em}.md-typeset .critic.block{display:block;margin:1em 0;padding-right:1.6rem;padding-left:1.6rem;box-shadow:none}.md-typeset .critic.block :first-child{margin-top:.5em}.md-typeset .critic.block :last-child{margin-bottom:.5em}.md-typeset .emojione{width:2rem;vertical-align:text-top}.md-typeset code.codehilite{margin:0 .29412em;padding:.07353em 0}.md-typeset .task-list-item{position:relative;list-style-type:none}.md-typeset .task-list-item [type=checkbox]{position:absolute;top:.45em;left:-2em}.md-typeset .task-list-control .task-list-indicator:before{position:absolute;top:.05em;left:-1.25em;color:rgba(0,0,0,.26);font-size:1.5em;content:"check_box_outline_blank";vertical-align:-.25em}.md-typeset .task-list-control [type=checkbox]:checked+.task-list-indicator:before{content:"check_box"}.md-typeset .task-list-control [type=checkbox]{opacity:0;z-index:-1}@media print{.md-typeset a:after{color:rgba(0,0,0,.54);content:" [" attr(href) "]"}.md-typeset code{box-shadow:none;-webkit-box-decoration-break:initial;box-decoration-break:slice}.md-content__edit,.md-footer,.md-header,.md-sidebar,.md-typeset .headerlink{display:none}}@media only screen and (max-width:44.9375em){.md-typeset pre{margin:1em -1.6rem;padding:1rem 1.6rem;border-radius:0}.md-footer-nav__link--prev .md-footer-nav__title{display:none}.codehilite .hll{margin:0 -1.6rem;padding:0 1.6rem}.md-typeset>.codehilite{padding:1rem 1.6rem .8rem}.md-typeset>.codehilite,.md-typeset>.codehilitetable{margin:1em -1.6rem;border-radius:0}.md-typeset>.codehilitetable .codehilite,.md-typeset>.codehilitetable .linenodiv{padding:1rem 1.6rem}.md-typeset>p>.MJXc-display{margin:.75em -1.6rem;padding:.25em 1.6rem}}@media only screen and (min-width:100em){html{font-size:68.75%}}@media only screen and (min-width:125em){html{font-size:75%}}@media only screen and (max-width:59.9375em){body[data-md-state=lock]{overflow:hidden}.ios body[data-md-state=lock] .md-container{display:none}.md-content__edit{margin-right:-.8rem}.md-nav--secondary{border-left:0}html .md-nav__link[for=toc]{display:block;padding-right:4.8rem}html .md-nav__link[for=toc]:after{color:inherit;content:"toc"}html .md-nav__link[for=toc]+.md-nav__link{display:none}html .md-nav__link[for=toc]~.md-nav{display:-webkit-box;display:-ms-flexbox;display:flex}.md-nav__source{display:block;padding:.4rem;background-color:rgba(98,113,140,.9675);color:#fff}.md-search__overlay{display:block;position:absolute;top:.4rem;left:.4rem;width:4rem;height:4rem;-webkit-transform-origin:center;transform-origin:center;-webkit-transition:opacity .2s .2s,-webkit-transform .3s .1s;transition:opacity .2s .2s,-webkit-transform .3s .1s;transition:transform .3s .1s,opacity .2s .2s;transition:transform .3s .1s,opacity .2s .2s,-webkit-transform .3s .1s;border-radius:2rem;background-color:#fff;opacity:0;overflow:hidden;z-index:1}[data-md-toggle=search]:checked~.md-header .md-search__overlay{-webkit-transition:opacity .1s,-webkit-transform .4s;transition:opacity .1s,-webkit-transform .4s;transition:transform .4s,opacity .1s;transition:transform .4s,opacity .1s,-webkit-transform .4s;opacity:1}.md-search__inner{position:fixed;top:0;left:100%;height:100%;-webkit-transform:translateX(5%);transform:translateX(5%);-webkit-transition:left 0s .3s,opacity .15s .15s,-webkit-transform .15s cubic-bezier(.4,0,.2,1) .15s;transition:left 0s .3s,opacity .15s .15s,-webkit-transform .15s cubic-bezier(.4,0,.2,1) .15s;transition:left 0s .3s,transform .15s cubic-bezier(.4,0,.2,1) .15s,opacity .15s .15s;transition:left 0s .3s,transform .15s cubic-bezier(.4,0,.2,1) .15s,opacity .15s .15s,-webkit-transform .15s cubic-bezier(.4,0,.2,1) .15s;opacity:0;z-index:2}[data-md-toggle=search]:checked~.md-header .md-search__inner{left:0;-webkit-transform:translateX(0);transform:translateX(0);-webkit-transition:left 0s 0s,opacity .15s .15s,-webkit-transform .15s cubic-bezier(.1,.7,.1,1) .15s;transition:left 0s 0s,opacity .15s .15s,-webkit-transform .15s cubic-bezier(.1,.7,.1,1) .15s;transition:left 0s 0s,transform .15s cubic-bezier(.1,.7,.1,1) .15s,opacity .15s .15s;transition:left 0s 0s,transform .15s cubic-bezier(.1,.7,.1,1) .15s,opacity .15s .15s,-webkit-transform .15s cubic-bezier(.1,.7,.1,1) .15s;opacity:1}.md-search__input{width:100%;height:5.6rem;font-size:1.8rem}.md-search__icon{top:1.6rem;left:1.6rem}.md-search__icon:before{content:"arrow_back"}.md-search__output{top:5.6rem;bottom:0}}@media only screen and (max-width:76.1875em){[data-md-toggle=drawer]:checked~.md-overlay{width:100%;height:100%;-webkit-transition:width 0s,height 0s,opacity .25s;transition:width 0s,height 0s,opacity .25s;opacity:1}.md-header-nav__button.md-icon--home,.md-header-nav__button.md-logo{display:none}.md-nav{background-color:#fff}.md-nav--primary,.md-nav--primary .md-nav{display:-webkit-box;display:-ms-flexbox;display:flex;position:absolute;top:0;right:0;left:0;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;height:100%;z-index:1}.md-nav--primary .md-nav__item,.md-nav--primary .md-nav__title{font-size:1.6rem;line-height:1.5}html .md-nav--primary .md-nav__title{position:relative;height:11.2rem;padding:6rem 1.6rem .4rem;background-color:rgba(0,0,0,.07);color:rgba(0,0,0,.54);font-weight:400;line-height:4.8rem;white-space:nowrap;cursor:pointer}html .md-nav--primary .md-nav__title:before{display:block;position:absolute;top:.4rem;left:.4rem;width:4rem;height:4rem;color:rgba(0,0,0,.54)}html .md-nav--primary .md-nav__title~.md-nav__list{background:-webkit-linear-gradient(top,#fff 10%,hsla(0,0%,100%,0)),-webkit-linear-gradient(top,rgba(0,0,0,.26),rgba(0,0,0,.07) 35%,transparent 60%);background:linear-gradient(180deg,#fff 10%,hsla(0,0%,100%,0)),linear-gradient(180deg,rgba(0,0,0,.26),rgba(0,0,0,.07) 35%,transparent 60%);background-attachment:local,scroll;background-color:#fff;background-repeat:no-repeat;background-size:100% 2rem,100% 1rem;box-shadow:inset 0 .1rem 0 rgba(0,0,0,.07)}html .md-nav--primary .md-nav__title~.md-nav__list>.md-nav__item:first-child{border-top:0}html .md-nav--primary .md-nav__title--site{position:relative;background-color:#7b8eb0;color:#fff}html .md-nav--primary .md-nav__title--site .md-nav__button{display:block;position:absolute;top:.4rem;left:.4rem;width:6.4rem;height:6.4rem;font-size:4.8rem}html .md-nav--primary .md-nav__title--site:before{display:none}.md-nav--primary .md-nav__list{-webkit-box-flex:1;-ms-flex:1;flex:1;overflow-y:auto}.md-nav--primary .md-nav__item{padding:0;border-top:.1rem solid rgba(0,0,0,.07)}.md-nav--primary .md-nav__item--nested>.md-nav__link{padding-right:4.8rem}.md-nav--primary .md-nav__item--nested>.md-nav__link:after{content:"keyboard_arrow_right"}.md-nav--primary .md-nav__link{position:relative;margin-top:0;padding:1.6rem}.md-nav--primary .md-nav__link:after{position:absolute;top:50%;right:1.2rem;margin-top:-1.2rem;color:rgba(0,0,0,.54);font-size:2.4rem}.md-nav--primary .md-nav__link:focus:after,.md-nav--primary .md-nav__link:hover:after{color:inherit}.md-nav--primary .md-nav--secondary .md-nav{position:static}.md-nav--primary .md-nav--secondary .md-nav .md-nav__link{padding-left:2.8rem}.md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav__link{padding-left:4rem}.md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav__link{padding-left:5.2rem}.md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav .md-nav__link{padding-left:6.4rem}.md-nav__toggle~.md-nav{display:none}.csstransforms3d .md-nav__toggle~.md-nav{-webkit-transform:translateX(100%);transform:translateX(100%);-webkit-transition:opacity .125s .05s,-webkit-transform .25s cubic-bezier(.8,0,.6,1);transition:opacity .125s .05s,-webkit-transform .25s cubic-bezier(.8,0,.6,1);transition:transform .25s cubic-bezier(.8,0,.6,1),opacity .125s .05s;transition:transform .25s cubic-bezier(.8,0,.6,1),opacity .125s .05s,-webkit-transform .25s cubic-bezier(.8,0,.6,1);opacity:0}.csstransforms3d .md-nav__toggle~.md-nav,.md-nav__toggle:checked~.md-nav{display:-webkit-box;display:-ms-flexbox;display:flex}.csstransforms3d .md-nav__toggle:checked~.md-nav{-webkit-transform:translateX(0);transform:translateX(0);-webkit-transition:opacity .125s .125s,-webkit-transform .25s cubic-bezier(.4,0,.2,1);transition:opacity .125s .125s,-webkit-transform .25s cubic-bezier(.4,0,.2,1);transition:transform .25s cubic-bezier(.4,0,.2,1),opacity .125s .125s;transition:transform .25s cubic-bezier(.4,0,.2,1),opacity .125s .125s,-webkit-transform .25s cubic-bezier(.4,0,.2,1);opacity:1}.md-sidebar--primary{position:fixed;top:0;left:-24.2rem;width:24.2rem;height:100%;-webkit-transform:translateX(0);transform:translateX(0);-webkit-transition:box-shadow .25s,-webkit-transform .25s cubic-bezier(.4,0,.2,1);transition:box-shadow .25s,-webkit-transform .25s cubic-bezier(.4,0,.2,1);transition:transform .25s cubic-bezier(.4,0,.2,1),box-shadow .25s;transition:transform .25s cubic-bezier(.4,0,.2,1),box-shadow .25s,-webkit-transform .25s cubic-bezier(.4,0,.2,1);background-color:#fff;z-index:2}.no-csstransforms3d .md-sidebar--primary{display:none}[data-md-toggle=drawer]:checked~.md-container .md-sidebar--primary{box-shadow:0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12),0 5px 5px -3px rgba(0,0,0,.4);-webkit-transform:translateX(24.2rem);transform:translateX(24.2rem)}.no-csstransforms3d [data-md-toggle=drawer]:checked~.md-container .md-sidebar--primary{display:block}.md-sidebar--primary .md-sidebar__scrollwrap{overflow:hidden;position:absolute;top:0;right:0;bottom:0;left:0;margin:0}.md-tabs{display:none}}@media only screen and (min-width:60em){.md-content{margin-right:24.2rem}.md-header-nav__button.md-icon--search{display:none}.md-header-nav__source{display:block;width:23rem;max-width:23rem;padding-right:1.2rem}.md-search{margin-right:2.8rem;padding:.4rem}.md-search__inner{display:table;position:relative;clear:both}.md-search__form{width:23rem;float:right;-webkit-transition:width .25s cubic-bezier(.1,.7,.1,1);transition:width .25s cubic-bezier(.1,.7,.1,1);border-radius:.2rem}.md-search__input{width:100%;height:4rem;padding-left:4.8rem;-webkit-transition:background-color .25s,color .25s;transition:background-color .25s,color .25s;border-radius:.2rem;background-color:rgba(0,0,0,.26);color:#fff;font-size:1.6rem}.md-search__input+.md-search__icon,.md-search__input::-webkit-input-placeholder{-webkit-transition:color .25s;transition:color .25s;color:#fff}.md-search__input+.md-search__icon,.md-search__input::-moz-placeholder{-webkit-transition:color .25s;transition:color .25s;color:#fff}.md-search__input+.md-search__icon,.md-search__input:-ms-input-placeholder{-webkit-transition:color .25s;transition:color .25s;color:#fff}.md-search__input+.md-search__icon,.md-search__input::placeholder{-webkit-transition:color .25s;transition:color .25s;color:#fff}.md-search__input:hover{background-color:hsla(0,0%,100%,.12)}[data-md-toggle=search]:checked~.md-header .md-search__input{border-radius:.2rem .2rem 0 0;background-color:#fff;color:rgba(0,0,0,.87);text-overflow:none}[data-md-toggle=search]:checked~.md-header .md-search__input+.md-search__icon,[data-md-toggle=search]:checked~.md-header .md-search__input::-webkit-input-placeholder{color:rgba(0,0,0,.54)}[data-md-toggle=search]:checked~.md-header .md-search__input+.md-search__icon,[data-md-toggle=search]:checked~.md-header .md-search__input::-moz-placeholder{color:rgba(0,0,0,.54)}[data-md-toggle=search]:checked~.md-header .md-search__input+.md-search__icon,[data-md-toggle=search]:checked~.md-header .md-search__input:-ms-input-placeholder{color:rgba(0,0,0,.54)}[data-md-toggle=search]:checked~.md-header .md-search__input+.md-search__icon,[data-md-toggle=search]:checked~.md-header .md-search__input::placeholder{color:rgba(0,0,0,.54)}.md-search__output{top:4rem;-webkit-transition:opacity .4s;transition:opacity .4s;opacity:0}[data-md-toggle=search]:checked~.md-header .md-search__output{box-shadow:0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12),0 3px 5px -1px rgba(0,0,0,.4);opacity:1}.md-search__scrollwrap{max-height:0}[data-md-toggle=search]:checked~.md-header .md-search__scrollwrap{max-height:75vh}.md-search__scrollwrap::-webkit-scrollbar{width:.4rem;height:.4rem}.md-search__scrollwrap::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.26)}.md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:#fca9a8}.md-search-result__link,.md-search-result__meta{padding-left:4.8rem}.md-sidebar--secondary{display:block;float:right}.md-sidebar--secondary[data-md-state=lock]{margin-left:100%;-webkit-transform:translate(-100%);transform:translate(-100%)}}@media only screen and (min-width:76.25em){.md-content{margin-left:24.2rem;overflow:auto}.md-content__inner{margin:2.4rem}.md-header{box-shadow:none}.md-header[data-md-state=shadow]{box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2)}.md-header-nav__button.md-icon--menu{display:none}.md-nav[data-md-state=animate]{-webkit-transition:max-height .25s cubic-bezier(.86,0,.07,1);transition:max-height .25s cubic-bezier(.86,0,.07,1)}.md-nav__toggle~.md-nav{max-height:0;overflow:hidden}.md-nav[data-md-state=expand],.md-nav__toggle:checked~.md-nav{max-height:100%}.md-nav__item--nested>.md-nav>.md-nav__title{display:none}.md-nav__item--nested>.md-nav__link:after{display:inline-block;-webkit-transform-origin:.45em .45em;transform-origin:.45em .45em;-webkit-transform-style:preserve-3d;transform-style:preserve-3d;vertical-align:-.125em}.js .md-nav__item--nested>.md-nav__link:after{-webkit-transition:-webkit-transform .4s;transition:-webkit-transform .4s;transition:transform .4s;transition:transform .4s,-webkit-transform .4s}.md-nav__item--nested .md-nav__toggle:checked~.md-nav__link:after{-webkit-transform:rotateX(180deg);transform:rotateX(180deg)}.md-search__scrollwrap,[data-md-toggle=search]:checked~.md-header .md-search__form{width:68.8rem}.md-sidebar__inner{border-right:.1rem solid rgba(0,0,0,.07)}.md-tabs~.md-main .md-nav--primary>.md-nav__list>.md-nav__item--nested{font-size:0}.md-tabs--active~.md-main .md-nav--primary .md-nav__title--site{display:none}.md-tabs--active~.md-main .md-nav--primary>.md-nav__list>.md-nav__item{font-size:0}.md-tabs--active~.md-main .md-nav--primary>.md-nav__list>.md-nav__item--nested{display:none;font-size:1.4rem;overflow:auto}.md-tabs--active~.md-main .md-nav--primary>.md-nav__list>.md-nav__item--nested>.md-nav__link{margin-top:1.2rem;font-weight:700;pointer-events:none}.md-tabs--active~.md-main .md-nav--primary>.md-nav__list>.md-nav__item--nested>.md-nav__link:after{display:none}.md-tabs--active~.md-main .md-nav--primary>.md-nav__list>.md-nav__item--active{display:block}.md-tabs--active~.md-main .md-nav[data-md-level="1"]{max-height:none}.md-tabs--active~.md-main .md-nav[data-md-level="1"]>.md-nav__list>.md-nav__item{padding-left:0}}@media only screen and (max-width:29.9375em){.md-header-nav__parent{display:none}[data-md-toggle=search]:checked~.md-header .md-search__overlay{-webkit-transform:scale(45);transform:scale(45)}}@media only screen and (min-width:45em){.md-footer-nav__link{width:50%}.md-footer-copyright{max-width:75%;float:left}.md-footer-social{padding:1.2rem 0;float:right}}@media only screen and (min-width:30em) and (max-width:44.9375em){[data-md-toggle=search]:checked~.md-header .md-search__overlay{-webkit-transform:scale(60);transform:scale(60)}}@media only screen and (min-width:45em) and (max-width:59.9375em){[data-md-toggle=search]:checked~.md-header .md-search__overlay{-webkit-transform:scale(75);transform:scale(75)}}@media only screen and (min-width:60em) and (max-width:76.1875em){.md-search__scrollwrap,[data-md-toggle=search]:checked~.md-header .md-search__form{width:46.8rem}}@media only screen and (min-width:60em) and (min-width:76.25em){.md-sidebar--secondary[data-md-state=lock]{margin-left:122rem}} \ No newline at end of file diff --git a/2.0/vapor-material/base.html b/2.0/vapor-material/base.html new file mode 100644 index 00000000..fb668bb6 --- /dev/null +++ b/2.0/vapor-material/base.html @@ -0,0 +1,158 @@ +{% import "partials/language.html" as lang %} + + + + {% block site_meta %} + + + {% if config.site_description %} + + {% endif %} + {% if page.canonical_url %} + + {% endif %} + {% if config.site_author %} + + {% endif %} + {% if config.site_favicon %} + + {% else %} + + {% endif %} + + {% endblock %} + {% block htmltitle %} + {% if page.title and not page.is_homepage %} + {{ page.title }} - {{ config.site_name }} + {% else %} + {{ config.site_name }} + {% endif %} + {% endblock %} + {% block libs %} + + {% endblock %} + {% block styles %} + + {% if config.extra.palette %} + + {% endif %} + {% endblock %} + {% block fonts %} + {% if config.extra.font != "none" %} + {% set text = config.extra.get("font", {}).text | default("Roboto") %} + {% set code = config.extra.get("font", {}).code + | default("Roboto Mono") %} + {% set font = text + ':300,400,400i,700|' + code | replace(' ', '+') %} + + + {% endif %} + + {% endblock %} + {% for path in extra_css %} + + {% endfor %} + {% block extrahead %}{% endblock %} + + {% set palette = config.extra.get("palette", {}) %} + {% set primary = palette.primary | replace(" ", "-") | lower %} + {% set accent = palette.accent | replace(" ", "-") | lower %} + {% if primary or accent %} + + {% else %} + + {% endif %} + + + {% set platform = config.extra.repo_icon or config.repo_url %} + {% if "github" in platform %} + {% include "assets/images/icons/github-1da075986e.svg" %} + {% elif "gitlab" in platform %} + {% include "assets/images/icons/gitlab-5ad3f9f9e5.svg" %} + {% elif "bitbucket" in platform %} + {% include "assets/images/icons/bitbucket-670608a71a.svg" %} + {% endif %} + + + + + + {% block header %} + {% include "partials/header.html" %} + {% endblock %} +
    + {% set feature = config.extra.get("feature", {}) %} + {% if feature.tabs %} + {% include "partials/tabs.html" %} + {% endif %} +
    +
    + {% block site_nav %} + {% if nav %} +
    +
    +
    + {% include "partials/nav.html" %} +
    +
    +
    + {% endif %} + {% if page.toc %} +
    +
    +
    + {% include "partials/toc.html" %} +
    +
    +
    + {% endif %} + {% endblock %} +
    +
    + {% if config.edit_uri %} + edit + {% endif %} + {% block content %} + {% if not "\x3ch1" in page.content %} +

    {{ page.title | default(config.site_name, true)}}

    + {% endif %} + {{ page.content }} + {% endblock %} + {% if config.extra.disqus and not page.is_homepage %} +

    {{ lang.t('comments') }}

    +
    + + {% endif %} +
    +
    +
    +
    + {% block footer %} + {% include "partials/footer.html" %} + {% endblock %} +
    + {% block scripts %} + + + {% for path in extra_javascript %} + + {% endfor %} + {% endblock %} + {% block analytics %} + {% if config.google_analytics %} + + {% endif %} + {% endblock %} + + diff --git a/2.0/vapor-material/main.html b/2.0/vapor-material/main.html new file mode 100644 index 00000000..94d9808c --- /dev/null +++ b/2.0/vapor-material/main.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/2.0/vapor-material/partials/footer.html b/2.0/vapor-material/partials/footer.html new file mode 100644 index 00000000..afadcdd6 --- /dev/null +++ b/2.0/vapor-material/partials/footer.html @@ -0,0 +1,58 @@ +{% import "partials/language.html" as lang %} + diff --git a/2.0/vapor-material/partials/header.html b/2.0/vapor-material/partials/header.html new file mode 100644 index 00000000..fda79778 --- /dev/null +++ b/2.0/vapor-material/partials/header.html @@ -0,0 +1,46 @@ +
    + +
    diff --git a/2.0/vapor-material/partials/language.html b/2.0/vapor-material/partials/language.html new file mode 100644 index 00000000..9e00a86f --- /dev/null +++ b/2.0/vapor-material/partials/language.html @@ -0,0 +1,9 @@ +{% macro t(key) %}{{ { + "edit.link.title": "Edit this page", + "comments": "Comments", + "footer.previous": "Previous", + "footer.next": "Next", + "search.placeholder": "Search", + "source.link.title": "Go to repository", + "toc.title": "Table of contents" +}[key] }}{% endmacro %} diff --git a/2.0/vapor-material/partials/nav-item.html b/2.0/vapor-material/partials/nav-item.html new file mode 100644 index 00000000..8d09de18 --- /dev/null +++ b/2.0/vapor-material/partials/nav-item.html @@ -0,0 +1,54 @@ +{% set class = "md-nav__item" %} +{% if nav_item.active %} + {% set class = "md-nav__item md-nav__item--active" %} +{% endif %} +{% if nav_item.children %} +
  • + {% if nav_item.active %} + + {% else %} + + {% endif %} + + +
  • +{% elif nav_item == page %} +
  • + {% set toc_ = page.toc %} + + {% if toc_ | first is defined %} + {% set toc_ = (toc_ | first).children %} + {% endif %} + {% if toc_ | first is defined %} + + {% endif %} + + {{ nav_item.title }} + + {% if toc_ | first is defined %} + {% include "partials/toc.html" %} + {% endif %} +
  • +{% else %} +
  • + + {{ nav_item.title }} + +
  • +{% endif %} diff --git a/2.0/vapor-material/partials/nav.html b/2.0/vapor-material/partials/nav.html new file mode 100644 index 00000000..651608d4 --- /dev/null +++ b/2.0/vapor-material/partials/nav.html @@ -0,0 +1,24 @@ + diff --git a/2.0/vapor-material/partials/search.html b/2.0/vapor-material/partials/search.html new file mode 100644 index 00000000..28337cca --- /dev/null +++ b/2.0/vapor-material/partials/search.html @@ -0,0 +1,15 @@ +{% import "partials/language.html" as lang %} + diff --git a/2.0/vapor-material/partials/social.html b/2.0/vapor-material/partials/social.html new file mode 100644 index 00000000..cb68735a --- /dev/null +++ b/2.0/vapor-material/partials/social.html @@ -0,0 +1,9 @@ +{% if config.extra.social %} + +{% endif %} diff --git a/2.0/vapor-material/partials/source.html b/2.0/vapor-material/partials/source.html new file mode 100644 index 00000000..221b551a --- /dev/null +++ b/2.0/vapor-material/partials/source.html @@ -0,0 +1,25 @@ +{% import "partials/language.html" as lang %} +{% set platform = config.extra.repo_icon or config.repo_url %} +{% if "github" in platform %} + {% set repo_type = "github" %} +{% elif "gitlab" in platform %} + {% set repo_type = "gitlab" %} +{% elif "bitbucket" in platform %} + {% set repo_type = "bitbucket" %} +{% else %} + {% set repo_type = "" %} +{% endif %} +{% block repo %} + + {% if repo_type %} +
    + + + +
    + {% endif %} +
    + {{ config.repo_name }} +
    +
    +{% endblock %} diff --git a/2.0/vapor-material/partials/tabs-item.html b/2.0/vapor-material/partials/tabs-item.html new file mode 100644 index 00000000..aef42d77 --- /dev/null +++ b/2.0/vapor-material/partials/tabs-item.html @@ -0,0 +1,25 @@ +{% if nav_item.is_homepage %} +
  • + {% if not page.ancestors | length and nav | selectattr("url", page.url) %} + + {{ nav_item.title }} + + {% else %} + + {{ nav_item.title }} + + {% endif %} +
  • +{% elif nav_item.children and nav_item.children | length > 0 %} +
  • + {% if nav_item.active %} + + {{ nav_item.title }} + + {% else %} + + {{ nav_item.title }} + + {% endif %} +
  • +{% endif %} diff --git a/2.0/vapor-material/partials/tabs.html b/2.0/vapor-material/partials/tabs.html new file mode 100644 index 00000000..e040436b --- /dev/null +++ b/2.0/vapor-material/partials/tabs.html @@ -0,0 +1,13 @@ +{% set class = "md-tabs" %} +{% if page.ancestors | length > 0 %} + {% set class = "md-tabs md-tabs--active" %} +{% endif %} + diff --git a/2.0/vapor-material/partials/toc-item.html b/2.0/vapor-material/partials/toc-item.html new file mode 100644 index 00000000..3b4f4d76 --- /dev/null +++ b/2.0/vapor-material/partials/toc-item.html @@ -0,0 +1,14 @@ +
  • + + {{ toc_item.title }} + + {% if toc_item.children %} + + {% endif %} +
  • diff --git a/2.0/vapor-material/partials/toc.html b/2.0/vapor-material/partials/toc.html new file mode 100644 index 00000000..5e44226b --- /dev/null +++ b/2.0/vapor-material/partials/toc.html @@ -0,0 +1,15 @@ +{% import "partials/language.html" as lang %} +