### Install @bufbuild/protobuf Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@bufbuild/protobuf/README.md Install the runtime library for protoc-gen-es. ```bash npm install @bufbuild/protobuf ``` -------------------------------- ### Basic example: tunnel.httpsOverHttp Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/tunnel/README.md Shows the minimal setup for creating an HTTPS-over-HTTP tunneling agent with tunnel.httpsOverHttp, specifying the proxy host and port, and using it with https.request. ```javascript var tunnel = require('tunnel'); var tunnelingAgent = tunnel.httpsOverHttp({ proxy: { host: 'localhost', port: 3128 } }); var req = https.request({ host: 'example.com', port: 443, agent: tunnelingAgent }); ``` -------------------------------- ### Install with component Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/isarray/README.md Installs the isarray package via component. ```bash $ component install juliangruber/isarray ``` -------------------------------- ### Installation command: npm install event-target-shim Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/event-target-shim/README.md Install the package via npm. After installation, use a bundler to include the library. ```bash npm install event-target-shim ``` -------------------------------- ### Install process-nextick-args Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/process-nextick-args/readme.md Install the process-nextick-args package via npm. ```bash npm install --save process-nextick-args ``` -------------------------------- ### Install @nodable/entities via npm Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@nodable/entities/README.md Install the package using npm. This is the standard installation command. ```bash npm install @nodable/entities ``` -------------------------------- ### Install is-fullwidth-code-point Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/is-fullwidth-code-point/readme.md Install the is-fullwidth-code-point package using npm. ```bash $ npm install is-fullwidth-code-point ``` -------------------------------- ### Install project dependencies Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@actions/http-client/README.md Install dependencies for the project. ```shell npm install ``` -------------------------------- ### Install Gulp and dependencies Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/typescript/README.md Install Gulp globally and install dev dependencies using npm ci. ```bash npm install -g gulp npm ci ``` -------------------------------- ### Install with npm Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/isarray/README.md Installs the isarray package via npm. ```bash $ npm install isarray ``` -------------------------------- ### Install xml-naming Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/xml-naming/README.md Installs the xml-naming package from npm. ```bash npm install xml-naming ``` -------------------------------- ### Get installation token Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/core/README.md Calls the auth() method to obtain an installation token for a specific installation. This method is provided by the current authentication strategy. ```javascript const { token } = await appOctokit.auth({ type: "installation", installationId: 123, }); ``` -------------------------------- ### Quick Start: Expression and Matcher Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/path-expression-matcher/README.md Shows how to create an Expression and Matcher, push path segments, and match the current path. Also demonstrates namespace support with the push method's third argument. ```javascript import { Expression, Matcher } from 'path-expression-matcher'; // Create expression (parse once, reuse many times) const expr = new Expression("root.users.user"); // Create matcher (tracks current path) const matcher = new Matcher(); matcher.push("root"); matcher.push("users"); matcher.push("user", { id: "123" }); // Match current path against expression if (matcher.matches(expr)) { console.log("Match found!"); console.log("Current path:", matcher.toString()); // "root.users.user" } // Namespace support const nsExpr = new Expression("soap::Envelope.soap::Body..ns::UserId"); matcher.push("Envelope", null, "soap"); matcher.push("Body", null, "soap"); matcher.push("UserId", null, "ns"); console.log(matcher.toString()); // "soap:Envelope.soap:Body.ns:UserId" ``` -------------------------------- ### Token type examples Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/auth-token/README.md Examples of createTokenAuth with different token types: personal access token (oauth), installation access token (installation), and user-to-server token (user-to-server). Each call returns an object with the token and its type. ```js // 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' // } ``` -------------------------------- ### Import Octokit in browser and Node Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/core/README.md Load @octokit/core in browsers via esm.sh or in Node.js after installing with npm install @octokit/core. The browser example uses a module script tag; the Node example uses an ES module import. ```html ``` ```js import { Octokit } from "@octokit/core"; ``` -------------------------------- ### Full example with virtual compiler host Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@typescript/vfs/README.md Complete example from the TypeScript Sandbox codebase showing how to set up a virtual compiler host, create a program, emit files, and access the AST. Uses CDN for lib files and lz-string for compression. ```ts import ts from "typescript" import tsvfs from "@typescript/vfs" import lzstring from "lz-string" const fsMap = await tsvfs.createDefaultMapFromCDN(compilerOptions, ts.version, true, ts, lzstring) fsMap.set("index.ts", "// main TypeScript file content") const system = tsvfs.createSystem(fsMap) const host = tsvfs.createVirtualCompilerHost(system, compilerOptions, ts) const program = ts.createProgram({ rootNames: [...fsMap.keys()], options: compilerOptions, host: host.compilerHost, }) // This will update the fsMap with new files // for the .d.ts and .js files program.emit() // Now I can look at the AST for the .ts file too const index = program.getSourceFile("index.ts") ``` -------------------------------- ### Command line example with output Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/minimist/README.md Example command and its output showing parsed arguments with -a and -b flags. ```bash $ node example/parse.js -a beep -b boop { _: [], a: 'beep', b: 'boop' } ``` -------------------------------- ### endpoint.merge() - Get defaulted endpoint options Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/endpoint/README.md Shows how to use endpoint.merge() to get the defaulted endpoint options without parsing them into request options. The example includes the returned object. ```javascript const myProjectEndpoint = endpoint.defaults({ baseUrl: "https://github-enterprise.acme-inc.com/api/v3", headers: { "user-agent": "myApp/1.2.3", }, org: "my-project", }); myProjectEndpoint.merge("GET /orgs/{org}/repos", { headers: { authorization: `token 0000000000000000000000000000000000000001`, }, org: "my-secret-project", type: "private", }); // { // baseUrl: 'https://github-enterprise.acme-inc.com/api/v3', // method: 'GET', // url: '/orgs/{org}/repos', // headers: { // accept: 'application/vnd.github.v3+json', // authorization: `token 0000000000000000000000000000000000000001`, // 'user-agent': 'myApp/1.2.3' // }, // org: 'my-secret-project', // type: 'private' // } ``` -------------------------------- ### Get response types from endpoint methods Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/types/README.md Shows how to get response types from endpoint methods using GetResponseTypeFromEndpointMethod and GetResponseDataTypeFromEndpointMethod. The example uses an Octokit instance and the issues.createLabel method. ```ts import { GetResponseTypeFromEndpointMethod, GetResponseDataTypeFromEndpointMethod, } from "@octokit/types"; import { Octokit } from "@octokit/rest"; const octokit = new Octokit(); type CreateLabelResponseType = GetResponseTypeFromEndpointMethod< typeof octokit.issues.createLabel >; type CreateLabelResponseDataType = GetResponseDataTypeFromEndpointMethod< typeof octokit.issues.createLabel >; ``` -------------------------------- ### Install @protobuf-ts/runtime with npm or yarn Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@protobuf-ts/runtime/README.md Install the runtime library using npm or yarn. Choose one package manager; both commands are equivalent. ```shell script # with npm: npm install @protobuf-ts/runtime # with yarn: yarn add @protobuf-ts/runtime ``` -------------------------------- ### Example: List organization repositories with endpoint() Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/endpoint/README.md Example for listing organization repositories. Passes a route string and parameters to endpoint() to generate request options. ```js const requestOptions = endpoint("GET /orgs/{org}/repos", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); ``` -------------------------------- ### Get command from shebang using shebangCommand Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/shebang-command/readme.md Require the module and call shebangCommand with a shebang string to get the command. The examples show that '#!/usr/bin/env node' returns 'node' and '#!/bin/bash' returns 'bash'. ```javascript const shebangCommand = require('shebang-command'); shebangCommand('#!/usr/bin/env node'); //=> 'node' shebangCommand('#!/bin/bash'); //=> 'bash' ``` -------------------------------- ### Example - EnvHttpProxyAgent instantiation Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md Example showing how to instantiate the EnvHttpProxyAgent. ```APIDOC ## EnvHttpProxyAgent instantiation ### Description Instantiates the EnvHttpProxyAgent. It will not do anything until registered as the agent to use with requests. ### Example ```js import { EnvHttpProxyAgent } from 'undici' const envHttpProxyAgent = new EnvHttpProxyAgent() ``` ``` -------------------------------- ### Get parameter and response data types for a REST API endpoint Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/types/README.md Shows how to use the Endpoints type to get parameter and response data types for a REST API endpoint. The example defines types for the GET /repos/{owner}/{repo} endpoint and uses them in an async function. ```ts import { Endpoints } from "@octokit/types"; type listUserReposParameters = Endpoints["GET /repos/{owner}/{repo}"]["parameters"]; type listUserReposResponse = Endpoints["GET /repos/{owner}/{repo}"]["response"]; async function listRepos( options: listUserReposParameters, ): listUserReposResponse["data"] { // ... } ``` -------------------------------- ### Example - Connect request with echo Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/Dispatcher.md Sets up an HTTP server that handles CONNECT, then uses client.connect() to establish a tunnel and echo data back. Logs received data and closes client and server. ```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) { } ``` -------------------------------- ### Matcher.toString() examples Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/path-expression-matcher/README.md Gets the path as a string. Optional separator and includeNamespace (default true) control output. ```javascript const path = matcher.toString(); // "root.ns:user.item" const path2 = matcher.toString('/'); // "root/ns:user/item" const path3 = matcher.toString('.', false); // "root.user.item" (no namespaces) ``` -------------------------------- ### Dispatcher - DispatchOptions and DispatchHandler Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/Dispatcher.md Documentation for the DispatchOptions and DispatchHandler parameters used with the dispatch method, including an example of dispatching a GET request. ```APIDOC ## DispatchOptions ### Description Options for dispatching a request via the `dispatch` method. ### Parameters - **origin** (`string | URL`) - Required - The origin of the request. - **path** (`string`) - Required - The path of the request. - **method** (`string`) - Required - The HTTP method. - **reset** (`boolean`) - Optional - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header, otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards. - **body** (`string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null`) - Optional - Default: `null` - The request body. - **headers** (`UndiciHeaders | string[]`) - Optional - Default: `null` - The request headers. - **query** (`Record | null`) - Optional - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead. - **idempotent** (`boolean`) - Optional - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed. - **blocking** (`boolean`) - Optional - Default: `false` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. - **upgrade** (`string | null`) - Optional - Default: `null` - Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. - **bodyTimeout** (`number | null`) - Optional - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. - **headersTimeout** (`number | null`) - Optional - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. - **throwOnError** (`boolean`) - Optional - Default: `false` - Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. - **expectContinue** (`boolean`) - Optional - Default: `false` - For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server. ## DispatchHandler ### Description Handler object for the `dispatch` method, containing callbacks for various stages of the request lifecycle. ### Callbacks - **onConnect** `(abort: () => void, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. - **onError** `(error: Error) => void` - Invoked when an error has occurred. May not throw. - **onUpgrade** `(statusCode: number, headers: Buffer[], socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`. - **onResponseStarted** `() => void` (optional) - Invoked when response is received, before headers have been read. - **onHeaders** `(statusCode: number, headers: Buffer[], resume: () => void, statusText: string) => boolean` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. - **onData** `(chunk: Buffer) => boolean` - Invoked when response payload data is received. Not required for `upgrade` requests. - **onComplete** `(trailers: Buffer[]) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests. - **onBodySent** `(chunk: string | Buffer | Uint8Array) => void` - Invoked when a body chunk is sent to the server. Not required. For a stream or iterable body this will be invoked for every chunk. For other body types, it will be invoked once after the body is sent. ## Example 1 - Dispatch GET request ### Description Example of dispatching a GET request using the `dispatch` method. ### Code ```js 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() } }) ``` ``` -------------------------------- ### Command line example with multiple flags and output Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/minimist/README.md Example command and its output showing parsing of multiple flags, numbers, and positional arguments. ```bash $ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz { _: ['foo', 'bar', 'baz'], x: 3, y: 4, n: 5, a: true, b: true, c: true, beep: 'boop' } ``` -------------------------------- ### GET /orgs/{org}/repos (alternative) Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/request/README.md Alternative example of using the request function by passing method and url as part of options. ```APIDOC ## [GET] /orgs/{org}/repos (alternative) ### Description Alternative way to call the request function by passing method and url as part of options. ### Method GET ### Endpoint /orgs/{org}/repos ### Parameters #### Path Parameters - **org** (string) - Required - The organization name. #### Query Parameters - **type** (string) - Optional - The type of repositories to list. #### Headers - **authorization** (string) - Required - The authentication token. ### Request Example ```js const result = await request({ method: "GET", url: "/orgs/{org}/repos", headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); ``` ``` -------------------------------- ### Setup and usage of deprecate() Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/util-deprecate/README.md Shows how to wrap a function with deprecate() to emit a deprecation warning when called. The setup exports a deprecated version of foo, and the users see section demonstrates that the warning is printed only on the first call. ```javascript // setup: exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); // users see: foo(); // foo() is deprecated, use bar() instead foo(); foo(); ``` -------------------------------- ### GET /orgs/{org}/repos Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/request/README.md Example of using the request function to list organization repositories via the GitHub REST API. ```APIDOC ## [GET] /orgs/{org}/repos ### Description List organization repositories. This is a REST API example using the request function. ### Method GET ### Endpoint /orgs/{org}/repos ### Parameters #### Path Parameters - **org** (string) - Required - The organization name. #### Query Parameters - **type** (string) - Optional - The type of repositories to list (e.g., private). #### Headers - **authorization** (string) - Required - The authentication token. ### Request Example ```js const result = await request("GET /orgs/{org}/repos", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); ``` ### Response #### Success Response (200) - **data** (array) - The list of repositories. #### Response Example ```js console.log(`${result.data.length} repos found.`); ``` ``` -------------------------------- ### Import and basic usage of glob, globSync, globStream, and Glob Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/glob/README.md Shows how to import the glob API and demonstrates the main functions: glob() for async, globSync() for sync, globStream() for streaming, and the Glob class for reusable walks. Includes examples of ignoring node_modules, using AbortSignal.timeout, multiple patterns, withFileTypes, stat, and custom ignore functions. ```javascript // load using import import { glob, globSync, globStream, globStreamSync, Glob } from 'glob' // or using commonjs, that's fine, too const { glob, globSync, globStream, globStreamSync, Glob, } = require('glob') // the main glob() and globSync() resolve/return array of filenames // all js files, but don't look in node_modules const jsfiles = await glob('**/*.js', { ignore: 'node_modules/**' }) // pass in a signal to cancel the glob walk const stopAfter100ms = await glob('**/*.css', { signal: AbortSignal.timeout(100), }) // multiple patterns supported as well const images = await glob(['css/*.{png,jpeg}', 'public/*.{png,jpeg}']) // but of course you can do that with the glob pattern also // the sync function is the same, just returns a string[] instead // of Promise const imagesAlt = globSync('{css,public}/*.{png,jpeg}') // you can also stream them, this is a Minipass stream const filesStream = globStream(['**/*.dat', 'logs/**/*.log']) // construct a Glob object if you wanna do it that way, which // allows for much faster walks if you have to look in the same // folder multiple times. const g = new Glob('**/foo', {}) // glob objects are async iterators, can also do globIterate() or // g.iterate(), same deal for await (const file of g) { console.log('found a foo file:', file) } // pass a glob as the glob options to reuse its settings and caches const g2 = new Glob('**/bar', g) // sync iteration works as well for (const file of g2) { console.log('found a bar file:', file) } // you can also pass withFileTypes: true to get Path objects // these are like a Dirent, but with some more added powers // check out http://npm.im/path-scurry for more info on their API const g3 = new Glob('**/baz/**', { withFileTypes: true }) g3.stream().on('data', path => { console.log( 'got a path object', path.fullpath(), path.isDirectory(), path.readdirSync().map(e => e.name), ) }) // if you use stat:true and withFileTypes, you can sort results // by things like modified time, filter by permission mode, etc. // All Stats fields will be available in that case. Slightly // slower, though. // For example: const results = await glob('**', { stat: true, withFileTypes: true }) const timeSortedFiles = results .sort((a, b) => a.mtimeMs - b.mtimeMs) .map(path => path.fullpath()) const groupReadableFiles = results .filter(path => path.mode & 0o040) .map(path => path.fullpath()) // custom ignores can be done like this, for example by saying // you'll ignore all markdown files, and all folders named 'docs' const customIgnoreResults = await glob('**', { ignore: { ignored: p => /\\.md$/.test(p.name), childrenIgnored: p => p.isNamed('docs'), }, }) // another fun use case, only return files with the same name as // their parent folder, plus either `.ts` or `.js` const folderNamedModules = await glob('**/*.{ts,js}', { ignore: { ignored: p => { const pp = p.parent return !(p.isNamed(pp.name + '.ts') || p.isNamed(pp.name + '.js')) }, }, }) // find all files edited in the last hour, to do this, we ignore // all of them that are more than an hour old const newFiles = await glob('**', { // need stat so we have mtime stat: true, // only want the files, not the dirs nodir: true, ignore: { ignored: p => { return new Date() - p.mtime > 60 * 60 * 1000 }, // could add similar childrenIgnored here as well, but // directory mtime is inconsistent across platforms, so // probably better not to, unless you know the system // tracks this reliably. }, }) ``` -------------------------------- ### parseArgs with tokens Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@pkgjs/parseargs/README.md Example of using parseArgs with tokens: true to get detailed parse information and reprocess tokens to support negated options. ```APIDOC ## parseArgs({ options, tokens: true }) ### Description Calls the `parseArgs` function from `node:util` with the `tokens` option set to `true` to obtain detailed parse information. The returned tokens can be used to implement custom behaviors such as negated options. ### Method Function call ### Endpoint `parseArgs({ options, tokens: true })` ### Parameters #### Configuration Object - **options** (object) - Required - An object mapping option names to their configuration, e.g., `{ type: 'boolean' }` or `{ type: 'string' }`. - **tokens** (boolean) - Required - Set to `true` to enable token output. ### Return Value Returns an object with properties: - **values** (object) - Parsed option values. - **tokens** (array) - Array of token objects with properties: - **kind** (string) - One of 'option', 'positional', or 'option-terminator'. - **index** (number) - Index of element in `args` containing token. - **name** (string) - Long name of option (for option tokens). - **rawName** (string) - How option used in args, like `-f` of `--foo`. - **value** (string | undefined) - Option value specified in args; undefined for boolean options. - **inlineValue** (boolean | undefined) - Whether option value specified inline, like `--foo=bar`. - **value** (string) - For positional tokens, the value of the positional argument. ### Example ```mjs import { parseArgs } from 'node:util'; const options = { 'color': { type: 'boolean' }, 'no-color': { type: 'boolean' }, 'logfile': { type: 'string' }, 'no-logfile': { type: 'boolean' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); // Reprocess the option tokens and overwrite the returned values. tokens .filter((token) => token.kind === 'option') .forEach((token) => { if (token.name.startsWith('no-')) { // Store foo:false for --no-foo const positiveName = token.name.slice(3); values[positiveName] = false; delete values[token.name]; } else { // Resave value so last one wins if both --foo and --no-foo. values[token.name] = token.value ?? true; } }); const color = values.color; const logfile = values.logfile ?? 'default.log'; console.log({ logfile, color }); ``` ```cjs const { parseArgs } = require('node:util'); const options = { 'color': { type: 'boolean' }, 'no-color': { type: 'boolean' }, 'logfile': { type: 'string' }, 'no-logfile': { type: 'boolean' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); // Reprocess the option tokens and overwrite the returned values. tokens .filter((token) => token.kind === 'option') .forEach((token) => { if (token.name.startsWith('no-')) { // Store foo:false for --no-foo const positiveName = token.name.slice(3); values[positiveName] = false; delete values[token.name]; } else { // Resave value so last one wins if both --foo and --no-foo. values[token.name] = token.value ?? true; } }); const color = values.color; const logfile = values.logfile ?? 'default.log'; console.log({ logfile, color }); ``` ### Example Output ```console $ node negate.js { logfile: 'default.log', color: undefined } $ node negate.js --no-logfile --no-color { logfile: false, color: false } $ node negate.js --logfile=test.log --color { logfile: 'test.log', color: true } $ node negate.js --no-logfile --logfile=test.log --color --no-color { logfile: 'test.log', color: false } ``` ``` -------------------------------- ### Build the project Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@actions/http-client/README.md Build the project. ```shell npm run build ``` -------------------------------- ### Color conversion examples for 16/256/truecolor Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/readme.md Shows how to use the color conversion functions from color-convert to convert between color spaces and get ANSI escape codes for foreground and background. ```javascript style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code ``` -------------------------------- ### Get raw escape code from styles.codes Map Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/ansi-styles/readme.md Retrieve raw escape codes from the styles.codes Map. The example shows that the close code for open code 36 is 39. ```js import styles from 'ansi-styles'; console.log(styles.codes.get(36)); //=> 39 ``` -------------------------------- ### Configure and use Jack with flags, options, and validation Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/jackspeak/README.md Complete example of configuring a Jack object with flags, options, numbers, lists, and flag lists, then parsing arguments, printing usage, and validating a config object. Shows how to define short flags, negations, defaults, hints, and how to combine short-form flags. The example also demonstrates the parse, usage, and validate methods. ```javascript import { jack } from 'jackspeak' const j = jack({ // Optional // This will be auto-generated from the descriptions if not supplied // top level usage line, printed by -h // will be auto-generated if not specified usage: 'foo [options] ', }) .heading('The best Foo that ever Fooed') .description( ` Executes all the files and interprets their output as TAP formatted test result data. To parse TAP data from stdin, specify "-" as a filename. `, ) // flags don't take a value, they're boolean on or off, and can be // turned off by prefixing with `--no-` // so this adds support for -b to mean --bail, or -B to mean --no-bail .flag({ flag: { // specify a short value if you like. this must be a single char short: 'f', // description is optional as well. description: `Make the flags wave`, // default value for flags is 'false', unless you change it default: true, }, 'no-flag': { // you can can always negate a flag with `--no-flag` // specifying a negate option will let you define a short // single-char option for negation. short: 'F', description: `Do not wave the flags`, }, }) // Options that take a value are specified with `opt()` .opt({ reporter: { short: 'R', description: 'the style of report to display', }, }) // if you want a number, say so, and jackspeak will enforce it .num({ jobs: { short: 'j', description: 'how many jobs to run in parallel', default: 1, }, }) // A list is an option that can be specified multiple times, // to expand into an array of all the settings. Normal opts // will just give you the last value specified. .optList({ 'node-arg': {}, }) // a flagList is an array of booleans, so `-ddd` is [true, true, true] // count the `true` values to treat it as a counter. .flagList({ debug: { short: 'd' }, }) // opts take a value, and is set to the string in the results // you can combine multiple short-form flags together, but // an opt will end the combine chain, posix-style. So, // -bofilename would be like --bail --output-file=filename .opt({ 'output-file': { short: 'o', // optional: make it -o in the help output insead of -o hint: 'file', description: `Send the raw output to the specified file.`, }, }) // now we can parse argv like this: const { values, positionals } = j.parse(process.argv) // or decide to show the usage banner console.log(j.usage()) // or validate an object config we got from somewhere else try { j.validate(someConfig) } catch (er) { console.error('someConfig is not valid!', er) } ``` -------------------------------- ### Install dependencies and run tests Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/normalize-path/README.md Installs dependencies and runs the unit test suite for the library. ```sh $ npm install && npm test ``` -------------------------------- ### MockPool.request example Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/MockPool.md Demonstrates using MockPool.request to send a mocked request. The intercept matches GET /foo and replies with 'foo'. The request returns statusCode 200 and a body that yields 'foo' when read. ```javascript import { MockAgent } from 'undici' const mockAgent = new MockAgent() const mockPool = mockAgent.get('http://localhost:3000') mockPool.intercept({ path: '/foo', method: 'GET', }).reply(200, 'foo') const { statusCode, body } = await mockPool.request({ origin: 'http://localhost:3000', path: '/foo', method: 'GET' }) console.log('response received', statusCode) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` -------------------------------- ### Example with opts['--'] option Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/minimist/README.md Shows how to use the '--' option to separate arguments before and after the '--' delimiter. ```javascript > require('./')('one two three -- four five --six'.split(' '), { '--': true }) { _: ['one', 'two', 'three'], '--': ['four', 'five', '--six'] } ``` -------------------------------- ### Basic Mocked Request with MockPool Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/MockPool.md Sets up a MockAgent with a global dispatcher, intercepts a GET request to /foo, and replies with 200 and 'foo'. The example then performs the request and logs the status code and body data. ```javascript import { MockAgent, setGlobalDispatcher, request } from 'undici' const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) // MockPool 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) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` -------------------------------- ### Example - Basic Proxy Fetch with global agent dispatcher Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md Example of using EnvHttpProxyAgent as the global dispatcher with fetch. ```APIDOC ## Basic Proxy Fetch with global agent dispatcher ### Description Demonstrates using the EnvHttpProxyAgent as the global dispatcher with the `fetch` API. ### Example ```js import { setGlobalDispatcher, fetch, EnvHttpProxyAgent } from 'undici' const envHttpProxyAgent = new EnvHttpProxyAgent() setGlobalDispatcher(envHttpProxyAgent) const { status, json } = await fetch('http://localhost:3000/foo') console.log('response received', status) // response received 200 const data = await json() // data { foo: "bar" } ``` ``` -------------------------------- ### Authenticate with a personal access token Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/request/README.md Sets the Authorization header directly with a personal access token using request.defaults. The token is a placeholder; replace it with a real token. The example then makes a GET request to /user. ```javascript const requestWithAuth = request.defaults({ headers: { authorization: "token 0000000000000000000000000000000000000001", }, }); const result = await requestWithAuth("GET /user"); ``` -------------------------------- ### Output of running example.js Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/balanced-match/README.md Expected output from running the example.js script with the three balanced() calls shown above. ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` -------------------------------- ### Quick Start: Basic request with undici Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/README.md Basic usage of the `request` function from the `undici` package. It sends a GET request to the specified URL and logs the status code, headers, body chunks, and trailers. ```javascript 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) ``` -------------------------------- ### Example - Request resolves before Client closes Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/Dispatcher.md Creates an HTTP server and a Client, sends a GET request, logs the response body, then closes the client and server. Demonstrates that close() waits for enqueued requests to complete. ```javascript import { createServer } from 'http' import { Client } from 'undici' import { once } from 'events' const server = createServer((request, response) => { response.end('undici') }).listen() await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const { body } = await client.request({ path: '/', method: 'GET' }) body.setEncoding('utf8') body.on('data', console.log) } catch (error) {} await client.close() console.log('Client closed') server.close() ``` -------------------------------- ### Basic usage example Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/minimist/README.md Shows how to require minimist and parse process.argv.slice(2), then log the result. ```javascript var argv = require('minimist')(process.argv.slice(2)); console.log(argv); ``` -------------------------------- ### Find out what permissions are enabled for a repository Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/auth-token/README.md Fetches the repository permissions for the authenticated token by calling the `GET /repos/{owner}/{repo}` endpoint and logging `response.data.permissions`. Note that the `permissions` key is not set when authenticated using 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", }); console.log(response.data.permissions); // { // admin: true, // push: true, // pull: true // } ``` -------------------------------- ### Basic LRUCache usage with options Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/lru-cache/README.md Shows how to import LRUCache, create a cache with common options (max, maxSize, ttl, dispose, fetchMethod), and use basic methods like set, get, and clear. Requires at least one of 'max', 'ttl', or 'maxSize'. Non-string keys are supported but must be the same object reference. ```js // hybrid module, either works import { LRUCache } from 'lru-cache' // or: const { LRUCache } = require('lru-cache') // or in minified form for web browsers: import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs' // At least one of 'max', 'ttl', or 'maxSize' is required, to prevent // unsafe unbounded storage. // // In most cases, it's best to specify a max for performance, so all // the required memory allocation is done up-front. // // All the other options are optional, see the sections below for // documentation on what each one does. Most of them can be // overridden for specific items in get()/set() const options = { max: 500, // for use with tracking overall storage size maxSize: 5000, sizeCalculation: (value, key) => { return 1 }, // for use when you need to clean up something when objects // are evicted from the cache dispose: (value, key) => { freeFromMemoryOrWhatever(value) }, // how long to live in ms ttl: 1000 * 60 * 5, // return stale items before removing from cache? allowStale: false, updateAgeOnGet: false, updateAgeOnHas: false, // async method to use for cache.fetch(), for // stale-while-revalidate type of behavior fetchMethod: async ( key, staleValue, { options, signal, context } ) => {}, } const cache = new LRUCache(options) cache.set('key', 'value') cache.get('key') // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.clear() // empty the cache ```