### Deploy Example Project with deployctl
Source: https://github.com/denoland/deployctl/blob/main/README.md
Navigates to an example project directory and deploys it using the deployctl command. This is a quick way to get started with Deno Deploy.
```shell
cd examples/hello-world
deployctl deploy
```
--------------------------------
### Quick Start Example
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/README.md
A basic example demonstrating how to make a request using Undici's `request` function.
```APIDOC
## Quick Start
```js
import { request } from 'undici'
const {
statusCode,
headers,
trailers,
body
} = await request('http://localhost:3000/foo')
console.log('response received', statusCode)
console.log('headers', headers)
for await (const data of body) {
console.log('data', data)
}
console.log('trailers', trailers)
```
```
--------------------------------
### Use Token for Git Operations with execa (JavaScript)
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
Provides an example of using both OAuth and installation access tokens for Git operations, specifically a 'git push'. It shows how to format the repository URL with the token, prefixing installation tokens with 'x-access-token:'.
```javascript
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const { token, tokenType } = await auth();
const tokenWithPrefix =
tokenType === "installation" ? `x-access-token:${token}` : token;
const repositoryUrl = `https://${tokenWithPrefix}@github.com/octocat/hello-world.git`;
const { stdout } = await execa("git", ["push", repositoryUrl]);
console.log(stdout);
```
--------------------------------
### Usage Example
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/plugin-rest-endpoint-methods/README.md
Demonstrates how to install and use the @octokit/plugin-rest-endpoint-methods with Octokit.js in both browser and Node.js environments.
```APIDOC
## Usage
### Browsers
Load `@octokit/plugin-rest-endpoint-methods` and [`@octokit/core`](https://github.com/octokit/core.js) (or core-compatible module) directly from [cdn.skypack.dev](https://cdn.skypack.dev)
```html
```
### Node.js
Install with `npm install @octokit/core @octokit/plugin-rest-endpoint-methods`. Optionally replace `@octokit/core` with a compatible module
```js
const { Octokit } = require("@octokit/core");
const {
restEndpointMethods,
} = require("@octokit/plugin-rest-endpoint-methods");
const MyOctokit = Octokit.plugin(restEndpointMethods);
const octokit = new MyOctokit({ auth: "secret123" });
// Example: https://developer.github.com/v3/users/#get-the-authenticated-user
octokit.rest.users.getAuthenticated();
```
## TypeScript
Parameter and response types for all endpoint methods are exported as `{ RestEndpointMethodTypes }`.
```ts
import { RestEndpointMethodTypes } from "@octokit/plugin-rest-endpoint-methods";
type UpdateLabelParameters = RestEndpointMethodTypes["issues"]["updateLabel"]["parameters"];
type UpdateLabelResponse = RestEndpointMethodTypes["issues"]["updateLabel"]["response"];
```
For types beyond parameters and responses, check out [`@octokit/openapi-types`](https://github.com/octokit/openapi-types.ts/#readme), which is a direct transpliation from GitHub's official OpenAPI specification.
```
--------------------------------
### Deploy Hello World Example (CLI)
Source: https://context7.com/denoland/deployctl/llms.txt
Command to navigate to the 'hello-world' example directory and deploy it using deployctl.
```bash
# Deploy the hello world example
cd examples/hello-world
deployctl deploy
```
--------------------------------
### Installation and Loading
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/node-fetch/README.md
Instructions on how to install the node-fetch module using npm and how to load it into your Node.js project.
```APIDOC
## Installation
Install the current stable release (`2.x`) using npm:
```sh
$ npm install node-fetch
```
## Loading the Module
It is recommended to load the module using `require`:
```javascript
const fetch = require('node-fetch');
```
## Configuring Promises
If you need to use a Promise library other than the native one, you can set it via `fetch.Promise`:
```javascript
const Bluebird = require('bluebird');
fetch.Promise = Bluebird;
```
```
--------------------------------
### Dispatch GET Request with Undici Client
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Dispatcher.md
Demonstrates how to dispatch a GET request using the Undici client. It sets up a basic HTTP server, creates an Undici client, and then dispatches a request with custom headers. The example includes handler functions for connection, headers, data reception, and completion, showcasing the lifecycle of an HTTP request and response.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
const data = []
client.dispatch({
path: '/',
method: 'GET',
headers: {
'x-foo': 'bar'
}
}, {
onConnect: () => {
console.log('Connected!')
},
onError: (error) => {
console.error(error)
},
onHeaders: (statusCode, headers) => {
console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`)
},
onData: (chunk) => {
console.log('onData: chunk received')
data.push(chunk)
},
onComplete: (trailers) => {
console.log(`onComplete | trailers: ${trailers}`)
const res = Buffer.concat(data).toString('utf8')
console.log(`Data: ${res}`)
client.close()
server.close()
}
})
```
--------------------------------
### Installing before-after-hook
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/before-after-hook/README.md
Provides instructions on how to install the before-after-hook library using npm. It also mentions the availability of a minified JavaScript file for direct download.
```bash
npm install before-after-hook
```
--------------------------------
### Install deployctl CLI
Source: https://context7.com/denoland/deployctl/llms.txt
Commands to install the deployctl tool globally using Deno's package manager and verify the installation.
```bash
# Install deployctl from JSR
deno install -gArf jsr:@deno/deployctl
# Verify installation
deployctl --version
```
--------------------------------
### Deploy Link Shortener Example (CLI)
Source: https://context7.com/denoland/deployctl/llms.txt
Commands to deploy the link shortener example application using deployctl, including specifying the project and entrypoint. Also shows how to create and use short links with curl.
```bash
# Deploy the link shortener
cd examples/link-shortener
deployctl deploy --project=my-links --entrypoint=main.ts
# Create a short link
curl -X POST https://my-links.deno.dev \
-H "Content-Type: application/json" \
-d '{"slug": "gh", "url": "https://github.com"}'
# Use the short link
curl -L https://my-links.deno.dev/gh
```
--------------------------------
### Deployctl Configuration File Examples
Source: https://context7.com/denoland/deployctl/llms.txt
Examples of configuring deployctl deployments using a JSON configuration file. This allows for repeatable deployments by storing settings like project name, entrypoint, and included/excluded files.
```json
{
"name": "@org/my-project",
"version": "1.0.0",
"exports": "./main.ts",
"deploy": {
"project": "my-project-id",
"entrypoint": "main.ts",
"include": ["src", "static"],
"exclude": ["tests", "*.test.ts"]
}
}
```
--------------------------------
### Common Usage Examples
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/node-fetch/README.md
Examples demonstrating various ways to use the fetch function, including fetching plain text, JSON, and making POST requests.
```APIDOC
## Common Usage
### Plain text or HTML
Fetch content from a URL and get the response as plain text.
```javascript
fetch('https://github.com/')
.then(res => res.text())
.then(body => console.log(body));
```
### JSON
Fetch JSON data from an API endpoint and parse it.
```javascript
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(json => console.log(json));
```
### Simple POST Request
Send a simple POST request with a string body.
```javascript
fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
.then(res => res.json()) // expecting a json response
.then(json => console.log(json));
```
### POST Request with JSON Body
Send a POST request with a JSON payload and appropriate headers.
```javascript
const body = { a: 1 };
fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
```
```
--------------------------------
### Install fetch-blob
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/fetch-blob/README.md
Installation command for the fetch-blob npm package.
```sh
npm install fetch-blob
```
--------------------------------
### Install Octokit.js for Node.js
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/core/README.md
Demonstrates how to install the @octokit/core package using npm and import the Octokit class in a Node.js environment. This is the standard way to begin using Octokit in server-side JavaScript projects.
```javascript
const { Octokit } = require("@octokit/core");
// or: import { Octokit } from "@octokit/core";
```
--------------------------------
### Retrieving Repository Permissions
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
Example demonstrating how to fetch repository permissions using an authenticated request. Note that permissions are not available for installation access tokens.
```APIDOC
## Find out what permissions are enabled for a repository
Note: The `permissions` key is not set when authenticated using an installation access token.
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("GET /repos/{owner}/{repo}", {
owner: 'octocat',
repo: 'hello-world',
headers: authentication.headers
});
console.log(response.data.permissions)
// {
// admin: true,
// push: true,
// pull: true
// }
```
```
--------------------------------
### Basic Authentication Example
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
Example of creating an authentication object using a personal access token and retrieving authentication details.
```APIDOC
## Basic Authentication Example
```js
const auth = createTokenAuth("ghp_PersonalAccessToken01245678900000000");
const authentication = await auth();
// {
// type: 'token',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
```
```
--------------------------------
### Installation
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/README.md
Install Undici using npm.
```APIDOC
## Install
```bash
npm i undici
```
```
--------------------------------
### Install deployctl CLI
Source: https://github.com/denoland/deployctl/blob/main/README.md
Installs the deployctl command-line tool globally using Deno's JSR package manager. Ensure Deno 1.46.0+ is installed.
```shell
deno install -gArf jsr:@deno/deployctl
```
--------------------------------
### Install node-fetch
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/node-fetch/README.md
Command to install the node-fetch package via npm.
```shell
npm install node-fetch
```
--------------------------------
### Hello World Deno Application
Source: https://context7.com/denoland/deployctl/llms.txt
A minimal Deno application that responds with 'Hello World' to any incoming request. This is a basic example for Deno Deploy.
```typescript
// main.ts
Deno.serve((_req) => new Response("Hello World"));
```
--------------------------------
### Node.js Usage
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
How to install and import @octokit/auth-token in a Node.js environment.
```APIDOC
## Node.js Usage
Install with `npm install @octokit/auth-token`
```js
const { createTokenAuth } = require("@octokit/auth-token");
// or: import { createTokenAuth } from "@octokit/auth-token";
```
```
--------------------------------
### Get deployctl Help Information
Source: https://github.com/denoland/deployctl/blob/main/README.md
Displays the help information for the deployctl command, listing all available subcommands and options.
```shell
deployctl -h
```
--------------------------------
### Retrieve Repository Permissions with createTokenAuth (JavaScript)
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
Illustrates how to fetch repository permissions using a token. Note that the 'permissions' key is not included when authenticated with an installation access token.
```javascript
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("GET /repos/{owner}/{repo}", {
owner: 'octocat',
repo: 'hello-world',
headers: authentication.headers
});
console.log(response.data.permissions)
// {
// admin: true,
// push: true,
// pull: true
// }
```
--------------------------------
### Usage Example
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/openapi-types/README.md
Demonstrates how to import and use the generated TypeScript types from the @octokit/openapi-types package.
```APIDOC
## Usage Example
### Description
This example shows how to import and utilize the generated TypeScript types for GitHub API schemas, specifically the 'full-repository' type.
### Method
N/A (This is a usage example for a TypeScript package)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```typescript
import { components } from "@octokit/openapi-types";
type Repository = components["schemas"]["full-repository"];
```
### Response
N/A
```
--------------------------------
### Dispatcher.connect(options[, callback])
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Dispatcher.md
Starts two-way communications with the requested resource using HTTP CONNECT. It accepts options and an optional callback.
```APIDOC
## Dispatcher.connect(options[, callback])
### Description
Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT).
### Method
`Dispatcher.connect`
### Parameters
#### Options (`ConnectOptions`)
- **path** `string` - The path for the CONNECT request.
- **headers** `UndiciHeaders` (optional) - Default: `null`. Headers to include in the CONNECT request.
- **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null`. An AbortSignal or EventEmitter to signal abortion.
- **opaque** `unknown` (optional) - This argument parameter is passed through to `ConnectData`.
#### Callback
- **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) - A callback function to be executed with the connection result.
### Returns
- `void | Promise` - Returns a `Promise` if no `callback` argument was passed, otherwise returns `void`.
#### `ConnectData` Object
- **statusCode** `number` - The HTTP status code of the connection response.
- **headers** `Record` - The headers received in the connection response.
- **socket** `stream.Duplex` - The duplex stream for two-way communication.
- **opaque** `unknown` - The opaque value passed during connection.
### Example - Connect request with echo
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
throw Error('should never get here')
}).listen()
server.on('connect', (req, socket, head) => {
socket.write('HTTP/1.1 200 Connection established\r\n\r\n')
let data = head.toString()
socket.on('data', (buf) => {
data += buf.toString()
})
socket.on('end', () => {
socket.end(data)
})
})
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { socket } = await client.connect({
path: '/'
})
const wanted = 'Body'
let data = ''
socket.on('data', d => { data += d })
socket.on('end', () => {
console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`)
client.close()
server.close()
})
socket.write(wanted)
socket.end()
} catch (error) { }
```
```
--------------------------------
### Node.js Usage of @octokit/auth-token
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
Shows how to install and import the createTokenAuth function for use in Node.js environments using npm.
```javascript
const { createTokenAuth } = require("@octokit/auth-token");
// or: import { createTokenAuth } from "@octokit/auth-token";
```
--------------------------------
### Using Tokens for Git Operations
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
Illustrates how to use authentication tokens (OAuth or installation) with a prefixed format for Git operations like `git push`.
```APIDOC
## Use token for git operations
Both OAuth and installation access tokens can be used for git operations. For installation tokens, prefix the token with `x-access-token`.
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const { token, tokenType } = await auth();
const tokenWithPrefix =
tokenType === "installation" ? `x-access-token:${token}` : token;
const repositoryUrl = `https://${tokenWithPrefix}@github.com/octocat/hello-world.git`;
const { stdout } = await execa("git", ["push", repositoryUrl]);
console.log(stdout);
```
```
--------------------------------
### Basic Request Mocking with Undici
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/MockPool.md
Demonstrates how to initialize a MockAgent and intercept a simple GET request to return a static response.
```javascript
import { MockAgent, setGlobalDispatcher, request } from 'undici'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
const { statusCode, body } = await request('http://localhost:3000/foo')
console.log('response received', statusCode)
for await (const data of body) {
console.log('data', data.toString('utf8'))
}
```
--------------------------------
### GET /orgs/{org}/repos
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/endpoint/README.md
Example of how to use the endpoint function to get a list of repositories for a specific organization. It demonstrates setting headers, path parameters, and query parameters.
```APIDOC
## GET /orgs/{org}/repos
### Description
Retrieves a list of repositories for a given GitHub organization. This endpoint can be used to fetch public or private repositories based on the organization's settings and the authenticated user's permissions.
### Method
GET
### Endpoint
/orgs/{org}/repos
### Parameters
#### Path Parameters
- **org** (string) - Required - The organization's login name (e.g., 'octokit').
#### Query Parameters
- **type** (string) - Optional - Specifies the type of repositories to retrieve (e.g., 'all', 'public', 'private', 'forks', 'sources'). Defaults to 'all'.
- **sort** (string) - Optional - Specifies the sort order of the repositories (e.g., 'created', 'updated', 'pushed', 'full_name').
- **direction** (string) - Optional - Specifies the direction of the sort ('asc' or 'desc').
- **per_page** (integer) - Optional - The number of results per page (max 100). Defaults to 30.
- **page** (integer) - Optional - Page number of the results to fetch.
#### Headers
- **authorization** (string) - Required - Authentication token for accessing private repositories or higher rate limits. Format: 'token YOUR_TOKEN'.
- **accept** (string) - Optional - Specifies the media type for the response. Defaults to 'application/vnd.github.v3+json'.
- **user-agent** (string) - Optional - Custom User-Agent string for the request. Defaults to 'octokit/endpoint.js vX.Y.Z'.
### Request Example
```javascript
const requestOptions = endpoint("GET /orgs/{org}/repos", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
});
```
### Response
#### Success Response (200)
- **repositories** (array) - An array of repository objects, each containing details about a repository.
- **repository** (object) - Contains details like `id`, `name`, `full_name`, `owner` (object), `private` (boolean), `html_url`, etc.
#### Response Example
```json
{
"method": "GET",
"url": "https://api.github.com/orgs/octokit/repos?type=private",
"headers": {
"accept": "application/vnd.github.v3+json",
"authorization": "token 0000000000000000000000000000000000000001",
"user-agent": "octokit/endpoint.js v1.2.3"
}
}
```
```
--------------------------------
### Perform HTTP GET Requests
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/node-fetch/README.md
Examples of fetching plain text/HTML or JSON data from a remote URL.
```javascript
// Fetch plain text or HTML
fetch('https://github.com/')
.then(res => res.text())
.then(body => console.log(body));
// Fetch JSON
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(json => console.log(json));
```
--------------------------------
### Creating Octokit Instances with Default Options
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/core/README.md
Demonstrates how to create a new Octokit class with predefined default options, simplifying instantiation and ensuring consistent configurations.
```javascript
const MyOctokit = Octokit.defaults({
auth: "personal-access-token123",
baseUrl: "https://github.acme-inc.com/api/v3",
userAgent: "my-app/v1.2.3",
});
const octokit1 = new MyOctokit();
const octokit2 = new MyOctokit();
```
--------------------------------
### Import RequestError in Node.js
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/request-error/README.md
Shows how to install and import the RequestError class in a Node.js environment using npm. It provides examples for both CommonJS and ES Module syntax.
```javascript
const { RequestError } = require("@octokit/request-error");
// or: import { RequestError } from "@octokit/request-error";
```
--------------------------------
### Using octokit.paginate.iterator() with string endpoint
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/plugin-paginate-rest/README.md
Iterate through paginated API responses using an async iterator. This example shows how to use it with a string endpoint like 'GET /repos/{owner}/{repo}/issues'.
```APIDOC
## `octokit.paginate.iterator()` with String Endpoint
### Description
This method allows you to iterate through paginated API responses using async iterators. It's useful when your runtime environment supports them (e.g., Node.js 10+ or modern browsers).
### Method
`octokit.paginate.iterator(path: string, parameters?: object)
### Endpoint
`GET /repos/{owner}/{repo}/issues` (example)
### Parameters
- **path** (string) - The API endpoint path, e.g., `"GET /repos/{owner}/{repo}/issues"`.
- **parameters** (object) - An object containing the parameters for the request, such as `owner`, `repo`, `since`, `per_page`, etc.
### Request Example
```js
const parameters = {
owner: "octocat",
repo: "hello-world",
since: "2010-10-01",
per_page: 100,
};
for await (const response of octokit.paginate.iterator(
"GET /repos/{owner}/{repo}/issues",
parameters
)) {
// do whatever you want with each response, break out of the loop, etc.
const issues = response.data;
console.log(`%d issues found`, issues.length);
}
```
### Response
Each iteration yields a response object containing the data for that page.
#### Success Response (200)
- **data** (array | object) - The data returned from the API, which might be an array of items or an object containing an items key (e.g., `items`, `check_runs`).
#### Response Example
```json
{
"data": [
{
"url": "https://api.github.com/repos/octocat/hello-world/issues/1347",
"html_url": "https://github.com/octocat/hello-world/issues/1347",
"number": 1347,
"state": "open",
"title": "Found some bugs in this code",
"body": "I'm having a problem with...",
"user": {
"login": "octocat",
"id": 583231,
"avatar_url": "https://avatars.githubusercontent.com/u/583231?v=4"
}
}
]
}
```
```
--------------------------------
### createTokenAuth with Different Token Types
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/auth-token/README.md
Provides examples of using createTokenAuth with various GitHub token types, including personal access tokens, OAuth tokens, installation tokens, and GitHub Actions tokens, showing the resulting authentication object structure.
```javascript
// Personal access token or OAuth access token
createTokenAuth("ghp_PersonalAccessToken01245678900000000");
// {
// type: 'token',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
// Installation access token or GitHub Action token
createTokenAuth("ghs_InstallallationOrActionToken00000000");
// {
// type: 'token',
// token: 'ghs_InstallallationOrActionToken00000000',
// tokenType: 'installation'
// }
// Installation access token or GitHub Action token
createTokenAuth("ghu_InstallationUserToServer000000000000");
// {
// type: 'token',
// token: 'ghu_InstallationUserToServer000000000000',
// tokenType: 'user-to-server'
// }
```
--------------------------------
### Instantiate MockAgent
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/MockAgent.md
Demonstrates how to initialize a MockAgent, either as a standalone instance or by wrapping an existing Agent.
```javascript
import { MockAgent } from 'undici';
const mockAgent = new MockAgent();
```
```javascript
import { Agent, MockAgent } from 'undici';
const agent = new Agent();
const mockAgent = new MockAgent({ agent });
```
--------------------------------
### Mock Request with Times Enabled (JavaScript)
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/MockPool.md
Mocks an HTTP GET request to '/foo' and limits its usage to a specific number of times using undici. The example demonstrates that the mock is used for the first two requests, but subsequent requests will not match the mock. Dependencies: undici.
```javascript
import { MockAgent, setGlobalDispatcher, request } from 'undici'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo',
method: 'GET'
}).reply(200, 'foo').times(2)
const result1 = await request('http://localhost:3000/foo')
// Will match and return mocked data
const result2 = await request('http://localhost:3000/foo')
// Will match and return mocked data
const result3 = await request('http://localhost:3000/foo')
// Will not match and make attempt a real request
```
--------------------------------
### Mock Request with Persist Enabled (JavaScript)
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/MockPool.md
Mocks an HTTP GET request to '/foo' and enables persistence using undici, meaning the mock will be reused for subsequent matching requests. The example shows multiple requests to the same endpoint all receiving the mocked response. Dependencies: undici.
```javascript
import { MockAgent, setGlobalDispatcher, request } from 'undici'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo',
method: 'GET'
}).reply(200, 'foo').persist()
const result1 = await request('http://localhost:3000/foo')
// Will match and return mocked data
const result2 = await request('http://localhost:3000/foo')
// Will match and return mocked data
// Etc
```
--------------------------------
### Perform HTTP Request with Dispatcher
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Dispatcher.md
This snippet demonstrates how to perform a basic HTTP GET request using the Dispatcher.request method. It includes setting up a mock server, making the request, and handling the response, including status code, headers, and body. The example utilizes Node.js 'http' and 'undici' modules.
```javascript
import { createServer } from 'http';
import { Client } from 'undici';
import { once } from 'events';
const server = createServer((request, response) => {
response.end('Hello, World!');
}).listen();
await once(server, 'listening');
const client = new Client(`http://localhost:${server.address().port}`);
try {
const { body, headers, statusCode, trailers } = await client.request({
path: '/',
method: 'GET'
});
console.log(`response received ${statusCode}`);
console.log('headers', headers);
body.setEncoding('utf8');
body.on('data', console.log);
body.on('end', () => {
console.log('trailers', trailers);
});
client.close();
server.close();
} catch (error) {
console.error(error);
}
```
--------------------------------
### Configuring Authentication
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/graphql/README.md
Explains how to set default headers for authentication or use advanced auth hooks like createAppAuth.
```javascript
const graphqlWithAuth = graphql.defaults({
headers: {
authorization: `token secret123`,
},
});
const { createAppAuth } = require("@octokit/auth-app");
const auth = createAppAuth({
id: process.env.APP_ID,
privateKey: process.env.PRIVATE_KEY,
installationId: 123,
});
const graphqlWithAuthApp = graphql.defaults({
request: {
hook: auth.hook,
},
});
```
--------------------------------
### Dispatch WebSocket Upgrade Request with Undici
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Dispatcher.md
This example demonstrates how to initiate a WebSocket upgrade request using the Undici client. It sets up a basic Node.js HTTP server that listens for upgrade events and responds with a WebSocket handshake. The client then sends a GET request with the 'websocket' upgrade header, and the server handles the upgrade, establishing a WebSocket connection.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end()
}).listen()
await once(server, 'listening')
server.on('upgrade', (request, socket, head) => {
console.log('Node.js Server - upgrade event')
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n')
socket.write('Upgrade: WebSocket\r\n')
socket.write('Connection: Upgrade\r\n')
socket.write('\r\n')
socket.end()
})
const client = new Client(`http://localhost:${server.address().port}`)
client.dispatch({
path: '/',
method: 'GET',
upgrade: 'websocket'
}, {
onConnect: () => {
console.log('Undici Client - onConnect')
},
onError: (error) => {
console.log('onError') // shouldn't print
},
onUpgrade: (statusCode, headers, socket) => {
console.log('Undici Client - onUpgrade')
console.log(`onUpgrade Headers: ${headers}`)
socket.on('data', buffer => {
console.log(buffer.toString('utf8'))
})
socket.on('end', () => {
client.close()
server.close()
})
socket.end()
}
})
```
--------------------------------
### Performing HTTP CONNECT Requests
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Dispatcher.md
Shows how to initiate a two-way communication channel using the HTTP CONNECT method. This example includes setting up a server that handles the CONNECT handshake and echoes data back to the client.
```javascript
import { createServer } from 'http';
import { Client } from 'undici';
import { once } from 'events';
const server = createServer((request, response) => {
throw Error('should never get here');
}).listen();
server.on('connect', (req, socket, head) => {
socket.write('HTTP/1.1 200 Connection established\r\n\r\n');
let data = head.toString();
socket.on('data', (buf) => { data += buf.toString(); });
socket.on('end', () => { socket.end(data); });
});
await once(server, 'listening');
const client = new Client(`http://localhost:${server.address().port}`);
try {
const { socket } = await client.connect({ path: '/' });
socket.on('data', d => { console.log(`Data received: ${d.toString()}`); });
socket.write('Body');
socket.end();
} catch (error) { }
```
--------------------------------
### Deno Deploy Action Input Parameters
Source: https://github.com/denoland/deployctl/blob/main/action/README.md
Overview of the available configuration inputs for the denoland/deployctl action, including project name, entrypoint, and file filtering options.
```yaml
- name: Deploy to Deno Deploy
uses: denoland/deployctl@v1
with:
project:
entrypoint:
root:
include:
exclude:
import-map:
```
--------------------------------
### Load and Configure node-fetch
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/node-fetch/README.md
Demonstrates how to import the module and optionally configure a custom Promise library.
```javascript
const fetch = require('node-fetch');
// Optional: Use a custom Promise library
const Bluebird = require('bluebird');
fetch.Promise = Bluebird;
```
--------------------------------
### Install is-plain-object via NPM
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/is-plain-object/README.md
Command to install the library as a dependency in your Node.js project.
```shell
npm install --save is-plain-object
```
--------------------------------
### Instantiate a MockPool with MockAgent
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/MockPool.md
Demonstrates how to initialize a MockAgent and retrieve a MockPool instance for a specific origin to begin intercepting requests.
```javascript
import { MockAgent } from 'undici'
const mockAgent = new MockAgent()
const mockPool = mockAgent.get('http://localhost:3000')
```
--------------------------------
### Validate CA Fingerprint Example
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Connector.md
An example demonstrating how to validate the CA fingerprint of a TLS certificate when establishing a connection.
```APIDOC
## Validate CA Fingerprint Example
### Description
This example shows how to use a custom connector to validate the CA fingerprint of the server's TLS certificate before completing the connection. This adds an extra layer of security by ensuring the certificate belongs to the expected Certificate Authority.
### Method
`Client` constructor with custom `connect` option.
### Endpoint
`https://localhost:3000` (example)
### Parameters
(See `buildConnector.BuildOptions` and `connector.Options` in the previous example)
### Request Example
```javascript
'use strict'
import { Client, buildConnector } from 'undici'
const caFingerprint = 'FO:OB:AR'
const connector = buildConnector({ rejectUnauthorized: false })
const client = new Client('https://localhost:3000', {
connect (opts, cb) {
connector(opts, (err, socket) => {
if (err) {
cb(err)
} else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) {
socket.destroy()
cb(new Error('Fingerprint does not match or malformed certificate'))
} else {
cb(null, socket)
}
})
}
})
client.request({
path: '/',
method: 'GET'
}, (err, data) => {
if (err) throw err
const bufs = []
data.body.on('data', (buf) => {
bufs.push(buf)
})
data.body.on('end', () => {
console.log(Buffer.concat(bufs).toString('utf8'))
client.close()
})
})
function getIssuerCertificate (socket) {
let certificate = socket.getPeerCertificate(true)
while (certificate && Object.keys(certificate).length > 0) {
// invalid certificate
if (certificate.issuerCertificate == null) {
return null
}
// We have reached the root certificate.
// In case of self-signed certificates, `issuerCertificate` may be a circular reference.
if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) {
break
}
// continue the loop
certificate = certificate.issuerCertificate
}
return certificate
}
```
### Response
#### Success Response (200)
- **body** (ReadableStream) - The response body.
#### Response Example
(Output depends on the server's response to the GET request)
```
--------------------------------
### Initialize Octokit with REST Endpoint Methods
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/plugin-rest-endpoint-methods/README.md
Demonstrates how to import and initialize the Octokit client with the REST endpoint methods plugin in both browser and Node.js environments.
```html
```
```javascript
const { Octokit } = require("@octokit/core");
const { restEndpointMethods } = require("@octokit/plugin-rest-endpoint-methods");
```
--------------------------------
### Install Undici via NPM
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/README.md
The command to install the Undici package into your Node.js project using the npm package manager.
```bash
npm i undici
```
--------------------------------
### Initialize Octokit with Pagination Plugin
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/plugin-paginate-rest/README.md
Shows how to import and initialize the Octokit client with the paginate-rest plugin in both browser and Node.js environments.
```html
```
```javascript
const { Octokit } = require("@octokit/core");
const {
paginateRest,
composePaginateRest,
} = require("@octokit/plugin-paginate-rest");
```
--------------------------------
### Running Tests and Building Docs
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/is-plain-object/README.md
Commands to execute the library's test suite or regenerate the documentation using verb.
```shell
npm install && npm test
npm install -g verbose/verb#dev verb-generate-readme && verb
```
--------------------------------
### Deployctl Command-Line Usage for Configuration
Source: https://context7.com/denoland/deployctl/llms.txt
Demonstrates command-line usage of deployctl for deployment, including specifying a custom configuration file, saving current arguments to a config file, and using environment variables for configuration.
```bash
# Use custom config file
deployctl deploy --config=deploy.json
# Save current args to config
deployctl deploy --project=my-project --entrypoint=main.ts --save-config
# Environment variables for configuration
export DENO_DEPLOY_TOKEN=ddp_xxxxxxxxxxxx
export DEPLOYCTL_CONFIG_FILE=./deploy.json
export DEPLOYCTL_ORGANIZATION=my-org
```
--------------------------------
### GET /foo Mocking
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/MockPool.md
Intercepts a GET request to /foo and returns a mocked response with specific headers and body content.
```APIDOC
## GET /foo
### Description
Intercepts a GET request to the specified path and returns a mocked response.
### Method
GET
### Endpoint
/foo
### Parameters
#### Path Parameters
- **path** (string) - Required - The path to intercept.
### Request Example
GET /foo
### Response
#### Success Response (200)
- **body** (string) - The mocked response body.
#### Response Example
"foo"
```
--------------------------------
### Defaults Configuration
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/core/README.md
Demonstrates how to create a new Octokit class with customized default options.
```APIDOC
## Defaults
You can create a new Octokit class with customized default options.
```js
const MyOctokit = Octokit.defaults({
auth: "personal-access-token123",
baseUrl: "https://github.acme-inc.com/api/v3",
userAgent: "my-app/v1.2.3",
});
const octokit1 = new MyOctokit();
const octokit2 = new MyOctokit();
```
If you pass additional options to your new constructor, the options will be merged shallowly.
```js
const MyOctokit = Octokit.defaults({
foo: {
opt1: 1,
},
});
const octokit = new MyOctokit({
foo: {
opt2: 1,
},
});
// options will be { foo: { opt2: 1 }}
```
If you need a deep or conditional merge, you can pass a function instead.
```js
const MyOctokit = Octokit.defaults((options) => {
return {
foo: Object.assign({}, options.foo, { opt2: 1 }),
};
});
const octokit = new MyOctokit({
foo: { opt2: 1 },
});
// options will be { foo: { opt1: 1, opt2: 1 }}
```
Be careful about mutating the `options` object in the `Octokit.defaults` callback, as it can have unforeseen consequences.
```
--------------------------------
### Deployctl Authentication Options
Source: https://context7.com/denoland/deployctl/llms.txt
Demonstrates different methods for authenticating with Deno Deploy using deployctl, including environment variables (recommended for CI/CD), command-line options, and interactive browser-based authentication.
```bash
# Using environment variable (recommended for CI/CD)
export DENO_DEPLOY_TOKEN=ddp_xxxxxxxxxxxx
deployctl deploy --project=my-project --entrypoint=main.ts
# Using command-line option
deployctl deploy --project=my-project --entrypoint=main.ts --token=ddp_xxxxxxxxxxxx
# Interactive authentication (opens browser)
# When no token is provided, deployctl will prompt for browser-based auth
deployctl deploy --project=my-project --entrypoint=main.ts
```
--------------------------------
### Install @octokit/endpoint.js in Node.js
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/endpoint/README.md
Installs the @octokit/endpoint.js library using npm for use in Node.js environments. This is the standard way to add the library as a project dependency.
```bash
npm install @octokit/endpoint
```
--------------------------------
### Install and Generate Random UUID
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/uuid/README.md
Demonstrates how to install the uuid package and generate a version 4 (random) UUID using both ES6 modules and CommonJS syntax.
```shell
npm install uuid
```
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4();
```
```javascript
const { v4: uuidv4 } = require('uuid');
uuidv4();
```
--------------------------------
### Perform HTTP Protocol Upgrade with Undici
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Dispatcher.md
Shows how to use the Dispatcher.upgrade method to initiate a protocol upgrade request. This example sets up a basic HTTP server that accepts upgrades and a client that initiates the handshake.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.statusCode = 101
response.setHeader('connection', 'upgrade')
response.setHeader('upgrade', request.headers.upgrade)
response.end()
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { headers, socket } = await client.upgrade({
path: '/',
})
socket.on('end', () => {
console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket
client.close()
server.close()
})
socket.end()
} catch (error) {
console.error(error)
client.close()
server.close()
}
```
--------------------------------
### Install and Import Deprecation in Node.js
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/deprecation/README.md
Demonstrates how to install the 'deprecation' package using npm and import the Deprecation class in a Node.js environment. Supports both CommonJS and ES Module syntax.
```javascript
const { Deprecation } = require("deprecation");
// or: import { Deprecation } from "deprecation";
```
--------------------------------
### JavaScript Array Example
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Dispatcher.md
This JavaScript code snippet demonstrates an example of an array, commonly used for storing collections of data. It is often utilized for representing headers or lists of items in web development contexts.
```javascript
[
'content-length', '123',
'content-type', 'text/plain',
'connection', 'keep-alive',
'host', 'mysite.com',
'accept', '*/*'
]
```
--------------------------------
### Extend Octokit with Plugins
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/@octokit/core/README.md
Demonstrates how to create and register custom plugins to add new methods and functionality to the Octokit instance.
```javascript
// index.js
const { Octokit } = require("@octokit/core")
const MyOctokit = Octokit.plugin(
require("./lib/my-plugin"),
require("octokit-plugin-example")
);
const octokit = new MyOctokit({ greeting: "Moin moin" });
octokit.helloWorld();
// lib/my-plugin.js
module.exports = (octokit, options = { greeting: "Hello" }) => {
octokit.hook.wrap("request", async (request, options) => {
const time = Date.now();
const response = await request(options);
console.log(`${options.method} ${options.url} – ${response.status} in ${Date.now() - time}ms`);
return response;
});
return {
helloWorld: () => console.log(`${options.greeting}, world!`)
}
};
```
--------------------------------
### ANY /api
Source: https://context7.com/denoland/deployctl/llms.txt
Execute raw HTTP requests against the Deno Deploy API for advanced management tasks.
```APIDOC
## ANY /api
### Description
Allows direct interaction with the Deno Deploy REST API using custom methods and payloads.
### Method
ANY (GET, POST, PUT, DELETE)
### Endpoint
deployctl api [path]
### Parameters
#### Query Parameters
- **method** (string) - Optional - HTTP method (default: GET).
- **body** (string) - Optional - JSON string for request body.
- **token** (string) - Optional - Custom authentication token.
### Request Example
deployctl api --method=POST --body='{"name": "my-project"}' organizations/org-id/projects
```
--------------------------------
### JavaScript WebIDL Type Conversion Example
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/webidl-conversions/README.md
Demonstrates how to use the 'webidl-conversions' package to convert JavaScript values to specific WebIDL types. The example shows converting a generic value to a 'boolean' and an 'unsigned long', mimicking the behavior of WebIDL operations.
```javascript
const conversions = require("webidl-conversions");
function doStuff(x, y) {
x = conversions["boolean"](x);
y = conversions["unsigned long"](y);
// actual algorithm code here
}
```
--------------------------------
### Add CommonJS Syntax Example to README in uuid (v8.0.0)
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/uuid/CHANGELOG.md
This update adds a clear example of using the uuid library with CommonJS syntax to the README file. This helps users who are working in CommonJS environments to quickly understand how to import and use the library.
```markdown
```javascript
const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
```
```
--------------------------------
### Instantiate Undici Client
Source: https://github.com/denoland/deployctl/blob/main/action/node_modules/undici/docs/api/Client.md
Demonstrates how to create a new Undici Client instance. Note that the client will not connect to the origin until a request or connection is explicitly triggered.
```javascript
'use strict'
import { Client } from 'undici'
const client = new Client('http://localhost:3000')
```