Merge pull request #2778 from github/update-v3.28.10-9856c48b1

Merge main into releases/v3
This commit is contained in:
Ian Lynagh 2025-02-21 16:09:01 +00:00 committed by GitHub
commit b56ba49b26
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
1455 changed files with 170429 additions and 4373 deletions

View file

@ -77,7 +77,7 @@ jobs:
setup-kotlin: 'true'
- uses: actions/setup-go@v5
with:
go-version: ~1.23.0
go-version: ~1.24.0
# to avoid potentially misleading autobuilder results where we expect it to download
# dependencies successfully, but they actually come from a warm cache
cache: false

View file

@ -77,7 +77,7 @@ jobs:
setup-kotlin: 'true'
- uses: actions/setup-go@v5
with:
go-version: ~1.23.0
go-version: ~1.24.0
# to avoid potentially misleading autobuilder results where we expect it to download
# dependencies successfully, but they actually come from a warm cache
cache: false

View file

@ -77,7 +77,7 @@ jobs:
setup-kotlin: 'true'
- uses: actions/setup-go@v5
with:
go-version: ~1.23.0
go-version: ~1.24.0
# to avoid potentially misleading autobuilder results where we expect it to download
# dependencies successfully, but they actually come from a warm cache
cache: false

View file

@ -46,7 +46,7 @@ jobs:
use-all-platform-bundle: 'false'
setup-kotlin: 'true'
- name: Set up Ruby
uses: ruby/setup-ruby@2654679fe7f7c29875c669398a8ec0791b8a64a1 # v1.215.0
uses: ruby/setup-ruby@32110d4e311bd8996b2a82bf2a43b714ccc91777 # v1.221.0
with:
ruby-version: 2.6
- name: Install Code Scanning integration

71
.github/workflows/__rust.yml generated vendored Normal file
View file

@ -0,0 +1,71 @@
# Warning: This file is generated automatically, and should not be modified.
# Instead, please modify the template in the pr-checks directory and run:
# (cd pr-checks; pip install ruamel.yaml@0.17.31 && python3 sync.py)
# to regenerate this file.
name: PR Check - Rust analysis
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GO111MODULE: auto
on:
push:
branches:
- main
- releases/v*
pull_request:
types:
- opened
- synchronize
- reopened
- ready_for_review
schedule:
- cron: '0 5 * * *'
workflow_dispatch: {}
jobs:
rust:
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
version: linked
- os: ubuntu-latest
version: default
- os: ubuntu-latest
version: nightly-latest
name: Rust analysis
permissions:
contents: read
security-events: read
timeout-minutes: 45
runs-on: ${{ matrix.os }}
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Prepare test
id: prepare-test
uses: ./.github/actions/prepare-test
with:
version: ${{ matrix.version }}
use-all-platform-bundle: 'false'
setup-kotlin: 'true'
- uses: ./../action/init
with:
languages: rust
tools: ${{ steps.prepare-test.outputs.tools-url }}
env:
CODEQL_ACTION_RUST_ANALYSIS: true
- uses: ./../action/analyze
id: analysis
with:
upload-database: false
- name: Check database
shell: bash
run: |
RUST_DB="${{ fromJson(steps.analysis.outputs.db-locations).rust }}"
if [[ ! -d "$RUST_DB" ]]; then
echo "Did not create a database for Rust."
exit 1
fi
env:
CODEQL_ACTION_TEST_MODE: true

View file

@ -168,7 +168,7 @@ jobs:
--draft
- name: Generate token
uses: actions/create-github-app-token@136412a57a7081aa63c935a2cc2918f76c34f514
uses: actions/create-github-app-token@0d564482f06ca65fa9e77e2510873638c82206f2
id: app-token
with:
app-id: ${{ vars.AUTOMATION_APP_ID }}

View file

@ -124,7 +124,7 @@ jobs:
pull-requests: write # needed to create pull request
steps:
- name: Generate token
uses: actions/create-github-app-token@136412a57a7081aa63c935a2cc2918f76c34f514
uses: actions/create-github-app-token@0d564482f06ca65fa9e77e2510873638c82206f2
id: app-token
with:
app-id: ${{ vars.AUTOMATION_APP_ID }}

View file

@ -16,5 +16,5 @@ repos:
name: Synchronize PR check workflows
files: ^.github/workflows/__.*\.yml$|^pr-checks
language: system
entry: python3 pr-checks/sync.py
entry: pr-checks/sync.sh
pass_filenames: false

View file

@ -2,6 +2,11 @@
See the [releases page](https://github.com/github/codeql-action/releases) for the relevant changes to the CodeQL CLI and language packs.
## 3.28.10 - 21 Feb 2025
- Update default CodeQL bundle version to 2.20.5. [#2772](https://github.com/github/codeql-action/pull/2772)
- Address an issue where the CodeQL Bundle would occasionally fail to decompress on macOS. [#2768](https://github.com/github/codeql-action/pull/2768)
## 3.28.9 - 07 Feb 2025
- Update default CodeQL bundle version to 2.20.4. [#2753](https://github.com/github/codeql-action/pull/2753)

10
justfile Normal file
View file

@ -0,0 +1,10 @@
# Sync generated files (javascript and PR checks)
sync: build update-pr-checks
# Perform all necessary steps to update the PR checks
update-pr-checks:
pr-checks/sync.sh
# Transpile typescript code into javascript
build:
npm run build

View file

@ -60,7 +60,7 @@ async function runWrapper() {
if (config !== undefined) {
const codeql = await (0, codeql_1.getCodeQL)(config.codeQLCmd);
const version = await codeql.getVersion();
await (0, logging_1.withGroup)("Uploading combined SARIF debug artifact", () => debugArtifacts.uploadCombinedSarifArtifacts(logger, config.gitHubVersion.type, version.version));
await debugArtifacts.uploadCombinedSarifArtifacts(logger, config.gitHubVersion.type, version.version);
}
}
}

View file

@ -1 +1 @@
{"version":3,"file":"analyze-action-post.js","sourceRoot":"","sources":["../src/analyze-action-post.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;GAIG;AACH,oDAAsC;AAEtC,4DAA8C;AAC9C,6CAAgD;AAChD,qCAAqC;AACrC,iDAA2C;AAC3C,kEAAoD;AACpD,+CAAuC;AACvC,uCAAwD;AACxD,iCAAoE;AAEpE,KAAK,UAAU,UAAU;IACvB,IAAI,CAAC;QACH,WAAW,CAAC,aAAa,EAAE,CAAC;QAC5B,MAAM,MAAM,GAAG,IAAA,0BAAgB,GAAE,CAAC;QAClC,MAAM,aAAa,GAAG,MAAM,IAAA,6BAAgB,GAAE,CAAC;QAC/C,IAAA,gCAAyB,EAAC,aAAa,EAAE,MAAM,CAAC,CAAC;QAEjD,kFAAkF;QAClF,wFAAwF;QACxF,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAM,CAAC,mBAAmB,CAAC,KAAK,MAAM,EAAE,CAAC;YACvD,MAAM,MAAM,GAAG,MAAM,IAAA,wBAAS,EAC5B,WAAW,CAAC,qBAA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MAAM,GAAG,MAAM,IAAA,wBAAS,EAC5B,WAAW,CAAC,qBAAqB,EAAE,EACnC,MAAM,CACP,CAAC;YACF,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;gBACzB,MAAM,MAAM,GAAG,MAAM,IAAA,kBAAS,EAAC,MAAM,CAAC,SAAS,CAAC,CAAC;gBACjD,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,UAAU,EAAE,CAAC;gBAC1C,MAAM,cAAc,CAAC,4BAA4B,CAC/C,MAAM,EACN,MAAM,CAAC,aAAa,CAAC,IAAI,EACzB,OAAO,CAAC,OAAO,CAChB,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,SAAS,CACZ,oCAAoC,IAAA,sBAAe,EAAC,KAAK,CAAC,EAAE,CAC7D,CAAC;IACJ,CAAC;AACH,CAAC;AAED,KAAK,UAAU,EAAE,CAAC"}

4
lib/analyze.js generated
View file

@ -55,6 +55,7 @@ const api_client_1 = require("./api-client");
const autobuild_1 = require("./autobuild");
const codeql_1 = require("./codeql");
const diagnostics_1 = require("./diagnostics");
const diff_filtering_utils_1 = require("./diff-filtering-utils");
const environment_1 = require("./environment");
const feature_flags_1 = require("./feature-flags");
const languages_1 = require("./languages");
@ -368,6 +369,9 @@ extensions:
const extensionFilePath = path.join(diffRangeDir, "pr-diff-range.yml");
fs.writeFileSync(extensionFilePath, extensionContents);
logger.debug(`Wrote pr-diff-range extension pack to ${extensionFilePath}:\n${extensionContents}`);
// Write the diff ranges to a JSON file, for action-side alert filtering by the
// upload-lib module.
(0, diff_filtering_utils_1.writeDiffRangesJsonFile)(logger, ranges);
return diffRangeDir;
}
// Runs queries and creates sarif files in the given folder

File diff suppressed because one or more lines are too long

38
lib/debug-artifacts.js generated
View file

@ -66,26 +66,28 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion
const tempDir = (0, actions_util_1.getTemporaryDirectory)();
// Upload Actions SARIF artifacts for debugging when environment variable is set
if (process.env["CODEQL_ACTION_DEBUG_COMBINED_SARIF"] === "true") {
logger.info("Uploading available combined SARIF files as Actions debugging artifact...");
const baseTempDir = path.resolve(tempDir, "combined-sarif");
const toUpload = [];
if (fs.existsSync(baseTempDir)) {
const outputDirs = fs.readdirSync(baseTempDir);
for (const outputDir of outputDirs) {
const sarifFiles = fs
.readdirSync(path.resolve(baseTempDir, outputDir))
.filter((f) => f.endsWith(".sarif"));
for (const sarifFile of sarifFiles) {
toUpload.push(path.resolve(baseTempDir, outputDir, sarifFile));
await (0, logging_1.withGroup)("Uploading combined SARIF debug artifact", async () => {
logger.info("Uploading available combined SARIF files as Actions debugging artifact...");
const baseTempDir = path.resolve(tempDir, "combined-sarif");
const toUpload = [];
if (fs.existsSync(baseTempDir)) {
const outputDirs = fs.readdirSync(baseTempDir);
for (const outputDir of outputDirs) {
const sarifFiles = fs
.readdirSync(path.resolve(baseTempDir, outputDir))
.filter((f) => f.endsWith(".sarif"));
for (const sarifFile of sarifFiles) {
toUpload.push(path.resolve(baseTempDir, outputDir, sarifFile));
}
}
}
}
try {
await uploadDebugArtifacts(logger, toUpload, baseTempDir, "combined-sarif-artifacts", gitHubVariant, codeQlVersion);
}
catch (e) {
logger.warning(`Failed to upload combined SARIF files as Actions debugging artifact. Reason: ${(0, util_1.getErrorMessage)(e)}`);
}
try {
await uploadDebugArtifacts(logger, toUpload, baseTempDir, "combined-sarif-artifacts", gitHubVariant, codeQlVersion);
}
catch (e) {
logger.warning(`Failed to upload combined SARIF files as Actions debugging artifact. Reason: ${(0, util_1.getErrorMessage)(e)}`);
}
});
}
}
/**

File diff suppressed because one or more lines are too long

View file

@ -1,6 +1,6 @@
{
"bundleVersion": "codeql-bundle-v2.20.4",
"cliVersion": "2.20.4",
"priorBundleVersion": "codeql-bundle-v2.20.3",
"priorCliVersion": "2.20.3"
"bundleVersion": "codeql-bundle-v2.20.5",
"cliVersion": "2.20.5",
"priorBundleVersion": "codeql-bundle-v2.20.4",
"priorCliVersion": "2.20.4"
}

60
lib/diff-filtering-utils.js generated Normal file
View file

@ -0,0 +1,60 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeDiffRangesJsonFile = writeDiffRangesJsonFile;
exports.readDiffRangesJsonFile = readDiffRangesJsonFile;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const actionsUtil = __importStar(require("./actions-util"));
function getDiffRangesJsonFilePath() {
return path.join(actionsUtil.getTemporaryDirectory(), "pr-diff-range.json");
}
function writeDiffRangesJsonFile(logger, ranges) {
const jsonContents = JSON.stringify(ranges, null, 2);
const jsonFilePath = getDiffRangesJsonFilePath();
fs.writeFileSync(jsonFilePath, jsonContents);
logger.debug(`Wrote pr-diff-range JSON file to ${jsonFilePath}:\n${jsonContents}`);
}
function readDiffRangesJsonFile(logger) {
const jsonFilePath = getDiffRangesJsonFilePath();
if (!fs.existsSync(jsonFilePath)) {
logger.debug(`Diff ranges JSON file does not exist at ${jsonFilePath}`);
return undefined;
}
const jsonContents = fs.readFileSync(jsonFilePath, "utf8");
logger.debug(`Read pr-diff-range JSON file from ${jsonFilePath}:\n${jsonContents}`);
return JSON.parse(jsonContents);
}
//# sourceMappingURL=diff-filtering-utils.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"diff-filtering-utils.js","sourceRoot":"","sources":["../src/diff-filtering-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,0DAUC;AAED,wDAaC;AAzCD,uCAAyB;AACzB,2CAA6B;AAE7B,4DAA8C;AAS9C,SAAS,yBAAyB;IAChC,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,qBAAqB,EAAE,EAAE,oBAAoB,CAAC,CAAC;AAC9E,CAAC;AAED,SAAgB,uBAAuB,CACrC,MAAc,EACd,MAAwB;IAExB,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACrD,MAAM,YAAY,GAAG,yBAAyB,EAAE,CAAC;IACjD,EAAE,CAAC,aAAa,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;IAC7C,MAAM,CAAC,KAAK,CACV,oCAAoC,YAAY,MAAM,YAAY,EAAE,CACrE,CAAC;AACJ,CAAC;AAED,SAAgB,sBAAsB,CACpC,MAAc;IAEd,MAAM,YAAY,GAAG,yBAAyB,EAAE,CAAC;IACjD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QACjC,MAAM,CAAC,KAAK,CAAC,2CAA2C,YAAY,EAAE,CAAC,CAAC;QACxE,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,YAAY,GAAG,EAAE,CAAC,YAAY,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IAC3D,MAAM,CAAC,KAAK,CACV,qCAAqC,YAAY,MAAM,YAAY,EAAE,CACtE,CAAC;IACF,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAqB,CAAC;AACtD,CAAC"}

6
lib/feature-flags.js generated
View file

@ -68,6 +68,7 @@ var Feature;
Feature["ExtractToToolcache"] = "extract_to_toolcache";
Feature["PythonDefaultIsToNotExtractStdlib"] = "python_default_is_to_not_extract_stdlib";
Feature["QaTelemetryEnabled"] = "qa_telemetry_enabled";
Feature["RustAnalysis"] = "rust_analysis";
Feature["ZstdBundleStreamingExtraction"] = "zstd_bundle_streaming_extraction";
})(Feature || (exports.Feature = Feature = {}));
exports.featureConfig = {
@ -132,6 +133,11 @@ exports.featureConfig = {
minimumVersion: undefined,
toolsFeature: tools_features_1.ToolsFeature.PythonDefaultIsToNotExtractStdlib,
},
[Feature.RustAnalysis]: {
defaultValue: false,
envVar: "CODEQL_ACTION_RUST_ANALYSIS",
minimumVersion: "2.19.3",
},
[Feature.QaTelemetryEnabled]: {
defaultValue: false,
envVar: "CODEQL_ACTION_QA_TELEMETRY",

File diff suppressed because one or more lines are too long

21
lib/init-action.js generated
View file

@ -37,6 +37,7 @@ const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const core = __importStar(require("@actions/core"));
const io = __importStar(require("@actions/io"));
const semver = __importStar(require("semver"));
const uuid_1 = require("uuid");
const actions_util_1 = require("./actions-util");
const api_client_1 = require("./api-client");
@ -345,6 +346,26 @@ async function run() {
logger.info(`Setting C++ build-mode: none to ${value}`);
core.exportVariable(bmnVar, value);
}
// Set CODEQL_ENABLE_EXPERIMENTAL_FEATURES for rust
if (config.languages.includes(languages_1.Language.rust)) {
const feat = feature_flags_1.Feature.RustAnalysis;
const minVer = feature_flags_1.featureConfig[feat].minimumVersion;
const envVar = "CODEQL_ENABLE_EXPERIMENTAL_FEATURES";
// if in default setup, it means the feature flag was on when rust was enabled
// if the feature flag gets turned off, let's not have rust analysis throwing a configuration error
// in that case rust analysis will be disabled only when default setup is refreshed
if ((0, actions_util_1.isDefaultSetup)() || (await features.getValue(feat, codeql))) {
core.exportVariable(envVar, "true");
}
if (process.env[envVar] !== "true") {
throw new util_1.ConfigurationError(`Experimental and not officially supported Rust analysis requires setting ${envVar}=true in the environment`);
}
const actualVer = (await codeql.getVersion()).version;
if (semver.lt(actualVer, minVer)) {
throw new util_1.ConfigurationError(`Experimental rust analysis is supported by CodeQL CLI version ${minVer} or higher, but found version ${actualVer}`);
}
logger.info("Experimental rust analysis enabled");
}
// Restore dependency cache(s), if they exist.
if ((0, caching_utils_1.shouldRestoreCache)(config.dependencyCachingEnabled)) {
await (0, dependency_caching_1.downloadDependencyCaches)(config.languages, logger);

File diff suppressed because one or more lines are too long

11
lib/tar.js generated
View file

@ -143,7 +143,16 @@ async function extractTarZst(tar, dest, tarVersion, logger) {
: ""}`);
try {
// Initialize args
const args = ["-x", "--zstd"];
//
// `--ignore-zeros` means that trailing zero bytes at the end of an archive will be read
// by `tar` in case a further concatenated archive follows. Otherwise when a tarball built
// by GNU tar, which writes many trailing zeroes, is read by BSD tar, which expects less, then
// BSD tar can hang up the pipe to its filter program early, and if that program is `zstd`
// then it will try to write the remaining zeroes, get an EPIPE error because `tar` has closed
// its end of the pipe, return 1, and `tar` will pass the error along.
//
// See also https://github.com/facebook/zstd/issues/4294
const args = ["-x", "--zstd", "--ignore-zeros"];
if (tarVersion.type === "gnu") {
// Suppress warnings when using GNU tar to extract archives created by BSD tar
args.push("--warning=no-unknown-keyword");

File diff suppressed because one or more lines are too long

41
lib/upload-lib.js generated
View file

@ -58,6 +58,7 @@ const api = __importStar(require("./api-client"));
const api_client_1 = require("./api-client");
const codeql_1 = require("./codeql");
const config_utils_1 = require("./config-utils");
const diff_filtering_utils_1 = require("./diff-filtering-utils");
const environment_1 = require("./environment");
const fingerprints = __importStar(require("./fingerprints"));
const gitUtils = __importStar(require("./git-utils"));
@ -412,6 +413,7 @@ async function uploadFiles(sarifPath, checkoutPath, category, features, logger)
validateSarifFileSchema(file, logger);
}
let sarif = await combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, logger);
sarif = filterAlertsByDiffRange(logger, sarif);
sarif = await fingerprints.addFingerprints(sarif, checkoutPath, logger);
const analysisKey = await api.getAnalysisKey();
const environment = actionsUtil.getRequiredInput("matrix");
@ -607,4 +609,43 @@ class InvalidSarifUploadError extends Error {
}
}
exports.InvalidSarifUploadError = InvalidSarifUploadError;
function filterAlertsByDiffRange(logger, sarif) {
const diffRanges = (0, diff_filtering_utils_1.readDiffRangesJsonFile)(logger);
if (!diffRanges?.length) {
return sarif;
}
const checkoutPath = actionsUtil.getRequiredInput("checkout_path");
for (const run of sarif.runs) {
if (run.results) {
run.results = run.results.filter((result) => {
const locations = [
...(result.locations || []).map((loc) => loc.physicalLocation),
...(result.relatedLocations || []).map((loc) => loc.physicalLocation),
];
return locations.some((physicalLocation) => {
const locationUri = physicalLocation?.artifactLocation?.uri;
const locationStartLine = physicalLocation?.region?.startLine;
if (!locationUri || locationStartLine === undefined) {
return false;
}
// CodeQL always uses forward slashes as the path separator, so on Windows we
// need to replace any backslashes with forward slashes.
const locationPath = path
.join(checkoutPath, locationUri)
.replaceAll(path.sep, "/");
// Alert filtering here replicates the same behavior as the restrictAlertsTo
// extensible predicate in CodeQL. See the restrictAlertsTo documentation
// https://codeql.github.com/codeql-standard-libraries/csharp/codeql/util/AlertFiltering.qll/predicate.AlertFiltering$restrictAlertsTo.3.html
// for more details, such as why the filtering applies only to the first line
// of an alert location.
return diffRanges.some((range) => range.path === locationPath &&
((range.startLine <= locationStartLine &&
range.endLine >= locationStartLine) ||
(range.startLine === 0 && range.endLine === 0)));
});
});
}
}
return sarif;
}
//# sourceMappingURL=upload-lib.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1129
node_modules/.package-lock.json generated vendored

File diff suppressed because it is too large Load diff

View file

@ -213,7 +213,7 @@ function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsAr
};
const response = yield twirpClient.GetCacheEntryDownloadURL(request);
if (!response.ok) {
core.warning(`Cache not found for keys: ${keys.join(', ')}`);
core.debug(`Cache not found for keys: ${keys.join(', ')}`);
return undefined;
}
core.info(`Cache hit for: ${request.key}`);

File diff suppressed because one or more lines are too long

View file

@ -5,7 +5,6 @@ import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
import { CacheEntry } from "../../entities/v1/cacheentry";
import { CacheMetadata } from "../../entities/v1/cachemetadata";
/**
* @generated from protobuf message github.actions.results.api.v1.CreateCacheEntryRequest
@ -139,118 +138,6 @@ export interface GetCacheEntryDownloadURLResponse {
*/
matchedKey: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.DeleteCacheEntryRequest
*/
export interface DeleteCacheEntryRequest {
/**
* Scope and other metadata for the cache entry
*
* @generated from protobuf field: github.actions.results.entities.v1.CacheMetadata metadata = 1;
*/
metadata?: CacheMetadata;
/**
* An explicit key for a cache entry
*
* @generated from protobuf field: string key = 2;
*/
key: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.DeleteCacheEntryResponse
*/
export interface DeleteCacheEntryResponse {
/**
* @generated from protobuf field: bool ok = 1;
*/
ok: boolean;
/**
* Cache entry database ID
*
* @generated from protobuf field: int64 entry_id = 2;
*/
entryId: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.ListCacheEntriesRequest
*/
export interface ListCacheEntriesRequest {
/**
* Scope and other metadata for the cache entry
*
* @generated from protobuf field: github.actions.results.entities.v1.CacheMetadata metadata = 1;
*/
metadata?: CacheMetadata;
/**
* An explicit key for a cache entry
*
* @generated from protobuf field: string key = 2;
*/
key: string;
/**
* Restore keys used for prefix searching
*
* @generated from protobuf field: repeated string restore_keys = 3;
*/
restoreKeys: string[];
}
/**
* @generated from protobuf message github.actions.results.api.v1.ListCacheEntriesResponse
*/
export interface ListCacheEntriesResponse {
/**
* Cache entries in the defined scope
*
* @generated from protobuf field: repeated github.actions.results.entities.v1.CacheEntry entries = 1;
*/
entries: CacheEntry[];
}
/**
* @generated from protobuf message github.actions.results.api.v1.LookupCacheEntryRequest
*/
export interface LookupCacheEntryRequest {
/**
* Scope and other metadata for the cache entry
*
* @generated from protobuf field: github.actions.results.entities.v1.CacheMetadata metadata = 1;
*/
metadata?: CacheMetadata;
/**
* An explicit key for a cache entry
*
* @generated from protobuf field: string key = 2;
*/
key: string;
/**
* Restore keys used for prefix searching
*
* @generated from protobuf field: repeated string restore_keys = 3;
*/
restoreKeys: string[];
/**
* Hash of the compression tool, runner OS and paths cached
*
* @generated from protobuf field: string version = 4;
*/
version: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.LookupCacheEntryResponse
*/
export interface LookupCacheEntryResponse {
/**
* Indicates whether the cache entry exists or not
*
* @generated from protobuf field: bool exists = 1;
*/
exists: boolean;
/**
* Matched cache entry metadata
*
* @generated from protobuf field: github.actions.results.entities.v1.CacheEntry entry = 2;
*/
entry?: CacheEntry;
}
declare class CreateCacheEntryRequest$Type extends MessageType<CreateCacheEntryRequest> {
constructor();
create(value?: PartialMessage<CreateCacheEntryRequest>): CreateCacheEntryRequest;
@ -311,66 +198,6 @@ declare class GetCacheEntryDownloadURLResponse$Type extends MessageType<GetCache
* @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLResponse
*/
export declare const GetCacheEntryDownloadURLResponse: GetCacheEntryDownloadURLResponse$Type;
declare class DeleteCacheEntryRequest$Type extends MessageType<DeleteCacheEntryRequest> {
constructor();
create(value?: PartialMessage<DeleteCacheEntryRequest>): DeleteCacheEntryRequest;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: DeleteCacheEntryRequest): DeleteCacheEntryRequest;
internalBinaryWrite(message: DeleteCacheEntryRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.DeleteCacheEntryRequest
*/
export declare const DeleteCacheEntryRequest: DeleteCacheEntryRequest$Type;
declare class DeleteCacheEntryResponse$Type extends MessageType<DeleteCacheEntryResponse> {
constructor();
create(value?: PartialMessage<DeleteCacheEntryResponse>): DeleteCacheEntryResponse;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: DeleteCacheEntryResponse): DeleteCacheEntryResponse;
internalBinaryWrite(message: DeleteCacheEntryResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.DeleteCacheEntryResponse
*/
export declare const DeleteCacheEntryResponse: DeleteCacheEntryResponse$Type;
declare class ListCacheEntriesRequest$Type extends MessageType<ListCacheEntriesRequest> {
constructor();
create(value?: PartialMessage<ListCacheEntriesRequest>): ListCacheEntriesRequest;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ListCacheEntriesRequest): ListCacheEntriesRequest;
internalBinaryWrite(message: ListCacheEntriesRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.ListCacheEntriesRequest
*/
export declare const ListCacheEntriesRequest: ListCacheEntriesRequest$Type;
declare class ListCacheEntriesResponse$Type extends MessageType<ListCacheEntriesResponse> {
constructor();
create(value?: PartialMessage<ListCacheEntriesResponse>): ListCacheEntriesResponse;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ListCacheEntriesResponse): ListCacheEntriesResponse;
internalBinaryWrite(message: ListCacheEntriesResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.ListCacheEntriesResponse
*/
export declare const ListCacheEntriesResponse: ListCacheEntriesResponse$Type;
declare class LookupCacheEntryRequest$Type extends MessageType<LookupCacheEntryRequest> {
constructor();
create(value?: PartialMessage<LookupCacheEntryRequest>): LookupCacheEntryRequest;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: LookupCacheEntryRequest): LookupCacheEntryRequest;
internalBinaryWrite(message: LookupCacheEntryRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.LookupCacheEntryRequest
*/
export declare const LookupCacheEntryRequest: LookupCacheEntryRequest$Type;
declare class LookupCacheEntryResponse$Type extends MessageType<LookupCacheEntryResponse> {
constructor();
create(value?: PartialMessage<LookupCacheEntryResponse>): LookupCacheEntryResponse;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: LookupCacheEntryResponse): LookupCacheEntryResponse;
internalBinaryWrite(message: LookupCacheEntryResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.LookupCacheEntryResponse
*/
export declare const LookupCacheEntryResponse: LookupCacheEntryResponse$Type;
/**
* @generated ServiceType for protobuf service github.actions.results.api.v1.CacheService
*/

View file

@ -1,6 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheService = exports.LookupCacheEntryResponse = exports.LookupCacheEntryRequest = exports.ListCacheEntriesResponse = exports.ListCacheEntriesRequest = exports.DeleteCacheEntryResponse = exports.DeleteCacheEntryRequest = exports.GetCacheEntryDownloadURLResponse = exports.GetCacheEntryDownloadURLRequest = exports.FinalizeCacheEntryUploadResponse = exports.FinalizeCacheEntryUploadRequest = exports.CreateCacheEntryResponse = exports.CreateCacheEntryRequest = void 0;
exports.CacheService = exports.GetCacheEntryDownloadURLResponse = exports.GetCacheEntryDownloadURLRequest = exports.FinalizeCacheEntryUploadResponse = exports.FinalizeCacheEntryUploadRequest = exports.CreateCacheEntryResponse = exports.CreateCacheEntryRequest = void 0;
// @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies
// @generated from protobuf file "results/api/v1/cache.proto" (package "github.actions.results.api.v1", syntax proto3)
// tslint:disable
@ -10,7 +10,6 @@ const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const runtime_4 = require("@protobuf-ts/runtime");
const runtime_5 = require("@protobuf-ts/runtime");
const cacheentry_1 = require("../../entities/v1/cacheentry");
const cachemetadata_1 = require("../../entities/v1/cachemetadata");
// @generated message type with reflection information, may provide speed optimized methods
class CreateCacheEntryRequest$Type extends runtime_5.MessageType {
@ -378,353 +377,12 @@ class GetCacheEntryDownloadURLResponse$Type extends runtime_5.MessageType {
* @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLResponse
*/
exports.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type();
// @generated message type with reflection information, may provide speed optimized methods
class DeleteCacheEntryRequest$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.DeleteCacheEntryRequest", [
{ no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
{ no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { key: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1:
message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
break;
case /* string key */ 2:
message.key = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* github.actions.results.entities.v1.CacheMetadata metadata = 1; */
if (message.metadata)
cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* string key = 2; */
if (message.key !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.DeleteCacheEntryRequest
*/
exports.DeleteCacheEntryRequest = new DeleteCacheEntryRequest$Type();
// @generated message type with reflection information, may provide speed optimized methods
class DeleteCacheEntryResponse$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.DeleteCacheEntryResponse", [
{ no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
{ no: 2, name: "entry_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ }
]);
}
create(value) {
const message = { ok: false, entryId: "0" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* bool ok */ 1:
message.ok = reader.bool();
break;
case /* int64 entry_id */ 2:
message.entryId = reader.int64().toString();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* bool ok = 1; */
if (message.ok !== false)
writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
/* int64 entry_id = 2; */
if (message.entryId !== "0")
writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.DeleteCacheEntryResponse
*/
exports.DeleteCacheEntryResponse = new DeleteCacheEntryResponse$Type();
// @generated message type with reflection information, may provide speed optimized methods
class ListCacheEntriesRequest$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.ListCacheEntriesRequest", [
{ no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
{ no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "restore_keys", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { key: "", restoreKeys: [] };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1:
message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
break;
case /* string key */ 2:
message.key = reader.string();
break;
case /* repeated string restore_keys */ 3:
message.restoreKeys.push(reader.string());
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* github.actions.results.entities.v1.CacheMetadata metadata = 1; */
if (message.metadata)
cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* string key = 2; */
if (message.key !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
/* repeated string restore_keys = 3; */
for (let i = 0; i < message.restoreKeys.length; i++)
writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.ListCacheEntriesRequest
*/
exports.ListCacheEntriesRequest = new ListCacheEntriesRequest$Type();
// @generated message type with reflection information, may provide speed optimized methods
class ListCacheEntriesResponse$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.ListCacheEntriesResponse", [
{ no: 1, name: "entries", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => cacheentry_1.CacheEntry }
]);
}
create(value) {
const message = { entries: [] };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated github.actions.results.entities.v1.CacheEntry entries */ 1:
message.entries.push(cacheentry_1.CacheEntry.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* repeated github.actions.results.entities.v1.CacheEntry entries = 1; */
for (let i = 0; i < message.entries.length; i++)
cacheentry_1.CacheEntry.internalBinaryWrite(message.entries[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.ListCacheEntriesResponse
*/
exports.ListCacheEntriesResponse = new ListCacheEntriesResponse$Type();
// @generated message type with reflection information, may provide speed optimized methods
class LookupCacheEntryRequest$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.LookupCacheEntryRequest", [
{ no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
{ no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "restore_keys", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ },
{ no: 4, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { key: "", restoreKeys: [], version: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1:
message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
break;
case /* string key */ 2:
message.key = reader.string();
break;
case /* repeated string restore_keys */ 3:
message.restoreKeys.push(reader.string());
break;
case /* string version */ 4:
message.version = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* github.actions.results.entities.v1.CacheMetadata metadata = 1; */
if (message.metadata)
cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* string key = 2; */
if (message.key !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
/* repeated string restore_keys = 3; */
for (let i = 0; i < message.restoreKeys.length; i++)
writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]);
/* string version = 4; */
if (message.version !== "")
writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.LookupCacheEntryRequest
*/
exports.LookupCacheEntryRequest = new LookupCacheEntryRequest$Type();
// @generated message type with reflection information, may provide speed optimized methods
class LookupCacheEntryResponse$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.LookupCacheEntryResponse", [
{ no: 1, name: "exists", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
{ no: 2, name: "entry", kind: "message", T: () => cacheentry_1.CacheEntry }
]);
}
create(value) {
const message = { exists: false };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* bool exists */ 1:
message.exists = reader.bool();
break;
case /* github.actions.results.entities.v1.CacheEntry entry */ 2:
message.entry = cacheentry_1.CacheEntry.internalBinaryRead(reader, reader.uint32(), options, message.entry);
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* bool exists = 1; */
if (message.exists !== false)
writer.tag(1, runtime_1.WireType.Varint).bool(message.exists);
/* github.actions.results.entities.v1.CacheEntry entry = 2; */
if (message.entry)
cacheentry_1.CacheEntry.internalBinaryWrite(message.entry, writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.LookupCacheEntryResponse
*/
exports.LookupCacheEntryResponse = new LookupCacheEntryResponse$Type();
/**
* @generated ServiceType for protobuf service github.actions.results.api.v1.CacheService
*/
exports.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [
{ name: "CreateCacheEntry", options: {}, I: exports.CreateCacheEntryRequest, O: exports.CreateCacheEntryResponse },
{ name: "FinalizeCacheEntryUpload", options: {}, I: exports.FinalizeCacheEntryUploadRequest, O: exports.FinalizeCacheEntryUploadResponse },
{ name: "GetCacheEntryDownloadURL", options: {}, I: exports.GetCacheEntryDownloadURLRequest, O: exports.GetCacheEntryDownloadURLResponse },
{ name: "DeleteCacheEntry", options: {}, I: exports.DeleteCacheEntryRequest, O: exports.DeleteCacheEntryResponse },
{ name: "ListCacheEntries", options: {}, I: exports.ListCacheEntriesRequest, O: exports.ListCacheEntriesResponse },
{ name: "LookupCacheEntry", options: {}, I: exports.LookupCacheEntryRequest, O: exports.LookupCacheEntryResponse }
{ name: "GetCacheEntryDownloadURL", options: {}, I: exports.GetCacheEntryDownloadURLRequest, O: exports.GetCacheEntryDownloadURLResponse }
]);
//# sourceMappingURL=cache.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,24 @@
import { CreateCacheEntryRequest, CreateCacheEntryResponse, FinalizeCacheEntryUploadRequest, FinalizeCacheEntryUploadResponse, GetCacheEntryDownloadURLRequest, GetCacheEntryDownloadURLResponse } from "./cache";
interface Rpc {
request(service: string, method: string, contentType: "application/json" | "application/protobuf", data: object | Uint8Array): Promise<object | Uint8Array>;
}
export interface CacheServiceClient {
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
}
export declare class CacheServiceClientJSON implements CacheServiceClient {
private readonly rpc;
constructor(rpc: Rpc);
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
}
export declare class CacheServiceClientProtobuf implements CacheServiceClient {
private readonly rpc;
constructor(rpc: Rpc);
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
}
export {};

View file

@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheServiceClientProtobuf = exports.CacheServiceClientJSON = void 0;
const cache_1 = require("./cache");
class CacheServiceClientJSON {
constructor(rpc) {
this.rpc = rpc;
this.CreateCacheEntry.bind(this);
this.FinalizeCacheEntryUpload.bind(this);
this.GetCacheEntryDownloadURL.bind(this);
}
CreateCacheEntry(request) {
const data = cache_1.CreateCacheEntryRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data);
return promise.then((data) => cache_1.CreateCacheEntryResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
FinalizeCacheEntryUpload(request) {
const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data);
return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
GetCacheEntryDownloadURL(request) {
const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data);
return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
}
exports.CacheServiceClientJSON = CacheServiceClientJSON;
class CacheServiceClientProtobuf {
constructor(rpc) {
this.rpc = rpc;
this.CreateCacheEntry.bind(this);
this.FinalizeCacheEntryUpload.bind(this);
this.GetCacheEntryDownloadURL.bind(this);
}
CreateCacheEntry(request) {
const data = cache_1.CreateCacheEntryRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data);
return promise.then((data) => cache_1.CreateCacheEntryResponse.fromBinary(data));
}
FinalizeCacheEntryUpload(request) {
const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data);
return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data));
}
GetCacheEntryDownloadURL(request) {
const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data);
return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data));
}
}
exports.CacheServiceClientProtobuf = CacheServiceClientProtobuf;
//# sourceMappingURL=cache.twirp-client.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"cache.twirp-client.js","sourceRoot":"","sources":["../../../../../src/generated/results/api/v1/cache.twirp-client.ts"],"names":[],"mappings":";;;AAAA,mCAOmB;AA2BjB,MAAa,sBAAsB;IAEjC,YAAY,GAAQ;QAClB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3C,CAAC;IACD,gBAAgB,CACd,OAAgC;QAEhC,MAAM,IAAI,GAAG,+BAAuB,CAAC,MAAM,CAAC,OAAO,EAAE;YACnD,iBAAiB,EAAE,IAAI;YACvB,iBAAiB,EAAE,KAAK;SACzB,CAAC,CAAC;QACH,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAC9B,4CAA4C,EAC5C,kBAAkB,EAClB,kBAAkB,EAClB,IAAc,CACf,CAAC;QACF,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAC3B,gCAAwB,CAAC,QAAQ,CAAC,IAAW,EAAE;YAC7C,mBAAmB,EAAE,IAAI;SAC1B,CAAC,CACH,CAAC;IACJ,CAAC;IAED,wBAAwB,CACtB,OAAwC;QAExC,MAAM,IAAI,GAAG,uCAA+B,CAAC,MAAM,CAAC,OAAO,EAAE;YAC3D,iBAAiB,EAAE,IAAI;YACvB,iBAAiB,EAAE,KAAK;SACzB,CAAC,CAAC;QACH,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAC9B,4CA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,CAAC,IAAI,EAAE,EAAE,CAC3B,gCAAwB,CAAC,UAAU,CAAC,IAAkB,CAAC,CACxD,CAAC;IACJ,CAAC;IAED,wBAAwB,CACtB,OAAwC;QAExC,MAAM,IAAI,GAAG,uCAA+B,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAC/D,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAC9B,4CAA4C,EAC5C,0BAA0B,EAC1B,sBAAsB,EACtB,IAAI,CACL,CAAC;QACF,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAC3B,wCAAgC,CAAC,UAAU,CAAC,IAAkB,CAAC,CAChE,CAAC;IACJ,CAAC;IAED,wBAAwB,CACtB,OAAwC;QAExC,MAAM,IAAI,GAAG,uCAA+B,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAC/D,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAC9B,4CAA4C,EAC5C,0BAA0B,EAC1B,sBAAsB,EACtB,IAAI,CACL,CAAC;QACF,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAC3B,wCAAgC,CAAC,UAAU,CAAC,IAAkB,CAAC,CAChE,CAAC;IACJ,CAAC;CACF;AApDD,gEAoDC"}

View file

@ -1,53 +0,0 @@
/// <reference types="node" />
import { TwirpContext, TwirpServer } from "twirp-ts";
import { CreateCacheEntryRequest, CreateCacheEntryResponse, FinalizeCacheEntryUploadRequest, FinalizeCacheEntryUploadResponse, GetCacheEntryDownloadURLRequest, GetCacheEntryDownloadURLResponse, DeleteCacheEntryRequest, DeleteCacheEntryResponse, ListCacheEntriesRequest, ListCacheEntriesResponse, LookupCacheEntryRequest, LookupCacheEntryResponse } from "./cache";
interface Rpc {
request(service: string, method: string, contentType: "application/json" | "application/protobuf", data: object | Uint8Array): Promise<object | Uint8Array>;
}
export interface CacheServiceClient {
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
DeleteCacheEntry(request: DeleteCacheEntryRequest): Promise<DeleteCacheEntryResponse>;
ListCacheEntries(request: ListCacheEntriesRequest): Promise<ListCacheEntriesResponse>;
LookupCacheEntry(request: LookupCacheEntryRequest): Promise<LookupCacheEntryResponse>;
}
export declare class CacheServiceClientJSON implements CacheServiceClient {
private readonly rpc;
constructor(rpc: Rpc);
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
DeleteCacheEntry(request: DeleteCacheEntryRequest): Promise<DeleteCacheEntryResponse>;
ListCacheEntries(request: ListCacheEntriesRequest): Promise<ListCacheEntriesResponse>;
LookupCacheEntry(request: LookupCacheEntryRequest): Promise<LookupCacheEntryResponse>;
}
export declare class CacheServiceClientProtobuf implements CacheServiceClient {
private readonly rpc;
constructor(rpc: Rpc);
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
DeleteCacheEntry(request: DeleteCacheEntryRequest): Promise<DeleteCacheEntryResponse>;
ListCacheEntries(request: ListCacheEntriesRequest): Promise<ListCacheEntriesResponse>;
LookupCacheEntry(request: LookupCacheEntryRequest): Promise<LookupCacheEntryResponse>;
}
export interface CacheServiceTwirp<T extends TwirpContext = TwirpContext> {
CreateCacheEntry(ctx: T, request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(ctx: T, request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(ctx: T, request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
DeleteCacheEntry(ctx: T, request: DeleteCacheEntryRequest): Promise<DeleteCacheEntryResponse>;
ListCacheEntries(ctx: T, request: ListCacheEntriesRequest): Promise<ListCacheEntriesResponse>;
LookupCacheEntry(ctx: T, request: LookupCacheEntryRequest): Promise<LookupCacheEntryResponse>;
}
export declare enum CacheServiceMethod {
CreateCacheEntry = "CreateCacheEntry",
FinalizeCacheEntryUpload = "FinalizeCacheEntryUpload",
GetCacheEntryDownloadURL = "GetCacheEntryDownloadURL",
DeleteCacheEntry = "DeleteCacheEntry",
ListCacheEntries = "ListCacheEntries",
LookupCacheEntry = "LookupCacheEntry"
}
export declare const CacheServiceMethodList: CacheServiceMethod[];
export declare function createCacheServiceServer<T extends TwirpContext = TwirpContext>(service: CacheServiceTwirp<T>): TwirpServer<CacheServiceTwirp<TwirpContext<import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>>>, T>;
export {};

View file

@ -1,602 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCacheServiceServer = exports.CacheServiceMethodList = exports.CacheServiceMethod = exports.CacheServiceClientProtobuf = exports.CacheServiceClientJSON = void 0;
const twirp_ts_1 = require("twirp-ts");
const cache_1 = require("./cache");
class CacheServiceClientJSON {
constructor(rpc) {
this.rpc = rpc;
this.CreateCacheEntry.bind(this);
this.FinalizeCacheEntryUpload.bind(this);
this.GetCacheEntryDownloadURL.bind(this);
this.DeleteCacheEntry.bind(this);
this.ListCacheEntries.bind(this);
this.LookupCacheEntry.bind(this);
}
CreateCacheEntry(request) {
const data = cache_1.CreateCacheEntryRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data);
return promise.then((data) => cache_1.CreateCacheEntryResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
FinalizeCacheEntryUpload(request) {
const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data);
return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
GetCacheEntryDownloadURL(request) {
const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data);
return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
DeleteCacheEntry(request) {
const data = cache_1.DeleteCacheEntryRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "DeleteCacheEntry", "application/json", data);
return promise.then((data) => cache_1.DeleteCacheEntryResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
ListCacheEntries(request) {
const data = cache_1.ListCacheEntriesRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "ListCacheEntries", "application/json", data);
return promise.then((data) => cache_1.ListCacheEntriesResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
LookupCacheEntry(request) {
const data = cache_1.LookupCacheEntryRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "LookupCacheEntry", "application/json", data);
return promise.then((data) => cache_1.LookupCacheEntryResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
}
exports.CacheServiceClientJSON = CacheServiceClientJSON;
class CacheServiceClientProtobuf {
constructor(rpc) {
this.rpc = rpc;
this.CreateCacheEntry.bind(this);
this.FinalizeCacheEntryUpload.bind(this);
this.GetCacheEntryDownloadURL.bind(this);
this.DeleteCacheEntry.bind(this);
this.ListCacheEntries.bind(this);
this.LookupCacheEntry.bind(this);
}
CreateCacheEntry(request) {
const data = cache_1.CreateCacheEntryRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data);
return promise.then((data) => cache_1.CreateCacheEntryResponse.fromBinary(data));
}
FinalizeCacheEntryUpload(request) {
const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data);
return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data));
}
GetCacheEntryDownloadURL(request) {
const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data);
return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data));
}
DeleteCacheEntry(request) {
const data = cache_1.DeleteCacheEntryRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "DeleteCacheEntry", "application/protobuf", data);
return promise.then((data) => cache_1.DeleteCacheEntryResponse.fromBinary(data));
}
ListCacheEntries(request) {
const data = cache_1.ListCacheEntriesRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "ListCacheEntries", "application/protobuf", data);
return promise.then((data) => cache_1.ListCacheEntriesResponse.fromBinary(data));
}
LookupCacheEntry(request) {
const data = cache_1.LookupCacheEntryRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "LookupCacheEntry", "application/protobuf", data);
return promise.then((data) => cache_1.LookupCacheEntryResponse.fromBinary(data));
}
}
exports.CacheServiceClientProtobuf = CacheServiceClientProtobuf;
var CacheServiceMethod;
(function (CacheServiceMethod) {
CacheServiceMethod["CreateCacheEntry"] = "CreateCacheEntry";
CacheServiceMethod["FinalizeCacheEntryUpload"] = "FinalizeCacheEntryUpload";
CacheServiceMethod["GetCacheEntryDownloadURL"] = "GetCacheEntryDownloadURL";
CacheServiceMethod["DeleteCacheEntry"] = "DeleteCacheEntry";
CacheServiceMethod["ListCacheEntries"] = "ListCacheEntries";
CacheServiceMethod["LookupCacheEntry"] = "LookupCacheEntry";
})(CacheServiceMethod || (exports.CacheServiceMethod = CacheServiceMethod = {}));
exports.CacheServiceMethodList = [
CacheServiceMethod.CreateCacheEntry,
CacheServiceMethod.FinalizeCacheEntryUpload,
CacheServiceMethod.GetCacheEntryDownloadURL,
CacheServiceMethod.DeleteCacheEntry,
CacheServiceMethod.ListCacheEntries,
CacheServiceMethod.LookupCacheEntry,
];
function createCacheServiceServer(service) {
return new twirp_ts_1.TwirpServer({
service,
packageName: "github.actions.results.api.v1",
serviceName: "CacheService",
methodList: exports.CacheServiceMethodList,
matchRoute: matchCacheServiceRoute,
});
}
exports.createCacheServiceServer = createCacheServiceServer;
function matchCacheServiceRoute(method, events) {
switch (method) {
case "CreateCacheEntry":
return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () {
ctx = Object.assign(Object.assign({}, ctx), { methodName: "CreateCacheEntry" });
yield events.onMatch(ctx);
return handleCacheServiceCreateCacheEntryRequest(ctx, service, data, interceptors);
});
case "FinalizeCacheEntryUpload":
return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () {
ctx = Object.assign(Object.assign({}, ctx), { methodName: "FinalizeCacheEntryUpload" });
yield events.onMatch(ctx);
return handleCacheServiceFinalizeCacheEntryUploadRequest(ctx, service, data, interceptors);
});
case "GetCacheEntryDownloadURL":
return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () {
ctx = Object.assign(Object.assign({}, ctx), { methodName: "GetCacheEntryDownloadURL" });
yield events.onMatch(ctx);
return handleCacheServiceGetCacheEntryDownloadURLRequest(ctx, service, data, interceptors);
});
case "DeleteCacheEntry":
return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () {
ctx = Object.assign(Object.assign({}, ctx), { methodName: "DeleteCacheEntry" });
yield events.onMatch(ctx);
return handleCacheServiceDeleteCacheEntryRequest(ctx, service, data, interceptors);
});
case "ListCacheEntries":
return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () {
ctx = Object.assign(Object.assign({}, ctx), { methodName: "ListCacheEntries" });
yield events.onMatch(ctx);
return handleCacheServiceListCacheEntriesRequest(ctx, service, data, interceptors);
});
case "LookupCacheEntry":
return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () {
ctx = Object.assign(Object.assign({}, ctx), { methodName: "LookupCacheEntry" });
yield events.onMatch(ctx);
return handleCacheServiceLookupCacheEntryRequest(ctx, service, data, interceptors);
});
default:
events.onNotFound();
const msg = `no handler found`;
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg);
}
}
function handleCacheServiceCreateCacheEntryRequest(ctx, service, data, interceptors) {
switch (ctx.contentType) {
case twirp_ts_1.TwirpContentType.JSON:
return handleCacheServiceCreateCacheEntryJSON(ctx, service, data, interceptors);
case twirp_ts_1.TwirpContentType.Protobuf:
return handleCacheServiceCreateCacheEntryProtobuf(ctx, service, data, interceptors);
default:
const msg = "unexpected Content-Type";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg);
}
}
function handleCacheServiceFinalizeCacheEntryUploadRequest(ctx, service, data, interceptors) {
switch (ctx.contentType) {
case twirp_ts_1.TwirpContentType.JSON:
return handleCacheServiceFinalizeCacheEntryUploadJSON(ctx, service, data, interceptors);
case twirp_ts_1.TwirpContentType.Protobuf:
return handleCacheServiceFinalizeCacheEntryUploadProtobuf(ctx, service, data, interceptors);
default:
const msg = "unexpected Content-Type";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg);
}
}
function handleCacheServiceGetCacheEntryDownloadURLRequest(ctx, service, data, interceptors) {
switch (ctx.contentType) {
case twirp_ts_1.TwirpContentType.JSON:
return handleCacheServiceGetCacheEntryDownloadURLJSON(ctx, service, data, interceptors);
case twirp_ts_1.TwirpContentType.Protobuf:
return handleCacheServiceGetCacheEntryDownloadURLProtobuf(ctx, service, data, interceptors);
default:
const msg = "unexpected Content-Type";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg);
}
}
function handleCacheServiceDeleteCacheEntryRequest(ctx, service, data, interceptors) {
switch (ctx.contentType) {
case twirp_ts_1.TwirpContentType.JSON:
return handleCacheServiceDeleteCacheEntryJSON(ctx, service, data, interceptors);
case twirp_ts_1.TwirpContentType.Protobuf:
return handleCacheServiceDeleteCacheEntryProtobuf(ctx, service, data, interceptors);
default:
const msg = "unexpected Content-Type";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg);
}
}
function handleCacheServiceListCacheEntriesRequest(ctx, service, data, interceptors) {
switch (ctx.contentType) {
case twirp_ts_1.TwirpContentType.JSON:
return handleCacheServiceListCacheEntriesJSON(ctx, service, data, interceptors);
case twirp_ts_1.TwirpContentType.Protobuf:
return handleCacheServiceListCacheEntriesProtobuf(ctx, service, data, interceptors);
default:
const msg = "unexpected Content-Type";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg);
}
}
function handleCacheServiceLookupCacheEntryRequest(ctx, service, data, interceptors) {
switch (ctx.contentType) {
case twirp_ts_1.TwirpContentType.JSON:
return handleCacheServiceLookupCacheEntryJSON(ctx, service, data, interceptors);
case twirp_ts_1.TwirpContentType.Protobuf:
return handleCacheServiceLookupCacheEntryProtobuf(ctx, service, data, interceptors);
default:
const msg = "unexpected Content-Type";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg);
}
}
function handleCacheServiceCreateCacheEntryJSON(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
const body = JSON.parse(data.toString() || "{}");
request = cache_1.CreateCacheEntryRequest.fromJson(body, {
ignoreUnknownFields: true,
});
}
catch (e) {
if (e instanceof Error) {
const msg = "the json request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.CreateCacheEntry(ctx, inputReq);
});
}
else {
response = yield service.CreateCacheEntry(ctx, request);
}
return JSON.stringify(cache_1.CreateCacheEntryResponse.toJson(response, {
useProtoFieldName: true,
emitDefaultValues: false,
}));
});
}
function handleCacheServiceFinalizeCacheEntryUploadJSON(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
const body = JSON.parse(data.toString() || "{}");
request = cache_1.FinalizeCacheEntryUploadRequest.fromJson(body, {
ignoreUnknownFields: true,
});
}
catch (e) {
if (e instanceof Error) {
const msg = "the json request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.FinalizeCacheEntryUpload(ctx, inputReq);
});
}
else {
response = yield service.FinalizeCacheEntryUpload(ctx, request);
}
return JSON.stringify(cache_1.FinalizeCacheEntryUploadResponse.toJson(response, {
useProtoFieldName: true,
emitDefaultValues: false,
}));
});
}
function handleCacheServiceGetCacheEntryDownloadURLJSON(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
const body = JSON.parse(data.toString() || "{}");
request = cache_1.GetCacheEntryDownloadURLRequest.fromJson(body, {
ignoreUnknownFields: true,
});
}
catch (e) {
if (e instanceof Error) {
const msg = "the json request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.GetCacheEntryDownloadURL(ctx, inputReq);
});
}
else {
response = yield service.GetCacheEntryDownloadURL(ctx, request);
}
return JSON.stringify(cache_1.GetCacheEntryDownloadURLResponse.toJson(response, {
useProtoFieldName: true,
emitDefaultValues: false,
}));
});
}
function handleCacheServiceDeleteCacheEntryJSON(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
const body = JSON.parse(data.toString() || "{}");
request = cache_1.DeleteCacheEntryRequest.fromJson(body, {
ignoreUnknownFields: true,
});
}
catch (e) {
if (e instanceof Error) {
const msg = "the json request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.DeleteCacheEntry(ctx, inputReq);
});
}
else {
response = yield service.DeleteCacheEntry(ctx, request);
}
return JSON.stringify(cache_1.DeleteCacheEntryResponse.toJson(response, {
useProtoFieldName: true,
emitDefaultValues: false,
}));
});
}
function handleCacheServiceListCacheEntriesJSON(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
const body = JSON.parse(data.toString() || "{}");
request = cache_1.ListCacheEntriesRequest.fromJson(body, {
ignoreUnknownFields: true,
});
}
catch (e) {
if (e instanceof Error) {
const msg = "the json request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.ListCacheEntries(ctx, inputReq);
});
}
else {
response = yield service.ListCacheEntries(ctx, request);
}
return JSON.stringify(cache_1.ListCacheEntriesResponse.toJson(response, {
useProtoFieldName: true,
emitDefaultValues: false,
}));
});
}
function handleCacheServiceLookupCacheEntryJSON(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
const body = JSON.parse(data.toString() || "{}");
request = cache_1.LookupCacheEntryRequest.fromJson(body, {
ignoreUnknownFields: true,
});
}
catch (e) {
if (e instanceof Error) {
const msg = "the json request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.LookupCacheEntry(ctx, inputReq);
});
}
else {
response = yield service.LookupCacheEntry(ctx, request);
}
return JSON.stringify(cache_1.LookupCacheEntryResponse.toJson(response, {
useProtoFieldName: true,
emitDefaultValues: false,
}));
});
}
function handleCacheServiceCreateCacheEntryProtobuf(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
request = cache_1.CreateCacheEntryRequest.fromBinary(data);
}
catch (e) {
if (e instanceof Error) {
const msg = "the protobuf request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.CreateCacheEntry(ctx, inputReq);
});
}
else {
response = yield service.CreateCacheEntry(ctx, request);
}
return Buffer.from(cache_1.CreateCacheEntryResponse.toBinary(response));
});
}
function handleCacheServiceFinalizeCacheEntryUploadProtobuf(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
request = cache_1.FinalizeCacheEntryUploadRequest.fromBinary(data);
}
catch (e) {
if (e instanceof Error) {
const msg = "the protobuf request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.FinalizeCacheEntryUpload(ctx, inputReq);
});
}
else {
response = yield service.FinalizeCacheEntryUpload(ctx, request);
}
return Buffer.from(cache_1.FinalizeCacheEntryUploadResponse.toBinary(response));
});
}
function handleCacheServiceGetCacheEntryDownloadURLProtobuf(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
request = cache_1.GetCacheEntryDownloadURLRequest.fromBinary(data);
}
catch (e) {
if (e instanceof Error) {
const msg = "the protobuf request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.GetCacheEntryDownloadURL(ctx, inputReq);
});
}
else {
response = yield service.GetCacheEntryDownloadURL(ctx, request);
}
return Buffer.from(cache_1.GetCacheEntryDownloadURLResponse.toBinary(response));
});
}
function handleCacheServiceDeleteCacheEntryProtobuf(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
request = cache_1.DeleteCacheEntryRequest.fromBinary(data);
}
catch (e) {
if (e instanceof Error) {
const msg = "the protobuf request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.DeleteCacheEntry(ctx, inputReq);
});
}
else {
response = yield service.DeleteCacheEntry(ctx, request);
}
return Buffer.from(cache_1.DeleteCacheEntryResponse.toBinary(response));
});
}
function handleCacheServiceListCacheEntriesProtobuf(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
request = cache_1.ListCacheEntriesRequest.fromBinary(data);
}
catch (e) {
if (e instanceof Error) {
const msg = "the protobuf request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.ListCacheEntries(ctx, inputReq);
});
}
else {
response = yield service.ListCacheEntries(ctx, request);
}
return Buffer.from(cache_1.ListCacheEntriesResponse.toBinary(response));
});
}
function handleCacheServiceLookupCacheEntryProtobuf(ctx, service, data, interceptors) {
return __awaiter(this, void 0, void 0, function* () {
let request;
let response;
try {
request = cache_1.LookupCacheEntryRequest.fromBinary(data);
}
catch (e) {
if (e instanceof Error) {
const msg = "the protobuf request could not be decoded";
throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
}
}
if (interceptors && interceptors.length > 0) {
const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors);
response = yield interceptor(ctx, request, (ctx, inputReq) => {
return service.LookupCacheEntry(ctx, inputReq);
});
}
else {
response = yield service.LookupCacheEntry(ctx, request);
}
return Buffer.from(cache_1.LookupCacheEntryResponse.toBinary(response));
});
}
//# sourceMappingURL=cache.twirp.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,71 +0,0 @@
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
import { Timestamp } from "../../../google/protobuf/timestamp";
/**
* @generated from protobuf message github.actions.results.entities.v1.CacheEntry
*/
export interface CacheEntry {
/**
* An explicit key for a cache entry
*
* @generated from protobuf field: string key = 1;
*/
key: string;
/**
* SHA256 hex digest of the cache archive
*
* @generated from protobuf field: string hash = 2;
*/
hash: string;
/**
* Cache entry size in bytes
*
* @generated from protobuf field: int64 size_bytes = 3;
*/
sizeBytes: string;
/**
* Access scope
*
* @generated from protobuf field: string scope = 4;
*/
scope: string;
/**
* Version SHA256 hex digest
*
* @generated from protobuf field: string version = 5;
*/
version: string;
/**
* When the cache entry was created
*
* @generated from protobuf field: google.protobuf.Timestamp created_at = 6;
*/
createdAt?: Timestamp;
/**
* When the cache entry was last accessed
*
* @generated from protobuf field: google.protobuf.Timestamp last_accessed_at = 7;
*/
lastAccessedAt?: Timestamp;
/**
* When the cache entry is set to expire
*
* @generated from protobuf field: google.protobuf.Timestamp expires_at = 8;
*/
expiresAt?: Timestamp;
}
declare class CacheEntry$Type extends MessageType<CacheEntry> {
constructor();
create(value?: PartialMessage<CacheEntry>): CacheEntry;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: CacheEntry): CacheEntry;
internalBinaryWrite(message: CacheEntry, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.entities.v1.CacheEntry
*/
export declare const CacheEntry: CacheEntry$Type;
export {};

View file

@ -1,106 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheEntry = void 0;
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const runtime_4 = require("@protobuf-ts/runtime");
const runtime_5 = require("@protobuf-ts/runtime");
const timestamp_1 = require("../../../google/protobuf/timestamp");
// @generated message type with reflection information, may provide speed optimized methods
class CacheEntry$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.entities.v1.CacheEntry", [
{ no: 1, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "hash", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "size_bytes", kind: "scalar", T: 3 /*ScalarType.INT64*/ },
{ no: 4, name: "scope", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 5, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp },
{ no: 7, name: "last_accessed_at", kind: "message", T: () => timestamp_1.Timestamp },
{ no: 8, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }
]);
}
create(value) {
const message = { key: "", hash: "", sizeBytes: "0", scope: "", version: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* string key */ 1:
message.key = reader.string();
break;
case /* string hash */ 2:
message.hash = reader.string();
break;
case /* int64 size_bytes */ 3:
message.sizeBytes = reader.int64().toString();
break;
case /* string scope */ 4:
message.scope = reader.string();
break;
case /* string version */ 5:
message.version = reader.string();
break;
case /* google.protobuf.Timestamp created_at */ 6:
message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt);
break;
case /* google.protobuf.Timestamp last_accessed_at */ 7:
message.lastAccessedAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.lastAccessedAt);
break;
case /* google.protobuf.Timestamp expires_at */ 8:
message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt);
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* string key = 1; */
if (message.key !== "")
writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.key);
/* string hash = 2; */
if (message.hash !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.hash);
/* int64 size_bytes = 3; */
if (message.sizeBytes !== "0")
writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes);
/* string scope = 4; */
if (message.scope !== "")
writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.scope);
/* string version = 5; */
if (message.version !== "")
writer.tag(5, runtime_1.WireType.LengthDelimited).string(message.version);
/* google.protobuf.Timestamp created_at = 6; */
if (message.createdAt)
timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* google.protobuf.Timestamp last_accessed_at = 7; */
if (message.lastAccessedAt)
timestamp_1.Timestamp.internalBinaryWrite(message.lastAccessedAt, writer.tag(7, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* google.protobuf.Timestamp expires_at = 8; */
if (message.expiresAt)
timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(8, runtime_1.WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.entities.v1.CacheEntry
*/
exports.CacheEntry = new CacheEntry$Type();
//# sourceMappingURL=cacheentry.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"cacheentry.js","sourceRoot":"","sources":["../../../../../src/generated/results/entities/v1/cacheentry.ts"],"names":[],"mappings":";;;AAKA,kDAAgD;AAGhD,kDAA2D;AAE3D,kDAA8D;AAC9D,kDAAoD;AACpD,kDAAmD;AACnD,kEAA+D;AAsD/D,2FAA2F;AAC3F,MAAM,eAAgB,SAAQ,qBAAuB;IACjD;QACI,KAAK,CAAC,+CAA+C,EAAE;YACnD,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,qBAAqB,EAAE;YAClE,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,qBAAqB,EAAE;YACnE,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,oBAAoB,EAAE;YACxE,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,qBAAqB,EAAE;YACpE,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,qBAAqB,EAAE;YACtE,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,qBAAS,EAAE;YAClE,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,SAAS,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AAE,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,kBAAQ,CAAC,eAAe,CAAC,CAAC,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;QACrH,qDAAqD;QACrD,IAAI,OAAO,CAAC,cAAc;YACtB,qBAAS,CAAC,mBAAmB,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,kBAAQ,CAAC,eAAe,CAAC,CAAC,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;QAC1H,+CAA+C;QAC/C,IAAI,OAAO,CAAC,SAAS;YACjB,qBAAS,CAAC,mBAAmB,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,kBAAQ,CAAC,eAAe,CAAC,CAAC,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;QACrH,IAAI,CAAC,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACnC,IAAI,CAAC,KAAK,KAAK;YACX,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,6BAAmB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAClF,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AACD;;GAEG;AACU,QAAA,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC"}

View file

@ -1,4 +1,4 @@
import { CacheServiceClientJSON } from '../../generated/results/api/v1/cache.twirp';
import { CacheServiceClientJSON } from '../../generated/results/api/v1/cache.twirp-client';
export declare function internalCacheTwirpClient(options?: {
maxAttempts?: number;
retryIntervalMs?: number;

View file

@ -17,7 +17,7 @@ const config_1 = require("../config");
const cacheUtils_1 = require("../cacheUtils");
const auth_1 = require("@actions/http-client/lib/auth");
const http_client_1 = require("@actions/http-client");
const cache_twirp_1 = require("../../generated/results/api/v1/cache.twirp");
const cache_twirp_client_1 = require("../../generated/results/api/v1/cache.twirp-client");
/**
* This class is a wrapper around the CacheServiceClientJSON class generated by Twirp.
*
@ -154,7 +154,7 @@ class CacheServiceClient {
}
function internalCacheTwirpClient(options) {
const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier);
return new cache_twirp_1.CacheServiceClientJSON(client);
return new cache_twirp_client_1.CacheServiceClientJSON(client);
}
exports.internalCacheTwirpClient = internalCacheTwirpClient;
//# sourceMappingURL=cacheTwirpClient.js.map

View file

@ -1 +1 @@
{"version":3,"file":"cacheTwirpClient.js","sourceRoot":"","sources":["../../../src/internal/shared/cacheTwirpClient.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAyC;AACzC,6CAA+C;AAC/C,qCAAiD;AACjD,sCAA4C;AAC5C,8CAA6C;AAC7C,wDAAqE;AACrE,sDAA8E;AAC9E,4EAAiF;AAYjF;;;;;;GAMG;AACH,MAAM,kBAAkB;IAOtB,YACE,SAAiB,EACjB,WAAoB,EACpB,6BAAsC,EACtC,eAAwB;QARlB,gBAAW,GAAG,CAAC,CAAA;QACf,kCAA6B,GAAG,IAAI,CAAA;QACpC,oBAAe,GAAG,GAAG,CAAA;QAQ3B,MAAM,KAAK,GAAG,IAAA,4BAAe,GAAE,CAAA;QAC/B,IAAI,CAAC,OAAO,GAAG,IAAA,2BAAkB,GAAE,CAAA;QACnC,IAAI,WAAW,EAAE;YACf,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;SAC/B;QACD,IAAI,6BAA6B,EAAE;YACjC,IAAI,CAAC,6BAA6B,GAAG,6BAA6B,CAAA;SACnE;QACD,IAAI,eAAe,EAAE;YACnB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAA;SACvC;QAED,IAAI,CAAC,UAAU,GAAG,IAAI,wBAAU,CAAC,SAA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O,uBAAP,OAAO,CAAE,WAAW,EACpB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,EACxB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,CACzB,CAAA;IACD,OAAO,IAAI,2CAAsB,CAAC,MAAM,CAAC,CAAA;AAC3C,CAAC;AAZD,4DAYC"}

View file

@ -1,6 +1,6 @@
{
"name": "@actions/cache",
"version": "4.0.0",
"version": "4.0.1",
"preview": true,
"description": "Actions cache lib",
"keywords": [
@ -46,11 +46,10 @@
"@azure/ms-rest-js": "^2.6.0",
"@azure/storage-blob": "^12.13.0",
"@protobuf-ts/plugin": "^2.9.4",
"semver": "^6.3.1",
"twirp-ts": "^2.5.0"
"semver": "^6.3.1"
},
"devDependencies": {
"@types/semver": "^6.0.0",
"typescript": "^5.2.2"
}
}
}

View file

@ -1,6 +1,6 @@
{
"name": "@eslint/js",
"version": "9.19.0",
"version": "9.20.0",
"description": "ESLint JavaScript language implementation",
"main": "./src/index.js",
"types": "./types/index.d.ts",

21
node_modules/@octokit/app/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

440
node_modules/@octokit/app/README.md generated vendored Normal file
View file

@ -0,0 +1,440 @@
# app.js
> GitHub App toolset for Node.js
[![@latest](https://img.shields.io/npm/v/@octokit/app.svg)](https://www.npmjs.com/package/@octokit/app)
[![Build Status](https://github.com/octokit/app.js/workflows/Test/badge.svg)](https://github.com/octokit/app.js/actions?workflow=Test)
<!-- toc -->
- [Usage](#usage)
- [`App.defaults(options)`](#appdefaultsoptions)
- [Constructor](#constructor)
- [API](#api)
- [`app.octokit`](#appoctokit)
- [`app.log`](#applog)
- [`app.getInstallationOctokit`](#appgetinstallationoctokit)
- [`app.eachInstallation`](#appeachinstallation)
- [`app.eachRepository`](#appeachrepository)
- [`app.getInstallationUrl`](#appgetinstallationurl)
- [`app.webhooks`](#appwebhooks)
- [`app.oauth`](#appoauth)
- [Middlewares](#middlewares)
- [`createNodeMiddleware(app, options)`](#createnodemiddlewareapp-options)
- [Contributing](#contributing)
- [License](#license)
<!-- tocstop -->
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
`@octokit/app` is not meant for browser usage.
</td></tr>
<tr><th>
Node
</th><td>
Install with `npm install @octokit/app`
```js
const { App, createNodeMiddleware } = require("@octokit/app");
```
</td></tr>
</tbody>
</table>
> [!IMPORTANT]
> As we use [conditional exports](https://nodejs.org/api/packages.html#conditional-exports), you will need to adapt your `tsconfig.json` by setting `"moduleResolution": "node16", "module": "node16"`.
>
> See the TypeScript docs on [package.json "exports"](https://www.typescriptlang.org/docs/handbook/modules/reference.html#packagejson-exports).<br>
> See this [helpful guide on transitioning to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) from [@sindresorhus](https://github.com/sindresorhus)
```js
const app = new App({
appId: 123,
privateKey: "-----BEGIN PRIVATE KEY-----\n...",
oauth: {
clientId: "0123",
clientSecret: "0123secret",
},
webhooks: {
secret: "secret",
},
});
const { data } = await app.octokit.request("/app");
console.log("authenticated as %s", data.name);
for await (const { installation } of app.eachInstallation.iterator()) {
for await (const { octokit, repository } of app.eachRepository.iterator({
installationId: installation.id,
})) {
await octokit.request("POST /repos/{owner}/{repo}/dispatches", {
owner: repository.owner.login,
repo: repository.name,
event_type: "my_event",
});
}
}
app.webhooks.on("issues.opened", async ({ octokit, payload }) => {
await octokit.request(
"POST /repos/{owner}/{repo}/issues/{issue_number}/comments",
{
owner: payload.repository.owner.login,
repo: payload.repository.name,
issue_number: payload.issue.number,
body: "Hello World!",
},
);
});
app.oauth.on("token", async ({ token, octokit }) => {
const { data } = await octokit.request("GET /user");
console.log(`Token retrieved for ${data.login}`);
});
require("http").createServer(createNodeMiddleware(app)).listen(3000);
// can now receive requests at /api/github/*
```
## `App.defaults(options)`
Create a new `App` with custom defaults for the [constructor options](#constructor-options)
```js
const MyApp = App.defaults({
Octokit: MyOctokit,
});
const app = new MyApp({ clientId, clientSecret });
// app.octokit is now an instance of MyOctokit
```
## Constructor
<table width="100%">
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>appId</code>
</th>
<th>
<code>number</code>
</th>
<td>
<strong>Required</strong>. Find the <strong>App ID</strong> on the apps about page in settings.
</td>
</tr>
<tr>
<th>
<code>privateKey</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required</strong>. Content of the <code>*.pem</code> file you downloaded from the apps about page. You can generate a new private key if needed.
</td>
</tr>
<tr id="constructor-option-octokit">
<th>
<code>Octokit</code>
</th>
<th>
<code>Constructor</code>
</th>
<td>
You can pass in your own Octokit constructor with custom defaults and plugins. Note that `authStrategy` will be always be set to `createAppAuth` from [`@octokit/auth-app`](https://github.com/octokit/auth-app.js).
For usage with enterprise, set `baseUrl` to the hostname + `/api/v3`. Example:
```js
const { Octokit } = require("@octokit/core");
new App({
appId: 123,
privateKey: "-----BEGIN PRIVATE KEY-----\n...",
oauth: {
clientId: 123,
clientSecret: "secret",
},
webhooks: {
secret: "secret",
},
Octokit: Octokit.defaults({
baseUrl: "https://ghe.my-company.com/api/v3",
}),
});
```
Defaults to [`@octokit/core`](https://github.com/octokit/core.js).
</td></tr>
<tr id="constructor-option-log">
<th>
<code>log</code>
</th>
<th>
<code>object</code>
</th>
<td>
Used for internal logging. Defaults to <a href="https://developer.mozilla.org/en-US/docs/Web/API/console"><code>console</code></a>.
</td>
</tr>
<tr>
<th>
<code>webhooks.secret</code>
</th>
<th>
<code>string</code>
</th>
<td>
<strong>Required.</strong> Secret as configured in the GitHub App's settings.
</td>
</tr>
<tr>
<th>
<code>webhooks.transform</code>
</th>
<th>
<code>function</code>
</th>
<td>
Only relevant for `app.webhooks.on`. Transform emitted event before calling handlers. Can be asynchronous.
</td>
</tr>
<tr>
<th>
<code>oauth.clientId</code>
</th>
<th>
<code>number</code>
</th>
<td>
Find the OAuth <strong>Client ID</strong> on the apps about page in settings.
</td>
</tr>
<tr>
<th>
<code>oauth.clientSecret</code>
</th>
<th>
<code>number</code>
</th>
<td>
Find the OAuth <strong>Client Secret</strong> on the apps about page in settings.
</td>
</tr>
<tr>
<th>
<code>oauth.allowSignup</code>
</th>
<th>
<code>boolean</code>
</th>
<td>
Sets the default value for <code>app.oauth.getAuthorizationUrl(options)</code>.
</td>
</tr>
</tbody>
</table>
## API
### `app.octokit`
Octokit instance. Uses the [`Octokit` constructor option](#constructor-option-octokit) if passed.
### `app.log`
See https://github.com/octokit/core.js#logging. Customize using the [`log` constructor option](#constructor-option-log).
### `app.getInstallationOctokit`
```js
const octokit = await app.getInstallationOctokit(123);
```
### `app.eachInstallation`
```js
for await (const { octokit, installation } of app.eachInstallation.iterator()) { /* ... */ }
await app.eachInstallation(({ octokit, installation }) => /* ... */)
```
### `app.eachRepository`
```js
for await (const { octokit, repository } of app.eachRepository.iterator()) { /* ... */ }
await app.eachRepository(({ octokit, repository }) => /* ... */)
```
Optionally pass installation ID to iterate through all repositories in one installation
```js
for await (const { octokit, repository } of app.eachRepository.iterator({ installationId })) { /* ... */ }
await app.eachRepository({ installationId }, ({ octokit, repository }) => /* ... */)
```
### `app.getInstallationUrl`
```js
const installationUrl = await app.getInstallationUrl();
return res.redirect(installationUrl);
```
Optionally pass the ID of a GitHub organization or user to request installation on that specific target.
If the user will be sent to a redirect URL after installation (such as if you request user authorization during installation), you can also supply a `state` string that will be included in the query of the post-install redirect.
```js
const installationUrl = await app.getInstallationUrl({ state, target_id });
return res.redirect(installationUrl);
```
### `app.webhooks`
An [`@octokit/webhooks` instance](https://github.com/octokit/webhooks.js/#readme)
### `app.oauth`
An [`@octokit/oauth-app` instance](https://github.com/octokit/oauth-app.js/#readme)
## Middlewares
A middleware is a method or set of methods to handle requests for common environments.
By default, all middlewares expose the following routes
| Route | Route Description |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /api/github/webhooks` | Endpoint to receive GitHub Webhook Event requests |
| `GET /api/github/oauth/login` | Redirects to GitHub's authorization endpoint. Accepts optional `?state` query parameter. |
| `GET /api/github/oauth/callback` | The client's redirect endpoint. This is where the `token` event gets triggered |
| `POST /api/github/oauth/token` | Exchange an authorization code for an OAuth Access token. If successful, the `token` event gets triggered. |
| `GET /api/github/oauth/token` | Check if token is valid. Must authenticate using token in `Authorization` header. Uses GitHub's [`POST /applications/{client_id}/token`](https://developer.github.com/v3/apps/oauth_applications/#check-a-token) endpoint |
| `PATCH /api/github/oauth/token` | Resets a token (invalidates current one, returns new token). Must authenticate using token in `Authorization` header. Uses GitHub's [`PATCH /applications/{client_id}/token`](https://developer.github.com/v3/apps/oauth_applications/#reset-a-token) endpoint. |
| `DELETE /api/github/oauth/token` | Invalidates current token, basically the equivalent of a logout. Must authenticate using token in `Authorization` header. |
| `DELETE /api/github/oauth/grant` | Revokes the user's grant, basically the equivalent of an uninstall. must authenticate using token in `Authorization` header. |
### `createNodeMiddleware(app, options)`
Middleware for Node's built in http server or [`express`](https://expressjs.com/).
```js
const { App, createNodeMiddleware } = require("@octokit/app");
const app = new App({
appId: 123,
privateKey: "-----BEGIN PRIVATE KEY-----\n...",
oauth: {
clientId: "0123",
clientSecret: "0123secret",
},
webhooks: {
secret: "secret",
},
});
const middleware = createNodeMiddleware(app);
require("http")
.createServer(async (req, res) => {
// `middleware` returns `false` when `req` is unhandled (beyond `/api/github`)
if (await middleware(req, res)) return;
res.writeHead(404);
res.end();
})
.listen(3000);
// can now receive user authorization callbacks at /api/github/*
```
The middleware returned from `createNodeMiddleware` can also serve as an
`Express.js` middleware directly.
<table width="100%">
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>app</code>
</th>
<th>
<code>App instance</code>
</th>
<td>
<strong>Required</strong>.
</td>
</tr>
<tr>
<th>
<code>options.pathPrefix</code>
</th>
<th>
<code>string</code>
</th>
<td>
All exposed paths will be prefixed with the provided prefix. Defaults to `"/api/github"`
</td>
</tr>
<tr>
<td>
<code>log</code>
<em>
object
</em>
</td>
<td>
Used for internal logging. Defaults to [`console`](https://developer.mozilla.org/en-US/docs/Web/API/console) with `debug` and `info` doing nothing.
</td>
</tr>
</tbody>
</table>
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md)
## License
[MIT](LICENSE)

341
node_modules/@octokit/app/dist-node/index.js generated vendored Normal file
View file

@ -0,0 +1,341 @@
// pkg/dist-src/index.js
import { Octokit as OctokitCore } from "@octokit/core";
import { createAppAuth as createAppAuth3 } from "@octokit/auth-app";
import { OAuthApp } from "@octokit/oauth-app";
// pkg/dist-src/version.js
var VERSION = "15.1.4";
// pkg/dist-src/webhooks.js
import { createAppAuth } from "@octokit/auth-app";
import { createUnauthenticatedAuth } from "@octokit/auth-unauthenticated";
import { Webhooks } from "@octokit/webhooks";
function webhooks(appOctokit, options) {
return new Webhooks({
secret: options.secret,
transform: async (event) => {
if (!("installation" in event.payload) || typeof event.payload.installation !== "object") {
const octokit2 = new appOctokit.constructor({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `"installation" key missing in webhook event payload`
}
});
return {
...event,
octokit: octokit2
};
}
const installationId = event.payload.installation.id;
const octokit = await appOctokit.auth({
type: "installation",
installationId,
factory(auth) {
return new auth.octokit.constructor({
...auth.octokitOptions,
authStrategy: createAppAuth,
...{
auth: {
...auth,
installationId
}
}
});
}
});
octokit.hook.before("request", (options2) => {
options2.headers["x-github-delivery"] = event.id;
});
return {
...event,
octokit
};
}
});
}
// pkg/dist-src/each-installation.js
import { composePaginateRest } from "@octokit/plugin-paginate-rest";
// pkg/dist-src/get-installation-octokit.js
import { createAppAuth as createAppAuth2 } from "@octokit/auth-app";
async function getInstallationOctokit(app, installationId) {
return app.octokit.auth({
type: "installation",
installationId,
factory(auth) {
const options = {
...auth.octokitOptions,
authStrategy: createAppAuth2,
...{ auth: { ...auth, installationId } }
};
return new auth.octokit.constructor(options);
}
});
}
// pkg/dist-src/each-installation.js
function eachInstallationFactory(app) {
return Object.assign(eachInstallation.bind(null, app), {
iterator: eachInstallationIterator.bind(null, app)
});
}
async function eachInstallation(app, callback) {
const i = eachInstallationIterator(app)[Symbol.asyncIterator]();
let result = await i.next();
while (!result.done) {
await callback(result.value);
result = await i.next();
}
}
function eachInstallationIterator(app) {
return {
async *[Symbol.asyncIterator]() {
const iterator = composePaginateRest.iterator(
app.octokit,
"GET /app/installations"
);
for await (const { data: installations } of iterator) {
for (const installation of installations) {
const installationOctokit = await getInstallationOctokit(
app,
installation.id
);
yield { octokit: installationOctokit, installation };
}
}
}
};
}
// pkg/dist-src/each-repository.js
import { composePaginateRest as composePaginateRest2 } from "@octokit/plugin-paginate-rest";
function eachRepositoryFactory(app) {
return Object.assign(eachRepository.bind(null, app), {
iterator: eachRepositoryIterator.bind(null, app)
});
}
async function eachRepository(app, queryOrCallback, callback) {
const i = eachRepositoryIterator(
app,
callback ? queryOrCallback : void 0
)[Symbol.asyncIterator]();
let result = await i.next();
while (!result.done) {
if (callback) {
await callback(result.value);
} else {
await queryOrCallback(result.value);
}
result = await i.next();
}
}
function singleInstallationIterator(app, installationId) {
return {
async *[Symbol.asyncIterator]() {
yield {
octokit: await app.getInstallationOctokit(installationId)
};
}
};
}
function eachRepositoryIterator(app, query) {
return {
async *[Symbol.asyncIterator]() {
const iterator = query ? singleInstallationIterator(app, query.installationId) : app.eachInstallation.iterator();
for await (const { octokit } of iterator) {
const repositoriesIterator = composePaginateRest2.iterator(
octokit,
"GET /installation/repositories"
);
for await (const { data: repositories } of repositoriesIterator) {
for (const repository of repositories) {
yield { octokit, repository };
}
}
}
}
};
}
// pkg/dist-src/get-installation-url.js
function getInstallationUrlFactory(app) {
let installationUrlBasePromise;
return async function getInstallationUrl(options = {}) {
if (!installationUrlBasePromise) {
installationUrlBasePromise = getInstallationUrlBase(app);
}
const installationUrlBase = await installationUrlBasePromise;
const installationUrl = new URL(installationUrlBase);
if (options.target_id !== void 0) {
installationUrl.pathname += "/permissions";
installationUrl.searchParams.append(
"target_id",
options.target_id.toFixed()
);
}
if (options.state !== void 0) {
installationUrl.searchParams.append("state", options.state);
}
return installationUrl.href;
};
}
async function getInstallationUrlBase(app) {
const { data: appInfo } = await app.octokit.request("GET /app");
if (!appInfo) {
throw new Error("[@octokit/app] unable to fetch metadata for app");
}
return `${appInfo.html_url}/installations/new`;
}
// pkg/dist-src/middleware/node/index.js
import {
createNodeMiddleware as oauthNodeMiddleware,
sendNodeResponse,
unknownRouteResponse
} from "@octokit/oauth-app";
import { createNodeMiddleware as webhooksNodeMiddleware } from "@octokit/webhooks";
function noop() {
}
function createNodeMiddleware(app, options = {}) {
const log = Object.assign(
{
debug: noop,
info: noop,
warn: console.warn.bind(console),
error: console.error.bind(console)
},
options.log
);
const optionsWithDefaults = {
pathPrefix: "/api/github",
...options,
log
};
const webhooksMiddleware = webhooksNodeMiddleware(app.webhooks, {
path: optionsWithDefaults.pathPrefix + "/webhooks",
log
});
const oauthMiddleware = oauthNodeMiddleware(app.oauth, {
pathPrefix: optionsWithDefaults.pathPrefix + "/oauth"
});
return middleware.bind(
null,
optionsWithDefaults.pathPrefix,
webhooksMiddleware,
oauthMiddleware
);
}
async function middleware(pathPrefix, webhooksMiddleware, oauthMiddleware, request, response, next) {
const { pathname } = new URL(request.url, "http://localhost");
if (pathname.startsWith(`${pathPrefix}/`)) {
if (pathname === `${pathPrefix}/webhooks`) {
webhooksMiddleware(request, response);
} else if (pathname.startsWith(`${pathPrefix}/oauth/`)) {
oauthMiddleware(request, response);
} else {
sendNodeResponse(unknownRouteResponse(request), response);
}
return true;
} else {
next?.();
return false;
}
}
// pkg/dist-src/index.js
var App = class {
static VERSION = VERSION;
static defaults(defaults) {
const AppWithDefaults = class extends this {
constructor(...args) {
super({
...defaults,
...args[0]
});
}
};
return AppWithDefaults;
}
octokit;
// @ts-ignore calling app.webhooks will throw a helpful error when options.webhooks is not set
webhooks;
// @ts-ignore calling app.oauth will throw a helpful error when options.oauth is not set
oauth;
getInstallationOctokit;
eachInstallation;
eachRepository;
getInstallationUrl;
log;
constructor(options) {
const Octokit = options.Octokit || OctokitCore;
const authOptions = Object.assign(
{
appId: options.appId,
privateKey: options.privateKey
},
options.oauth ? {
clientId: options.oauth.clientId,
clientSecret: options.oauth.clientSecret
} : {}
);
const octokitOptions = {
authStrategy: createAppAuth3,
auth: authOptions
};
if ("log" in options && typeof options.log !== "undefined") {
octokitOptions.log = options.log;
}
this.octokit = new Octokit(octokitOptions);
this.log = Object.assign(
{
debug: () => {
},
info: () => {
},
warn: console.warn.bind(console),
error: console.error.bind(console)
},
options.log
);
if (options.webhooks) {
this.webhooks = webhooks(this.octokit, options.webhooks);
} else {
Object.defineProperty(this, "webhooks", {
get() {
throw new Error("[@octokit/app] webhooks option not set");
}
});
}
if (options.oauth) {
this.oauth = new OAuthApp({
...options.oauth,
clientType: "github-app",
Octokit
});
} else {
Object.defineProperty(this, "oauth", {
get() {
throw new Error(
"[@octokit/app] oauth.clientId / oauth.clientSecret options are not set"
);
}
});
}
this.getInstallationOctokit = getInstallationOctokit.bind(
null,
this
);
this.eachInstallation = eachInstallationFactory(
this
);
this.eachRepository = eachRepositoryFactory(
this
);
this.getInstallationUrl = getInstallationUrlFactory(this);
}
};
export {
App,
createNodeMiddleware
};

7
node_modules/@octokit/app/dist-node/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,39 @@
import { composePaginateRest } from "@octokit/plugin-paginate-rest";
import { getInstallationOctokit } from "./get-installation-octokit.js";
function eachInstallationFactory(app) {
return Object.assign(eachInstallation.bind(null, app), {
iterator: eachInstallationIterator.bind(null, app)
});
}
async function eachInstallation(app, callback) {
const i = eachInstallationIterator(app)[Symbol.asyncIterator]();
let result = await i.next();
while (!result.done) {
await callback(result.value);
result = await i.next();
}
}
function eachInstallationIterator(app) {
return {
async *[Symbol.asyncIterator]() {
const iterator = composePaginateRest.iterator(
app.octokit,
"GET /app/installations"
);
for await (const { data: installations } of iterator) {
for (const installation of installations) {
const installationOctokit = await getInstallationOctokit(
app,
installation.id
);
yield { octokit: installationOctokit, installation };
}
}
}
};
}
export {
eachInstallation,
eachInstallationFactory,
eachInstallationIterator
};

53
node_modules/@octokit/app/dist-src/each-repository.js generated vendored Normal file
View file

@ -0,0 +1,53 @@
import { composePaginateRest } from "@octokit/plugin-paginate-rest";
function eachRepositoryFactory(app) {
return Object.assign(eachRepository.bind(null, app), {
iterator: eachRepositoryIterator.bind(null, app)
});
}
async function eachRepository(app, queryOrCallback, callback) {
const i = eachRepositoryIterator(
app,
callback ? queryOrCallback : void 0
)[Symbol.asyncIterator]();
let result = await i.next();
while (!result.done) {
if (callback) {
await callback(result.value);
} else {
await queryOrCallback(result.value);
}
result = await i.next();
}
}
function singleInstallationIterator(app, installationId) {
return {
async *[Symbol.asyncIterator]() {
yield {
octokit: await app.getInstallationOctokit(installationId)
};
}
};
}
function eachRepositoryIterator(app, query) {
return {
async *[Symbol.asyncIterator]() {
const iterator = query ? singleInstallationIterator(app, query.installationId) : app.eachInstallation.iterator();
for await (const { octokit } of iterator) {
const repositoriesIterator = composePaginateRest.iterator(
octokit,
"GET /installation/repositories"
);
for await (const { data: repositories } of repositoriesIterator) {
for (const repository of repositories) {
yield { octokit, repository };
}
}
}
}
};
}
export {
eachRepository,
eachRepositoryFactory,
eachRepositoryIterator
};

View file

@ -0,0 +1,18 @@
import { createAppAuth } from "@octokit/auth-app";
async function getInstallationOctokit(app, installationId) {
return app.octokit.auth({
type: "installation",
installationId,
factory(auth) {
const options = {
...auth.octokitOptions,
authStrategy: createAppAuth,
...{ auth: { ...auth, installationId } }
};
return new auth.octokit.constructor(options);
}
});
}
export {
getInstallationOctokit
};

View file

@ -0,0 +1,31 @@
function getInstallationUrlFactory(app) {
let installationUrlBasePromise;
return async function getInstallationUrl(options = {}) {
if (!installationUrlBasePromise) {
installationUrlBasePromise = getInstallationUrlBase(app);
}
const installationUrlBase = await installationUrlBasePromise;
const installationUrl = new URL(installationUrlBase);
if (options.target_id !== void 0) {
installationUrl.pathname += "/permissions";
installationUrl.searchParams.append(
"target_id",
options.target_id.toFixed()
);
}
if (options.state !== void 0) {
installationUrl.searchParams.append("state", options.state);
}
return installationUrl.href;
};
}
async function getInstallationUrlBase(app) {
const { data: appInfo } = await app.octokit.request("GET /app");
if (!appInfo) {
throw new Error("[@octokit/app] unable to fetch metadata for app");
}
return `${appInfo.html_url}/installations/new`;
}
export {
getInstallationUrlFactory
};

105
node_modules/@octokit/app/dist-src/index.js generated vendored Normal file
View file

@ -0,0 +1,105 @@
import { Octokit as OctokitCore } from "@octokit/core";
import { createAppAuth } from "@octokit/auth-app";
import { OAuthApp } from "@octokit/oauth-app";
import { VERSION } from "./version.js";
import { webhooks } from "./webhooks.js";
import { eachInstallationFactory } from "./each-installation.js";
import { eachRepositoryFactory } from "./each-repository.js";
import { getInstallationOctokit } from "./get-installation-octokit.js";
import { getInstallationUrlFactory } from "./get-installation-url.js";
class App {
static VERSION = VERSION;
static defaults(defaults) {
const AppWithDefaults = class extends this {
constructor(...args) {
super({
...defaults,
...args[0]
});
}
};
return AppWithDefaults;
}
octokit;
// @ts-ignore calling app.webhooks will throw a helpful error when options.webhooks is not set
webhooks;
// @ts-ignore calling app.oauth will throw a helpful error when options.oauth is not set
oauth;
getInstallationOctokit;
eachInstallation;
eachRepository;
getInstallationUrl;
log;
constructor(options) {
const Octokit = options.Octokit || OctokitCore;
const authOptions = Object.assign(
{
appId: options.appId,
privateKey: options.privateKey
},
options.oauth ? {
clientId: options.oauth.clientId,
clientSecret: options.oauth.clientSecret
} : {}
);
const octokitOptions = {
authStrategy: createAppAuth,
auth: authOptions
};
if ("log" in options && typeof options.log !== "undefined") {
octokitOptions.log = options.log;
}
this.octokit = new Octokit(octokitOptions);
this.log = Object.assign(
{
debug: () => {
},
info: () => {
},
warn: console.warn.bind(console),
error: console.error.bind(console)
},
options.log
);
if (options.webhooks) {
this.webhooks = webhooks(this.octokit, options.webhooks);
} else {
Object.defineProperty(this, "webhooks", {
get() {
throw new Error("[@octokit/app] webhooks option not set");
}
});
}
if (options.oauth) {
this.oauth = new OAuthApp({
...options.oauth,
clientType: "github-app",
Octokit
});
} else {
Object.defineProperty(this, "oauth", {
get() {
throw new Error(
"[@octokit/app] oauth.clientId / oauth.clientSecret options are not set"
);
}
});
}
this.getInstallationOctokit = getInstallationOctokit.bind(
null,
this
);
this.eachInstallation = eachInstallationFactory(
this
);
this.eachRepository = eachRepositoryFactory(
this
);
this.getInstallationUrl = getInstallationUrlFactory(this);
}
}
import { createNodeMiddleware } from "./middleware/node/index.js";
export {
App,
createNodeMiddleware
};

View file

@ -0,0 +1,57 @@
import {
createNodeMiddleware as oauthNodeMiddleware,
sendNodeResponse,
unknownRouteResponse
} from "@octokit/oauth-app";
import { createNodeMiddleware as webhooksNodeMiddleware } from "@octokit/webhooks";
function noop() {
}
function createNodeMiddleware(app, options = {}) {
const log = Object.assign(
{
debug: noop,
info: noop,
warn: console.warn.bind(console),
error: console.error.bind(console)
},
options.log
);
const optionsWithDefaults = {
pathPrefix: "/api/github",
...options,
log
};
const webhooksMiddleware = webhooksNodeMiddleware(app.webhooks, {
path: optionsWithDefaults.pathPrefix + "/webhooks",
log
});
const oauthMiddleware = oauthNodeMiddleware(app.oauth, {
pathPrefix: optionsWithDefaults.pathPrefix + "/oauth"
});
return middleware.bind(
null,
optionsWithDefaults.pathPrefix,
webhooksMiddleware,
oauthMiddleware
);
}
async function middleware(pathPrefix, webhooksMiddleware, oauthMiddleware, request, response, next) {
const { pathname } = new URL(request.url, "http://localhost");
if (pathname.startsWith(`${pathPrefix}/`)) {
if (pathname === `${pathPrefix}/webhooks`) {
webhooksMiddleware(request, response);
} else if (pathname.startsWith(`${pathPrefix}/oauth/`)) {
oauthMiddleware(request, response);
} else {
sendNodeResponse(unknownRouteResponse(request), response);
}
return true;
} else {
next?.();
return false;
}
}
export {
createNodeMiddleware,
middleware
};

4
node_modules/@octokit/app/dist-src/version.js generated vendored Normal file
View file

@ -0,0 +1,4 @@
const VERSION = "15.1.4";
export {
VERSION
};

49
node_modules/@octokit/app/dist-src/webhooks.js generated vendored Normal file
View file

@ -0,0 +1,49 @@
import { createAppAuth } from "@octokit/auth-app";
import { createUnauthenticatedAuth } from "@octokit/auth-unauthenticated";
import { Webhooks } from "@octokit/webhooks";
function webhooks(appOctokit, options) {
return new Webhooks({
secret: options.secret,
transform: async (event) => {
if (!("installation" in event.payload) || typeof event.payload.installation !== "object") {
const octokit2 = new appOctokit.constructor({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `"installation" key missing in webhook event payload`
}
});
return {
...event,
octokit: octokit2
};
}
const installationId = event.payload.installation.id;
const octokit = await appOctokit.auth({
type: "installation",
installationId,
factory(auth) {
return new auth.octokit.constructor({
...auth.octokitOptions,
authStrategy: createAppAuth,
...{
auth: {
...auth,
installationId
}
}
});
}
});
octokit.hook.before("request", (options2) => {
options2.headers["x-github-delivery"] = event.id;
});
return {
...event,
octokit
};
}
});
}
export {
webhooks
};

View file

@ -0,0 +1,122 @@
import type { Octokit } from "@octokit/core";
import type { App } from "./index.js";
import type { EachInstallationFunction, EachInstallationInterface } from "./types.js";
export declare function eachInstallationFactory(app: App): EachInstallationInterface<Octokit>;
export declare function eachInstallation(app: App, callback: EachInstallationFunction<Octokit>): Promise<void>;
export declare function eachInstallationIterator(app: App): {
[Symbol.asyncIterator](): AsyncGenerator<{
octokit: Octokit;
installation: {
id: number;
account: ({
name?: string | null;
email?: string | null;
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string;
} & {
description?: string | null;
html_url: string;
website_url?: string | null;
id: number;
node_id: string;
name: string;
slug: string;
created_at: string | null;
updated_at: string | null;
avatar_url: string;
}) | null;
repository_selection: "all" | "selected";
access_tokens_url: string;
repositories_url: string;
html_url: string;
app_id: number;
target_id: number;
target_type: string;
permissions: {
actions?: "read" | "write";
administration?: "read" | "write";
checks?: "read" | "write";
contents?: "read" | "write";
deployments?: "read" | "write";
environments?: "read" | "write";
issues?: "read" | "write";
metadata?: "read" | "write";
packages?: "read" | "write";
pages?: "read" | "write";
pull_requests?: "read" | "write";
repository_hooks?: "read" | "write";
repository_projects?: "read" | "write" | "admin";
secret_scanning_alerts?: "read" | "write";
secrets?: "read" | "write";
security_events?: "read" | "write";
single_file?: "read" | "write";
statuses?: "read" | "write";
vulnerability_alerts?: "read" | "write";
workflows?: "write";
members?: "read" | "write";
organization_administration?: "read" | "write";
organization_custom_roles?: "read" | "write";
organization_announcement_banners?: "read" | "write";
organization_hooks?: "read" | "write";
organization_personal_access_tokens?: "read" | "write";
organization_personal_access_token_requests?: "read" | "write";
organization_plan?: "read";
organization_projects?: "read" | "write" | "admin";
organization_packages?: "read" | "write";
organization_secrets?: "read" | "write";
organization_self_hosted_runners?: "read" | "write";
organization_user_blocking?: "read" | "write";
team_discussions?: "read" | "write";
};
events: string[];
created_at: string;
updated_at: string;
single_file_name: string | null;
has_multiple_single_files?: boolean;
single_file_paths?: string[];
app_slug: string;
suspended_by: {
name?: string | null;
email?: string | null;
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string | null;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
starred_at?: string;
} | null;
suspended_at: string | null;
contact_email?: string | null;
};
}, void, unknown>;
};

View file

@ -0,0 +1,113 @@
import type { Octokit } from "@octokit/core";
import type { App } from "./index.js";
import type { EachRepositoryFunction, EachRepositoryInterface, EachRepositoryQuery } from "./types.js";
export declare function eachRepositoryFactory(app: App): EachRepositoryInterface<Octokit>;
export declare function eachRepository(app: App, queryOrCallback: EachRepositoryQuery | EachRepositoryFunction<Octokit>, callback?: EachRepositoryFunction<Octokit>): Promise<void>;
export declare function eachRepositoryIterator(app: App, query?: EachRepositoryQuery): {
[Symbol.asyncIterator](): AsyncGenerator<{
octokit: Octokit;
repository: {
id: number;
node_id: string;
name: string;
full_name: string;
license: import("@octokit/openapi-types").components["schemas"]["nullable-license-simple"];
forks: number;
permissions?: {
admin: boolean;
pull: boolean;
triage?: boolean;
push: boolean;
maintain?: boolean;
};
owner: import("@octokit/openapi-types").components["schemas"]["simple-user"];
private: boolean;
html_url: string;
description: string | null;
fork: boolean;
url: string;
archive_url: string;
assignees_url: string;
blobs_url: string;
branches_url: string;
collaborators_url: string;
comments_url: string;
commits_url: string;
compare_url: string;
contents_url: string;
contributors_url: string;
deployments_url: string;
downloads_url: string;
events_url: string;
forks_url: string;
git_commits_url: string;
git_refs_url: string;
git_tags_url: string;
git_url: string;
issue_comment_url: string;
issue_events_url: string;
issues_url: string;
keys_url: string;
labels_url: string;
languages_url: string;
merges_url: string;
milestones_url: string;
notifications_url: string;
pulls_url: string;
releases_url: string;
ssh_url: string;
stargazers_url: string;
statuses_url: string;
subscribers_url: string;
subscription_url: string;
tags_url: string;
teams_url: string;
trees_url: string;
clone_url: string;
mirror_url: string | null;
hooks_url: string;
svn_url: string;
homepage: string | null;
language: string | null;
forks_count: number;
stargazers_count: number;
watchers_count: number;
size: number;
default_branch: string;
open_issues_count: number;
is_template?: boolean;
topics?: string[];
has_issues: boolean;
has_projects: boolean;
has_wiki: boolean;
has_pages: boolean;
has_downloads: boolean;
has_discussions?: boolean;
archived: boolean;
disabled: boolean;
visibility?: string;
pushed_at: string | null;
created_at: string | null;
updated_at: string | null;
allow_rebase_merge?: boolean;
temp_clone_token?: string;
allow_squash_merge?: boolean;
allow_auto_merge?: boolean;
delete_branch_on_merge?: boolean;
allow_update_branch?: boolean;
use_squash_pr_title_as_default?: boolean;
squash_merge_commit_title?: "PR_TITLE" | "COMMIT_OR_PR_TITLE";
squash_merge_commit_message?: "PR_BODY" | "COMMIT_MESSAGES" | "BLANK";
merge_commit_title?: "PR_TITLE" | "MERGE_MESSAGE";
merge_commit_message?: "PR_BODY" | "PR_TITLE" | "BLANK";
allow_merge_commit?: boolean;
allow_forking?: boolean;
web_commit_signoff_required?: boolean;
open_issues: number;
watchers: number;
master_branch?: string;
starred_at?: string;
anonymous_access_enabled?: boolean;
};
}, void, unknown>;
};

View file

@ -0,0 +1,3 @@
import type { Octokit } from "@octokit/core";
import type { App } from "./index.js";
export declare function getInstallationOctokit(app: App, installationId: number): Promise<Octokit>;

View file

@ -0,0 +1,3 @@
import type { App } from "./index.js";
import type { GetInstallationUrlOptions } from "./types.js";
export declare function getInstallationUrlFactory(app: App): (options?: GetInstallationUrlOptions) => Promise<string>;

55
node_modules/@octokit/app/dist-types/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,55 @@
import { Octokit as OctokitCore } from "@octokit/core";
import { OAuthApp } from "@octokit/oauth-app";
import type { Webhooks } from "@octokit/webhooks";
import type { Options, ConstructorOptions, EachInstallationInterface, EachRepositoryInterface, GetInstallationOctokitInterface, GetInstallationUrlInterface } from "./types.js";
export type { EachInstallationInterface, EachRepositoryInterface, GetInstallationOctokitInterface, GetInstallationUrlInterface, } from "./types.js";
type Constructor<T> = new (...args: any[]) => T;
type OctokitType<TOptions extends Options> = TOptions["Octokit"] extends typeof OctokitCore ? InstanceType<TOptions["Octokit"]> : OctokitCore;
type OctokitClassType<TOptions extends Options> = TOptions["Octokit"] extends typeof OctokitCore ? TOptions["Octokit"] : typeof OctokitCore;
export declare class App<TOptions extends Options = Options> {
static VERSION: string;
static defaults<TDefaults extends Options, S extends Constructor<App<TDefaults>>>(this: S, defaults: Partial<TDefaults>): ({
new (...args: any[]): {
octokit: OctokitType<TDefaults>;
webhooks: Webhooks<{
octokit: OctokitType<TDefaults>;
}>;
oauth: OAuthApp<{
clientType: "github-app";
Octokit: OctokitClassType<TDefaults>;
}>;
getInstallationOctokit: GetInstallationOctokitInterface<OctokitType<TDefaults>>;
eachInstallation: EachInstallationInterface<OctokitType<TDefaults>>;
eachRepository: EachRepositoryInterface<OctokitType<TDefaults>>;
getInstallationUrl: GetInstallationUrlInterface;
log: {
debug: (message: string, additionalInfo?: object) => void;
info: (message: string, additionalInfo?: object) => void;
warn: (message: string, additionalInfo?: object) => void;
error: (message: string, additionalInfo?: object) => void;
[key: string]: unknown;
};
};
} & S) & typeof this;
octokit: OctokitType<TOptions>;
webhooks: Webhooks<{
octokit: OctokitType<TOptions>;
}>;
oauth: OAuthApp<{
clientType: "github-app";
Octokit: OctokitClassType<TOptions>;
}>;
getInstallationOctokit: GetInstallationOctokitInterface<OctokitType<TOptions>>;
eachInstallation: EachInstallationInterface<OctokitType<TOptions>>;
eachRepository: EachRepositoryInterface<OctokitType<TOptions>>;
getInstallationUrl: GetInstallationUrlInterface;
log: {
debug: (message: string, additionalInfo?: object) => void;
info: (message: string, additionalInfo?: object) => void;
warn: (message: string, additionalInfo?: object) => void;
error: (message: string, additionalInfo?: object) => void;
[key: string]: unknown;
};
constructor(options: ConstructorOptions<TOptions>);
}
export { createNodeMiddleware } from "./middleware/node/index.js";

View file

@ -0,0 +1,11 @@
type IncomingMessage = any;
type ServerResponse = any;
import type { App } from "../../index.js";
import type { Options } from "../../types.js";
export type MiddlewareOptions = {
pathPrefix?: string;
log?: Options["log"];
};
export declare function createNodeMiddleware(app: App, options?: MiddlewareOptions): (request: any, response: any, next?: Function | undefined) => Promise<boolean>;
export declare function middleware(pathPrefix: string, webhooksMiddleware: any, oauthMiddleware: any, request: IncomingMessage, response: ServerResponse, next?: Function): Promise<boolean>;
export {};

58
node_modules/@octokit/app/dist-types/types.d.ts generated vendored Normal file
View file

@ -0,0 +1,58 @@
import type { Octokit } from "@octokit/core";
import type { Endpoints } from "@octokit/types";
export type Options = {
appId?: number | string;
privateKey?: string;
webhooks?: {
secret: string;
};
oauth?: {
clientId: string;
clientSecret: string;
allowSignup?: boolean;
};
Octokit?: typeof Octokit;
log?: {
debug: (...data: any[]) => void;
info: (...data: any[]) => void;
warn: (...data: any[]) => void;
error: (...data: any[]) => void;
};
};
export type ConstructorOptions<TOptions extends Options> = TOptions & {
appId: number | string;
privateKey: string;
};
export type InstallationFunctionOptions<O> = {
octokit: O;
installation: Endpoints["GET /app/installations"]["response"]["data"][0];
};
export type EachInstallationFunction<O> = (options: InstallationFunctionOptions<O>) => unknown | Promise<unknown>;
export interface EachInstallationInterface<O> {
(callback: EachInstallationFunction<O>): Promise<void>;
iterator: () => AsyncIterable<InstallationFunctionOptions<O>>;
}
type EachRepositoryFunctionOptions<O> = {
octokit: O;
repository: Endpoints["GET /installation/repositories"]["response"]["data"]["repositories"][0];
};
export type EachRepositoryFunction<O> = (options: EachRepositoryFunctionOptions<O>) => unknown | Promise<unknown>;
export type EachRepositoryQuery = {
installationId: number;
};
export interface EachRepositoryInterface<O> {
(callback: EachRepositoryFunction<O>): Promise<void>;
(query: EachRepositoryQuery, callback: EachRepositoryFunction<O>): Promise<void>;
iterator: (query?: EachRepositoryQuery) => AsyncIterable<EachRepositoryFunctionOptions<O>>;
}
export interface GetInstallationOctokitInterface<O> {
(installationId: number): Promise<O>;
}
export interface GetInstallationUrlOptions {
state?: string;
target_id?: number;
}
export interface GetInstallationUrlInterface {
(options?: GetInstallationUrlOptions): Promise<string>;
}
export {};

1
node_modules/@octokit/app/dist-types/version.d.ts generated vendored Normal file
View file

@ -0,0 +1 @@
export declare const VERSION = "15.1.4";

6
node_modules/@octokit/app/dist-types/webhooks.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
import type { Octokit } from "@octokit/core";
import { Webhooks, type EmitterWebhookEvent } from "@octokit/webhooks";
import type { Options } from "./types.js";
export declare function webhooks(appOctokit: Octokit, options: Required<Options>["webhooks"]): Webhooks<EmitterWebhookEvent & {
octokit: Octokit;
}>;

341
node_modules/@octokit/app/dist-web/index.js generated vendored Normal file
View file

@ -0,0 +1,341 @@
// pkg/dist-src/index.js
import { Octokit as OctokitCore } from "@octokit/core";
import { createAppAuth as createAppAuth3 } from "@octokit/auth-app";
import { OAuthApp } from "@octokit/oauth-app";
// pkg/dist-src/version.js
var VERSION = "15.1.4";
// pkg/dist-src/webhooks.js
import { createAppAuth } from "@octokit/auth-app";
import { createUnauthenticatedAuth } from "@octokit/auth-unauthenticated";
import { Webhooks } from "@octokit/webhooks";
function webhooks(appOctokit, options) {
return new Webhooks({
secret: options.secret,
transform: async (event) => {
if (!("installation" in event.payload) || typeof event.payload.installation !== "object") {
const octokit2 = new appOctokit.constructor({
authStrategy: createUnauthenticatedAuth,
auth: {
reason: `"installation" key missing in webhook event payload`
}
});
return {
...event,
octokit: octokit2
};
}
const installationId = event.payload.installation.id;
const octokit = await appOctokit.auth({
type: "installation",
installationId,
factory(auth) {
return new auth.octokit.constructor({
...auth.octokitOptions,
authStrategy: createAppAuth,
...{
auth: {
...auth,
installationId
}
}
});
}
});
octokit.hook.before("request", (options2) => {
options2.headers["x-github-delivery"] = event.id;
});
return {
...event,
octokit
};
}
});
}
// pkg/dist-src/each-installation.js
import { composePaginateRest } from "@octokit/plugin-paginate-rest";
// pkg/dist-src/get-installation-octokit.js
import { createAppAuth as createAppAuth2 } from "@octokit/auth-app";
async function getInstallationOctokit(app, installationId) {
return app.octokit.auth({
type: "installation",
installationId,
factory(auth) {
const options = {
...auth.octokitOptions,
authStrategy: createAppAuth2,
...{ auth: { ...auth, installationId } }
};
return new auth.octokit.constructor(options);
}
});
}
// pkg/dist-src/each-installation.js
function eachInstallationFactory(app) {
return Object.assign(eachInstallation.bind(null, app), {
iterator: eachInstallationIterator.bind(null, app)
});
}
async function eachInstallation(app, callback) {
const i = eachInstallationIterator(app)[Symbol.asyncIterator]();
let result = await i.next();
while (!result.done) {
await callback(result.value);
result = await i.next();
}
}
function eachInstallationIterator(app) {
return {
async *[Symbol.asyncIterator]() {
const iterator = composePaginateRest.iterator(
app.octokit,
"GET /app/installations"
);
for await (const { data: installations } of iterator) {
for (const installation of installations) {
const installationOctokit = await getInstallationOctokit(
app,
installation.id
);
yield { octokit: installationOctokit, installation };
}
}
}
};
}
// pkg/dist-src/each-repository.js
import { composePaginateRest as composePaginateRest2 } from "@octokit/plugin-paginate-rest";
function eachRepositoryFactory(app) {
return Object.assign(eachRepository.bind(null, app), {
iterator: eachRepositoryIterator.bind(null, app)
});
}
async function eachRepository(app, queryOrCallback, callback) {
const i = eachRepositoryIterator(
app,
callback ? queryOrCallback : void 0
)[Symbol.asyncIterator]();
let result = await i.next();
while (!result.done) {
if (callback) {
await callback(result.value);
} else {
await queryOrCallback(result.value);
}
result = await i.next();
}
}
function singleInstallationIterator(app, installationId) {
return {
async *[Symbol.asyncIterator]() {
yield {
octokit: await app.getInstallationOctokit(installationId)
};
}
};
}
function eachRepositoryIterator(app, query) {
return {
async *[Symbol.asyncIterator]() {
const iterator = query ? singleInstallationIterator(app, query.installationId) : app.eachInstallation.iterator();
for await (const { octokit } of iterator) {
const repositoriesIterator = composePaginateRest2.iterator(
octokit,
"GET /installation/repositories"
);
for await (const { data: repositories } of repositoriesIterator) {
for (const repository of repositories) {
yield { octokit, repository };
}
}
}
}
};
}
// pkg/dist-src/get-installation-url.js
function getInstallationUrlFactory(app) {
let installationUrlBasePromise;
return async function getInstallationUrl(options = {}) {
if (!installationUrlBasePromise) {
installationUrlBasePromise = getInstallationUrlBase(app);
}
const installationUrlBase = await installationUrlBasePromise;
const installationUrl = new URL(installationUrlBase);
if (options.target_id !== void 0) {
installationUrl.pathname += "/permissions";
installationUrl.searchParams.append(
"target_id",
options.target_id.toFixed()
);
}
if (options.state !== void 0) {
installationUrl.searchParams.append("state", options.state);
}
return installationUrl.href;
};
}
async function getInstallationUrlBase(app) {
const { data: appInfo } = await app.octokit.request("GET /app");
if (!appInfo) {
throw new Error("[@octokit/app] unable to fetch metadata for app");
}
return `${appInfo.html_url}/installations/new`;
}
// pkg/dist-src/middleware/node/index.js
import {
createNodeMiddleware as oauthNodeMiddleware,
sendNodeResponse,
unknownRouteResponse
} from "@octokit/oauth-app";
import { createNodeMiddleware as webhooksNodeMiddleware } from "@octokit/webhooks";
function noop() {
}
function createNodeMiddleware(app, options = {}) {
const log = Object.assign(
{
debug: noop,
info: noop,
warn: console.warn.bind(console),
error: console.error.bind(console)
},
options.log
);
const optionsWithDefaults = {
pathPrefix: "/api/github",
...options,
log
};
const webhooksMiddleware = webhooksNodeMiddleware(app.webhooks, {
path: optionsWithDefaults.pathPrefix + "/webhooks",
log
});
const oauthMiddleware = oauthNodeMiddleware(app.oauth, {
pathPrefix: optionsWithDefaults.pathPrefix + "/oauth"
});
return middleware.bind(
null,
optionsWithDefaults.pathPrefix,
webhooksMiddleware,
oauthMiddleware
);
}
async function middleware(pathPrefix, webhooksMiddleware, oauthMiddleware, request, response, next) {
const { pathname } = new URL(request.url, "http://localhost");
if (pathname.startsWith(`${pathPrefix}/`)) {
if (pathname === `${pathPrefix}/webhooks`) {
webhooksMiddleware(request, response);
} else if (pathname.startsWith(`${pathPrefix}/oauth/`)) {
oauthMiddleware(request, response);
} else {
sendNodeResponse(unknownRouteResponse(request), response);
}
return true;
} else {
next?.();
return false;
}
}
// pkg/dist-src/index.js
var App = class {
static VERSION = VERSION;
static defaults(defaults) {
const AppWithDefaults = class extends this {
constructor(...args) {
super({
...defaults,
...args[0]
});
}
};
return AppWithDefaults;
}
octokit;
// @ts-ignore calling app.webhooks will throw a helpful error when options.webhooks is not set
webhooks;
// @ts-ignore calling app.oauth will throw a helpful error when options.oauth is not set
oauth;
getInstallationOctokit;
eachInstallation;
eachRepository;
getInstallationUrl;
log;
constructor(options) {
const Octokit = options.Octokit || OctokitCore;
const authOptions = Object.assign(
{
appId: options.appId,
privateKey: options.privateKey
},
options.oauth ? {
clientId: options.oauth.clientId,
clientSecret: options.oauth.clientSecret
} : {}
);
const octokitOptions = {
authStrategy: createAppAuth3,
auth: authOptions
};
if ("log" in options && typeof options.log !== "undefined") {
octokitOptions.log = options.log;
}
this.octokit = new Octokit(octokitOptions);
this.log = Object.assign(
{
debug: () => {
},
info: () => {
},
warn: console.warn.bind(console),
error: console.error.bind(console)
},
options.log
);
if (options.webhooks) {
this.webhooks = webhooks(this.octokit, options.webhooks);
} else {
Object.defineProperty(this, "webhooks", {
get() {
throw new Error("[@octokit/app] webhooks option not set");
}
});
}
if (options.oauth) {
this.oauth = new OAuthApp({
...options.oauth,
clientType: "github-app",
Octokit
});
} else {
Object.defineProperty(this, "oauth", {
get() {
throw new Error(
"[@octokit/app] oauth.clientId / oauth.clientSecret options are not set"
);
}
});
}
this.getInstallationOctokit = getInstallationOctokit.bind(
null,
this
);
this.eachInstallation = eachInstallationFactory(
this
);
this.eachRepository = eachRepositoryFactory(
this
);
this.getInstallationUrl = getInstallationUrlFactory(this);
}
};
export {
App,
createNodeMiddleware
};

7
node_modules/@octokit/app/dist-web/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,284 @@
# auth-token.js
> GitHub API token authentication for browsers and Node.js
[![@latest](https://img.shields.io/npm/v/@octokit/auth-token.svg)](https://www.npmjs.com/package/@octokit/auth-token)
[![Build Status](https://github.com/octokit/auth-token.js/workflows/Test/badge.svg)](https://github.com/octokit/auth-token.js/actions?query=workflow%3ATest)
`@octokit/auth-token` is the simplest of [GitHubs authentication strategies](https://github.com/octokit/auth.js).
It is useful if you want to support multiple authentication strategies, as its API is compatible with its sibling packages for [basic](https://github.com/octokit/auth-basic.js), [GitHub App](https://github.com/octokit/auth-app.js) and [OAuth app](https://github.com/octokit/auth.js) authentication.
<!-- toc -->
- [Usage](#usage)
- [`createTokenAuth(token) options`](#createtokenauthtoken-options)
- [`auth()`](#auth)
- [Authentication object](#authentication-object)
- [`auth.hook(request, route, options)` or `auth.hook(request, options)`](#authhookrequest-route-options-or-authhookrequest-options)
- [Find more information](#find-more-information)
- [Find out what scopes are enabled for oauth tokens](#find-out-what-scopes-are-enabled-for-oauth-tokens)
- [Find out if token is a personal access token or if it belongs to an OAuth app](#find-out-if-token-is-a-personal-access-token-or-if-it-belongs-to-an-oauth-app)
- [Find out what permissions are enabled for a repository](#find-out-what-permissions-are-enabled-for-a-repository)
- [Use token for git operations](#use-token-for-git-operations)
- [License](#license)
<!-- tocstop -->
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
Load `@octokit/auth-token` directly from [esm.sh](https://esm.sh)
```html
<script type="module">
import { createTokenAuth } from "https://esm.sh/@octokit/auth-token";
</script>
```
</td></tr>
<tr><th>
Node
</th><td>
Install with <code>npm install @octokit/auth-token</code>
```js
import { createTokenAuth } from "@octokit/auth-token";
```
</td></tr>
</tbody>
</table>
```js
const auth = createTokenAuth("ghp_PersonalAccessToken01245678900000000");
const authentication = await auth();
// {
// type: 'token',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
```
## `createTokenAuth(token) options`
The `createTokenAuth` method accepts a single argument of type string, which is the token. The passed token can be one of the following:
- [Personal access token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line)
- [OAuth access token](https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/)
- [GITHUB_TOKEN provided to GitHub Actions](https://developer.github.com/actions/creating-github-actions/accessing-the-runtime-environment/#environment-variables)
- Installation access token ([server-to-server](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation))
- User authentication for installation ([user-to-server](https://docs.github.com/en/developers/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps))
Examples
```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'
// }
```
## `auth()`
The `auth()` method has no options. It returns a promise which resolves with the the authentication object.
## Authentication object
<table width="100%">
<thead align=left>
<tr>
<th width=150>
name
</th>
<th width=70>
type
</th>
<th>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>type</code>
</th>
<th>
<code>string</code>
</th>
<td>
<code>"token"</code>
</td>
</tr>
<tr>
<th>
<code>token</code>
</th>
<th>
<code>string</code>
</th>
<td>
The provided token.
</td>
</tr>
<tr>
<th>
<code>tokenType</code>
</th>
<th>
<code>string</code>
</th>
<td>
Can be either <code>"oauth"</code> for personal access tokens and OAuth tokens, <code>"installation"</code> for installation access tokens (includes <code>GITHUB_TOKEN</code> provided to GitHub Actions), <code>"app"</code> for a GitHub App JSON Web Token, or <code>"user-to-server"</code> for a user authentication token through an app installation.
</td>
</tr>
</tbody>
</table>
## `auth.hook(request, route, options)` or `auth.hook(request, options)`
`auth.hook()` hooks directly into the request life cycle. It authenticates the request using the provided token.
The `request` option is an instance of [`@octokit/request`](https://github.com/octokit/request.js#readme). The `route`/`options` parameters are the same as for the [`request()` method](https://github.com/octokit/request.js#request).
`auth.hook()` can be called directly to send an authenticated request
```js
const { data: authorizations } = await auth.hook(
request,
"GET /authorizations",
);
```
Or it can be passed as option to [`request()`](https://github.com/octokit/request.js#request).
```js
const requestWithAuth = request.defaults({
request: {
hook: auth.hook,
},
});
const { data: authorizations } = await requestWithAuth("GET /authorizations");
```
## Find more information
`auth()` does not send any requests, it only transforms the provided token string into an authentication object.
Here is a list of things you can do to retrieve further information
### Find out what scopes are enabled for oauth tokens
Note that this does not work for installations. There is no way to retrieve permissions based on an installation access tokens.
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("HEAD /");
const scopes = response.headers["x-oauth-scopes"].split(/,\s+/);
if (scopes.length) {
console.log(
`"${TOKEN}" has ${scopes.length} scopes enabled: ${scopes.join(", ")}`,
);
} else {
console.log(`"${TOKEN}" has no scopes enabled`);
}
```
### Find out if token is a personal access token or if it belongs to an OAuth app
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("HEAD /");
const clientId = response.headers["x-oauth-client-id"];
if (clientId) {
console.log(
`"${token}" is an OAuth token, its apps client_id is ${clientId}.`,
);
} else {
console.log(`"${token}" is a personal access token`);
}
```
### Find out what permissions are enabled for a repository
Note that 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",
});
console.log(response.data.permissions);
// {
// admin: true,
// push: true,
// pull: true
// }
```
### Use token for git operations
Both OAuth and installation access tokens can be used for git operations. However, when using with an installation, [the token must be prefixed with `x-access-token`](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation).
This example is using the [`execa`](https://github.com/sindresorhus/execa) package to run a `git push` command.
```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);
```
## License
[MIT](LICENSE)

View file

@ -0,0 +1,55 @@
// pkg/dist-src/is-jwt.js
var b64url = "(?:[a-zA-Z0-9_-]+)";
var sep = "\\.";
var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);
var isJWT = jwtRE.test.bind(jwtRE);
// pkg/dist-src/auth.js
async function auth(token) {
const isApp = isJWT(token);
const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_");
const isUserToServer = token.startsWith("ghu_");
const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
return {
type: "token",
token,
tokenType
};
}
// pkg/dist-src/with-authorization-prefix.js
function withAuthorizationPrefix(token) {
if (token.split(/\./).length === 3) {
return `bearer ${token}`;
}
return `token ${token}`;
}
// pkg/dist-src/hook.js
async function hook(token, request, route, parameters) {
const endpoint = request.endpoint.merge(
route,
parameters
);
endpoint.headers.authorization = withAuthorizationPrefix(token);
return request(endpoint);
}
// pkg/dist-src/index.js
var createTokenAuth = function createTokenAuth2(token) {
if (!token) {
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
}
if (typeof token !== "string") {
throw new Error(
"[@octokit/auth-token] Token passed to createTokenAuth is not a string"
);
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token)
});
};
export {
createTokenAuth
};

View file

@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../dist-src/is-jwt.js", "../dist-src/auth.js", "../dist-src/with-authorization-prefix.js", "../dist-src/hook.js", "../dist-src/index.js"],
"sourcesContent": ["const b64url = \"(?:[a-zA-Z0-9_-]+)\";\nconst sep = \"\\\\.\";\nconst jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);\nconst isJWT = jwtRE.test.bind(jwtRE);\nexport {\n isJWT\n};\n", "import { isJWT } from \"./is-jwt.js\";\nasync function auth(token) {\n const isApp = isJWT(token);\n const isInstallation = token.startsWith(\"v1.\") || token.startsWith(\"ghs_\");\n const isUserToServer = token.startsWith(\"ghu_\");\n const tokenType = isApp ? \"app\" : isInstallation ? \"installation\" : isUserToServer ? \"user-to-server\" : \"oauth\";\n return {\n type: \"token\",\n token,\n tokenType\n };\n}\nexport {\n auth\n};\n", "function withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\nexport {\n withAuthorizationPrefix\n};\n", "import { withAuthorizationPrefix } from \"./with-authorization-prefix.js\";\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(\n route,\n parameters\n );\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\nexport {\n hook\n};\n", "import { auth } from \"./auth.js\";\nimport { hook } from \"./hook.js\";\nconst createTokenAuth = function createTokenAuth2(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\n \"[@octokit/auth-token] Token passed to createTokenAuth is not a string\"\n );\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\nexport {\n createTokenAuth\n};\n"],
"mappings": ";AAAA,IAAM,SAAS;AACf,IAAM,MAAM;AACZ,IAAM,QAAQ,IAAI,OAAO,IAAI,MAAM,GAAG,GAAG,GAAG,MAAM,GAAG,GAAG,GAAG,MAAM,GAAG;AACpE,IAAM,QAAQ,MAAM,KAAK,KAAK,KAAK;;;ACFnC,eAAe,KAAK,OAAO;AACzB,QAAM,QAAQ,MAAM,KAAK;AACzB,QAAM,iBAAiB,MAAM,WAAW,KAAK,KAAK,MAAM,WAAW,MAAM;AACzE,QAAM,iBAAiB,MAAM,WAAW,MAAM;AAC9C,QAAM,YAAY,QAAQ,QAAQ,iBAAiB,iBAAiB,iBAAiB,mBAAmB;AACxG,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF;AACF;;;ACXA,SAAS,wBAAwB,OAAO;AACtC,MAAI,MAAM,MAAM,IAAI,EAAE,WAAW,GAAG;AAClC,WAAO,UAAU,KAAK;AAAA,EACxB;AACA,SAAO,SAAS,KAAK;AACvB;;;ACJA,eAAe,KAAK,OAAO,SAAS,OAAO,YAAY;AACrD,QAAM,WAAW,QAAQ,SAAS;AAAA,IAChC;AAAA,IACA;AAAA,EACF;AACA,WAAS,QAAQ,gBAAgB,wBAAwB,KAAK;AAC9D,SAAO,QAAQ,QAAQ;AACzB;;;ACNA,IAAM,kBAAkB,SAAS,iBAAiB,OAAO;AACvD,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,0DAA0D;AAAA,EAC5E;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,UAAQ,MAAM,QAAQ,sBAAsB,EAAE;AAC9C,SAAO,OAAO,OAAO,KAAK,KAAK,MAAM,KAAK,GAAG;AAAA,IAC3C,MAAM,KAAK,KAAK,MAAM,KAAK;AAAA,EAC7B,CAAC;AACH;",
"names": []
}

View file

@ -0,0 +1,15 @@
import { isJWT } from "./is-jwt.js";
async function auth(token) {
const isApp = isJWT(token);
const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_");
const isUserToServer = token.startsWith("ghu_");
const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
return {
type: "token",
token,
tokenType
};
}
export {
auth
};

View file

@ -0,0 +1,12 @@
import { withAuthorizationPrefix } from "./with-authorization-prefix.js";
async function hook(token, request, route, parameters) {
const endpoint = request.endpoint.merge(
route,
parameters
);
endpoint.headers.authorization = withAuthorizationPrefix(token);
return request(endpoint);
}
export {
hook
};

View file

@ -0,0 +1,19 @@
import { auth } from "./auth.js";
import { hook } from "./hook.js";
const createTokenAuth = function createTokenAuth2(token) {
if (!token) {
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
}
if (typeof token !== "string") {
throw new Error(
"[@octokit/auth-token] Token passed to createTokenAuth is not a string"
);
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token)
});
};
export {
createTokenAuth
};

View file

@ -0,0 +1,7 @@
const b64url = "(?:[a-zA-Z0-9_-]+)";
const sep = "\\.";
const jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);
const isJWT = jwtRE.test.bind(jwtRE);
export {
isJWT
};

View file

@ -0,0 +1,9 @@
function withAuthorizationPrefix(token) {
if (token.split(/\./).length === 3) {
return `bearer ${token}`;
}
return `token ${token}`;
}
export {
withAuthorizationPrefix
};

View file

@ -0,0 +1,2 @@
import type { Token, Authentication } from "./types.js";
export declare function auth(token: Token): Promise<Authentication>;

View file

@ -0,0 +1,2 @@
import type { AnyResponse, EndpointOptions, RequestInterface, RequestParameters, Route, Token } from "./types.js";
export declare function hook(token: Token, request: RequestInterface, route: Route | EndpointOptions, parameters?: RequestParameters): Promise<AnyResponse>;

View file

@ -0,0 +1,7 @@
import type { StrategyInterface, Token, Authentication } from "./types.js";
export type Types = {
StrategyOptions: Token;
AuthOptions: never;
Authentication: Authentication;
};
export declare const createTokenAuth: StrategyInterface;

View file

@ -0,0 +1 @@
export declare const isJWT: (string: string) => boolean;

View file

@ -0,0 +1,33 @@
import type * as OctokitTypes from "@octokit/types";
export type AnyResponse = OctokitTypes.OctokitResponse<any>;
export type StrategyInterface = OctokitTypes.StrategyInterface<[
Token
], [
], Authentication>;
export type EndpointDefaults = OctokitTypes.EndpointDefaults;
export type EndpointOptions = OctokitTypes.EndpointOptions;
export type RequestParameters = OctokitTypes.RequestParameters;
export type RequestInterface = OctokitTypes.RequestInterface;
export type Route = OctokitTypes.Route;
export type Token = string;
export type OAuthTokenAuthentication = {
type: "token";
tokenType: "oauth";
token: Token;
};
export type InstallationTokenAuthentication = {
type: "token";
tokenType: "installation";
token: Token;
};
export type AppAuthentication = {
type: "token";
tokenType: "app";
token: Token;
};
export type UserToServerAuthentication = {
type: "token";
tokenType: "user-to-server";
token: Token;
};
export type Authentication = OAuthTokenAuthentication | InstallationTokenAuthentication | AppAuthentication | UserToServerAuthentication;

View file

@ -0,0 +1,6 @@
/**
* Prefix token for usage in the Authorization header
*
* @param token OAuth token or JSON Web Token
*/
export declare function withAuthorizationPrefix(token: string): string;

View file

@ -0,0 +1,51 @@
{
"name": "@octokit/auth-token",
"publishConfig": {
"access": "public",
"provenance": true
},
"type": "module",
"version": "5.1.2",
"description": "GitHub API token authentication for browsers and Node.js",
"repository": "github:octokit/auth-token.js",
"keywords": [
"github",
"octokit",
"authentication",
"api"
],
"author": "Gregor Martynus (https://github.com/gr2m)",
"license": "MIT",
"devDependencies": {
"@octokit/request": "^9.0.0",
"@octokit/tsconfig": "^4.0.0",
"@octokit/types": "^13.0.0",
"@vitest/coverage-v8": "^3.0.0",
"esbuild": "^0.24.0",
"fetch-mock": "^11.0.0",
"glob": "^11.0.0",
"prettier": "3.4.2",
"semantic-release": "^24.0.0",
"typescript": "^5.3.0",
"vitest": "^3.0.0"
},
"engines": {
"node": ">= 18"
},
"files": [
"dist-*/**",
"bin/**"
],
"types": "./dist-types/index.d.ts",
"exports": {
".": {
"types": "./dist-types/index.d.ts",
"import": "./dist-bundle/index.js",
"default": "./dist-bundle/index.js"
},
"./types": {
"types": "./dist-types/index.d.ts"
}
},
"sideEffects": false
}

View file

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,457 @@
# core.js
> Extendable client for GitHub's REST & GraphQL APIs
[![@latest](https://img.shields.io/npm/v/@octokit/core.svg)](https://www.npmjs.com/package/@octokit/core)
[![Build Status](https://github.com/octokit/core.js/workflows/Test/badge.svg)](https://github.com/octokit/core.js/actions?query=workflow%3ATest+branch%3Amain)
<!-- toc -->
- [Usage](#usage)
- [REST API example](#rest-api-example)
- [GraphQL example](#graphql-example)
- [Options](#options)
- [Defaults](#defaults)
- [Authentication](#authentication)
- [Logging](#logging)
- [Hooks](#hooks)
- [Plugins](#plugins)
- [Build your own Octokit with Plugins and Defaults](#build-your-own-octokit-with-plugins-and-defaults)
- [LICENSE](#license)
<!-- tocstop -->
If you need a minimalistic library to utilize GitHub's [REST API](https://developer.github.com/v3/) and [GraphQL API](https://developer.github.com/v4/) which you can extend with plugins as needed, then `@octokit/core` is a great starting point.
If you don't need the Plugin API then using [`@octokit/request`](https://github.com/octokit/request.js/) or [`@octokit/graphql`](https://github.com/octokit/graphql.js/) directly is a good alternative.
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
Load <code>@octokit/core</code> directly from <a href="https://esm.sh">esm.sh</a>
```html
<script type="module">
import { Octokit } from "https://esm.sh/@octokit/core";
</script>
```
</td></tr>
<tr><th>
Node
</th><td>
Install with <code>npm install @octokit/core</code>
```js
import { Octokit } from "@octokit/core";
```
</td></tr>
</tbody>
</table>
As we use [conditional exports](https://nodejs.org/api/packages.html#conditional-exports), you will need to adapt your `tsconfig.json`. See the TypeScript docs on [package.json "exports"](https://www.typescriptlang.org/docs/handbook/modules/reference.html#packagejson-exports).
### REST API example
```js
// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo
const octokit = new Octokit({ auth: `personal-access-token123` });
const response = await octokit.request("GET /orgs/{org}/repos", {
org: "octokit",
type: "private",
});
```
See [`@octokit/request`](https://github.com/octokit/request.js) for full documentation of the `.request` method.
### GraphQL example
```js
const octokit = new Octokit({ auth: `secret123` });
const response = await octokit.graphql(
`query ($login: String!) {
organization(login: $login) {
repositories(privacy: PRIVATE) {
totalCount
}
}
}`,
{ login: "octokit" },
);
```
See [`@octokit/graphql`](https://github.com/octokit/graphql.js) for full documentation of the `.graphql` method.
## Options
<table>
<thead align=left>
<tr>
<th>
name
</th>
<th>
type
</th>
<th width=100%>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>options.authStrategy</code>
</th>
<td>
<code>Function<code>
</td>
<td>
Defaults to <a href="https://github.com/octokit/auth-token.js#readme"><code>@octokit/auth-token</code></a>. See <a href="#authentication">Authentication</a> below for examples.
</td>
</tr>
<tr>
<th>
<code>options.auth</code>
</th>
<td>
<code>String</code> or <code>Object</code>
</td>
<td>
See <a href="#authentication">Authentication</a> below for examples.
</td>
</tr>
<tr>
<th>
<code>options.baseUrl</code>
</th>
<td>
<code>String</code>
</td>
<td>
When using with GitHub Enterprise Server, set `options.baseUrl` to the root URL of the API. For example, if your GitHub Enterprise Server's hostname is `github.acme-inc.com`, then set `options.baseUrl` to `https://github.acme-inc.com/api/v3`. Example
```js
const octokit = new Octokit({
baseUrl: "https://github.acme-inc.com/api/v3",
});
```
</td></tr>
<tr>
<th>
<code>options.previews</code>
</th>
<td>
<code>Array of Strings</code>
</td>
<td>
Some REST API endpoints require preview headers to be set, or enable
additional features. Preview headers can be set on a per-request basis, e.g.
```js
octokit.request("POST /repos/{owner}/{repo}/pulls", {
mediaType: {
previews: ["shadow-cat"],
},
owner,
repo,
title: "My pull request",
base: "main",
head: "my-feature",
draft: true,
});
```
You can also set previews globally, by setting the `options.previews` option on the constructor. Example:
```js
const octokit = new Octokit({
previews: ["shadow-cat"],
});
```
</td></tr>
<tr>
<th>
<code>options.request</code>
</th>
<td>
<code>Object</code>
</td>
<td>
Set a default request timeout (`options.request.timeout`) or an [`http(s).Agent`](https://nodejs.org/api/http.html#http_class_http_agent) e.g. for proxy usage (Node only, `options.request.agent`).
There are more `options.request.*` options, see [`@octokit/request` options](https://github.com/octokit/request.js#request). `options.request` can also be set on a per-request basis.
</td></tr>
<tr>
<th>
<code>options.timeZone</code>
</th>
<td>
<code>String</code>
</td>
<td>
Sets the `Time-Zone` header which defines a timezone according to the [list of names from the Olson database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
```js
const octokit = new Octokit({
timeZone: "America/Los_Angeles",
});
```
The time zone header will determine the timezone used for generating the timestamp when creating commits. See [GitHub's Timezones documentation](https://developer.github.com/v3/#timezones).
</td></tr>
<tr>
<th>
<code>options.userAgent</code>
</th>
<td>
<code>String</code>
</td>
<td>
A custom user agent string for your app or library. Example
```js
const octokit = new Octokit({
userAgent: "my-app/v1.2.3",
});
```
</td></tr>
</tbody>
</table>
## 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, { opt1: 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.
## Authentication
Authentication is optional for some REST API endpoints accessing public data, but is required for GraphQL queries. Using authentication also increases your [API rate limit](https://developer.github.com/v3/#rate-limiting).
By default, Octokit authenticates using the [token authentication strategy](https://github.com/octokit/auth-token.js). Pass in a token using `options.auth`. It can be a personal access token, an OAuth token, an installation access token or a JSON Web Token for GitHub App authentication. The `Authorization` header will be set according to the type of token.
```js
import { Octokit } from "@octokit/core";
const octokit = new Octokit({
auth: "mypersonalaccesstoken123",
});
const { data } = await octokit.request("/user");
```
To use a different authentication strategy, set `options.authStrategy`. A list of authentication strategies is available at [octokit/authentication-strategies.js](https://github.com/octokit/authentication-strategies.js/#readme).
Example
```js
import { Octokit } from "@octokit/core";
import { createAppAuth } from "@octokit/auth-app";
const appOctokit = new Octokit({
authStrategy: createAppAuth,
auth: {
appId: 123,
privateKey: process.env.PRIVATE_KEY,
},
});
const { data } = await appOctokit.request("/app");
```
The `.auth()` method returned by the current authentication strategy can be accessed at `octokit.auth()`. Example
```js
const { token } = await appOctokit.auth({
type: "installation",
installationId: 123,
});
```
## Logging
There are four built-in log methods
1. `octokit.log.debug(message[, additionalInfo])`
1. `octokit.log.info(message[, additionalInfo])`
1. `octokit.log.warn(message[, additionalInfo])`
1. `octokit.log.error(message[, additionalInfo])`
They can be configured using the [`log` client option](client-options). By default, `octokit.log.debug()` and `octokit.log.info()` are no-ops, while the other two call `console.warn()` and `console.error()` respectively.
This is useful if you build reusable [plugins](#plugins).
If you would like to make the log level configurable using an environment variable or external option, we recommend the [console-log-level](https://github.com/watson/console-log-level) package. Example
```js
import consoleLogLevel from "console-log-level";
const octokit = new Octokit({
log: consoleLogLevel({ level: "info" }),
});
```
## Hooks
You can customize Octokit's request lifecycle with hooks.
```js
octokit.hook.before("request", async (options) => {
validate(options);
});
octokit.hook.after("request", async (response, options) => {
console.log(`${options.method} ${options.url}: ${response.status}`);
});
octokit.hook.error("request", async (error, options) => {
if (error.status === 304) {
return findInCache(error.response.headers.etag);
}
throw error;
});
octokit.hook.wrap("request", async (request, options) => {
// add logic before, after, catch errors or replace the request altogether
return request(options);
});
```
See [before-after-hook](https://github.com/gr2m/before-after-hook#readme) for more documentation on hooks.
## Plugins
Octokits functionality can be extended using plugins. The `Octokit.plugin()` method accepts a plugin (or many) and returns a new constructor.
A plugin is a function which gets two arguments:
1. the current instance
2. the options passed to the constructor.
In order to extend `octokit`'s API, the plugin must return an object with the new methods. Please refrain from adding methods directly to the `octokit` instance, especialy if you depend on keys that do not exist in `@octokit/core`, such as `octokit.rest`.
```js
// index.js
import { Octokit } from "@octokit/core";
import myPlugin from "./lib/my-plugin.js";
import octokitPluginExample from "octokit-plugin-example";
const MyOctokit = Octokit.plugin(
myPlugin,
octokitPluginExample
);
const octokit = new MyOctokit({ greeting: "Moin moin" });
octokit.helloWorld(); // logs "Moin moin, world!"
octokit.request("GET /"); // logs "GET / - 200 in 123ms"
// lib/my-plugin.js
const plugin = (octokit, options = { greeting: "Hello" }) => {
// hook into the request lifecycle
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;
});
// add a custom method
return {
helloWorld: () => console.log(`${options.greeting}, world!`);
}
};
export default plugin;
```
## Build your own Octokit with Plugins and Defaults
You can build your own Octokit class with preset default options and plugins. In fact, this is mostly how the `@octokit/<context>` modules work, such as [`@octokit/action`](https://github.com/octokit/action.js):
```js
import { Octokit } from "@octokit/core";
import { paginateRest } from "@octokit/plugin-paginate-rest";
import { throttling } from "@octokit/plugin-throttling";
import { retry } from "@octokit/plugin-retry";
import { createActionAuth } from "@octokit/auth-action";
const MyActionOctokit = Octokit.plugin(
paginateRest,
throttling,
retry,
).defaults({
throttle: {
onAbuseLimit: (retryAfter, options) => {
/* ... */
},
onRateLimit: (retryAfter, options) => {
/* ... */
},
},
authStrategy: createActionAuth,
userAgent: `my-octokit-action/v1.2.3`,
});
const octokit = new MyActionOctokit();
const installations = await octokit.paginate("GET /app/installations");
```
## LICENSE
[MIT](LICENSE)

View file

@ -0,0 +1,134 @@
import { getUserAgent } from "universal-user-agent";
import Hook from "before-after-hook";
import { request } from "@octokit/request";
import { withCustomRequest } from "@octokit/graphql";
import { createTokenAuth } from "@octokit/auth-token";
import { VERSION } from "./version.js";
const noop = () => {
};
const consoleWarn = console.warn.bind(console);
const consoleError = console.error.bind(console);
const userAgentTrail = `octokit-core.js/${VERSION} ${getUserAgent()}`;
class Octokit {
static VERSION = VERSION;
static defaults(defaults) {
const OctokitWithDefaults = class extends this {
constructor(...args) {
const options = args[0] || {};
if (typeof defaults === "function") {
super(defaults(options));
return;
}
super(
Object.assign(
{},
defaults,
options,
options.userAgent && defaults.userAgent ? {
userAgent: `${options.userAgent} ${defaults.userAgent}`
} : null
)
);
}
};
return OctokitWithDefaults;
}
static plugins = [];
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin(...newPlugins) {
const currentPlugins = this.plugins;
const NewOctokit = class extends this {
static plugins = currentPlugins.concat(
newPlugins.filter((plugin) => !currentPlugins.includes(plugin))
);
};
return NewOctokit;
}
constructor(options = {}) {
const hook = new Hook.Collection();
const requestDefaults = {
baseUrl: request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request")
}),
mediaType: {
previews: [],
format: ""
}
};
requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
requestDefaults.headers["time-zone"] = options.timeZone;
}
this.request = request.defaults(requestDefaults);
this.graphql = withCustomRequest(this.request).defaults(requestDefaults);
this.log = Object.assign(
{
debug: noop,
info: noop,
warn: consoleWarn,
error: consoleError
},
options.log
);
this.hook = hook;
if (!options.authStrategy) {
if (!options.auth) {
this.auth = async () => ({
type: "unauthenticated"
});
} else {
const auth = createTokenAuth(options.auth);
hook.wrap("request", auth.hook);
this.auth = auth;
}
} else {
const { authStrategy, ...otherOptions } = options;
const auth = authStrategy(
Object.assign(
{
request: this.request,
log: this.log,
// we pass the current octokit instance as well as its constructor options
// to allow for authentication strategies that return a new octokit instance
// that shares the same internal state as the current one. The original
// requirement for this was the "event-octokit" authentication strategy
// of https://github.com/probot/octokit-auth-probot.
octokit: this,
octokitOptions: otherOptions
},
options.auth
)
);
hook.wrap("request", auth.hook);
this.auth = auth;
}
const classConstructor = this.constructor;
for (let i = 0; i < classConstructor.plugins.length; ++i) {
Object.assign(this, classConstructor.plugins[i](this, options));
}
}
// assigned during constructor
request;
graphql;
log;
hook;
// TODO: type `octokit.auth` based on passed options.authStrategy
auth;
}
export {
Octokit
};

View file

@ -0,0 +1,4 @@
const VERSION = "6.1.4";
export {
VERSION
};

View file

@ -0,0 +1,31 @@
import type { HookCollection } from "before-after-hook";
import { request } from "@octokit/request";
import { type graphql } from "@octokit/graphql";
import type { Constructor, Hooks, OctokitOptions, OctokitPlugin, ReturnTypeOf, UnionToIntersection } from "./types.js";
export type { OctokitOptions } from "./types.js";
export declare class Octokit {
static VERSION: string;
static defaults<S extends Constructor<any>>(this: S, defaults: OctokitOptions | Function): S;
static plugins: OctokitPlugin[];
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin<S extends Constructor<any> & {
plugins: any[];
}, T extends OctokitPlugin[]>(this: S, ...newPlugins: T): S & Constructor<UnionToIntersection<ReturnTypeOf<T>>>;
constructor(options?: OctokitOptions);
request: typeof request;
graphql: typeof graphql;
log: {
debug: (message: string, additionalInfo?: object) => any;
info: (message: string, additionalInfo?: object) => any;
warn: (message: string, additionalInfo?: object) => any;
error: (message: string, additionalInfo?: object) => any;
[key: string]: any;
};
hook: HookCollection<Hooks>;
auth: (...args: unknown[]) => Promise<unknown>;
}

View file

@ -0,0 +1,44 @@
import type * as OctokitTypes from "@octokit/types";
import type { RequestError } from "@octokit/request-error";
import type { Octokit } from "./index.js";
export type RequestParameters = OctokitTypes.RequestParameters;
export interface OctokitOptions {
authStrategy?: any;
auth?: any;
userAgent?: string;
previews?: string[];
baseUrl?: string;
log?: {
debug: (message: string) => unknown;
info: (message: string) => unknown;
warn: (message: string) => unknown;
error: (message: string) => unknown;
};
request?: OctokitTypes.RequestRequestOptions;
timeZone?: string;
[option: string]: any;
}
export type Constructor<T> = new (...args: any[]) => T;
export type ReturnTypeOf<T extends AnyFunction | AnyFunction[]> = T extends AnyFunction ? ReturnType<T> : T extends AnyFunction[] ? UnionToIntersection<Exclude<ReturnType<T[number]>, void>> : never;
/**
* @author https://stackoverflow.com/users/2887218/jcalz
* @see https://stackoverflow.com/a/50375286/10325032
*/
export type UnionToIntersection<Union> = (Union extends any ? (argument: Union) => void : never) extends (argument: infer Intersection) => void ? Intersection : never;
type AnyFunction = (...args: any) => any;
export type OctokitPlugin = (octokit: Octokit, options: OctokitOptions) => {
[key: string]: any;
} | void;
export type Hooks = {
request: {
Options: Required<OctokitTypes.EndpointDefaults>;
Result: OctokitTypes.OctokitResponse<any>;
Error: RequestError | Error;
};
[key: string]: {
Options: unknown;
Result: unknown;
Error: unknown;
};
};
export {};

View file

@ -0,0 +1 @@
export declare const VERSION = "6.1.4";

View file

@ -0,0 +1,69 @@
{
"name": "@octokit/core",
"version": "6.1.4",
"publishConfig": {
"access": "public",
"provenance": true
},
"type": "module",
"description": "Extendable client for GitHub's REST & GraphQL APIs",
"repository": "github:octokit/core.js",
"keywords": [
"octokit",
"github",
"api",
"sdk",
"toolkit"
],
"author": "Gregor Martynus (https://github.com/gr2m)",
"license": "MIT",
"dependencies": {
"@octokit/auth-token": "^5.0.0",
"@octokit/graphql": "^8.1.2",
"@octokit/request": "^9.2.1",
"@octokit/request-error": "^6.1.7",
"@octokit/types": "^13.6.2",
"before-after-hook": "^3.0.2",
"universal-user-agent": "^7.0.0"
},
"devDependencies": {
"@octokit/auth-action": "^5.0.0",
"@octokit/auth-app": "^7.0.0",
"@octokit/auth-oauth-app": "^8.0.0",
"@octokit/tsconfig": "^4.0.0",
"@sinonjs/fake-timers": "^14.0.0",
"@types/lolex": "^5.1.0",
"@types/node": "^22.0.0",
"@types/sinonjs__fake-timers": "^8.1.5",
"@vitest/coverage-v8": "^3.0.5",
"esbuild": "^0.25.0",
"fetch-mock": "^12.0.0",
"glob": "^11.0.0",
"prettier": "3.4.2",
"proxy": "^2.0.0",
"semantic-release": "^24.0.0",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"typescript": "^5.0.0",
"undici": "^6.0.0",
"vitest": "^3.0.5"
},
"engines": {
"node": ">= 18"
},
"files": [
"dist-*/**",
"bin/**"
],
"types": "./dist-types/index.d.ts",
"exports": {
".": {
"types": "./dist-types/index.d.ts",
"import": "./dist-src/index.js",
"default": "./dist-src/index.js"
},
"./types": {
"types": "./dist-types/types.d.ts"
}
},
"sideEffects": false
}

View file

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,412 @@
# endpoint.js
> Turns GitHub REST API endpoints into generic request options
[![@latest](https://img.shields.io/npm/v/@octokit/endpoint.svg)](https://www.npmjs.com/package/@octokit/endpoint)
[![Build Status](https://github.com/octokit/endpoint.js/workflows/Test/badge.svg)](https://github.com/octokit/endpoint.js/actions/workflows/test.yml?query=branch%3Amain)
`@octokit/endpoint` combines [GitHub REST API routes](https://developer.github.com/v3/) with your parameters and turns them into generic request options that can be used in any request library.
<!-- update table of contents by running `npx markdown-toc README.md -i` -->
<!-- toc -->
- [Usage](#usage)
- [API](#api)
- [`endpoint(route, options)` or `endpoint(options)`](#endpointroute-options-or-endpointoptions)
- [`endpoint.defaults()`](#endpointdefaults)
- [`endpoint.DEFAULTS`](#endpointdefaults)
- [`endpoint.merge(route, options)` or `endpoint.merge(options)`](#endpointmergeroute-options-or-endpointmergeoptions)
- [`endpoint.parse()`](#endpointparse)
- [Special cases](#special-cases)
- [The `data` parameter set request body directly](#the-data-parameter-%E2%80%93-set-request-body-directly)
- [Set parameters for both the URL/query and the request body](#set-parameters-for-both-the-urlquery-and-the-request-body)
- [LICENSE](#license)
<!-- tocstop -->
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
Load <code>@octokit/endpoint</code> directly from <a href="https://esm.sh">esm.sh</a>
```html
<script type="module">
import { endpoint } from "https://esm.sh/@octokit/endpoint";
</script>
```
</td></tr>
<tr><th>
Node
</th><td>
Install with <code>npm install @octokit/endpoint</code>
```js
import { endpoint } from "@octokit/endpoint";
```
</td></tr>
</tbody>
</table>
Example for [List organization repositories](https://developer.github.com/v3/repos/#list-organization-repositories)
```js
const requestOptions = endpoint("GET /orgs/{org}/repos", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
});
```
The resulting `requestOptions` looks as follows
```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"
}
}
```
You can pass `requestOptions` to common request libraries
```js
const { url, ...options } = requestOptions;
// using with fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
fetch(url, options);
// using with request (https://github.com/request/request)
request(requestOptions);
// using with got (https://github.com/sindresorhus/got)
got[options.method](url, options);
// using with axios
axios(requestOptions);
```
> [!IMPORTANT]
> As we use [conditional exports](https://nodejs.org/api/packages.html#conditional-exports), you will need to adapt your `tsconfig.json`. See the TypeScript docs on [package.json "exports"](https://www.typescriptlang.org/docs/handbook/modules/reference.html#packagejson-exports).
## API
### `endpoint(route, options)` or `endpoint(options)`
<table>
<thead align=left>
<tr>
<th>
name
</th>
<th>
type
</th>
<th width=100%>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th>
<code>route</code>
</th>
<td>
String
</td>
<td>
If set, it has to be a string consisting of URL and the request method, e.g., <code>GET /orgs/{org}</code>. If its set to a URL, only the method defaults to <code>GET</code>.
</td>
</tr>
<tr>
<th>
<code>options.method</code>
</th>
<td>
String
</td>
<td>
<strong>Required unless <code>route</code> is set.</strong> Any supported <a href="https://developer.github.com/v3/#http-verbs">http verb</a>. <em>Defaults to <code>GET</code></em>.
</td>
</tr>
<tr>
<th>
<code>options.url</code>
</th>
<td>
String
</td>
<td>
<strong>Required unless <code>route</code> is set.</strong> A path or full URL which may contain <code>:variable</code> or <code>{variable}</code> placeholders,
e.g., <code>/orgs/{org}/repos</code>. The <code>url</code> is parsed using <a href="https://github.com/bramstein/url-template">url-template</a>.
</td>
</tr>
<tr>
<th>
<code>options.baseUrl</code>
</th>
<td>
String
</td>
<td>
<em>Defaults to <code>https://api.github.com</code></em>.
</td>
</tr>
<tr>
<th>
<code>options.headers</code>
</th>
<td>
Object
</td>
<td>
Custom headers. Passed headers are merged with defaults:<br>
<em><code>headers['user-agent']</code> defaults to <code>octokit-endpoint.js/1.2.3</code> (where <code>1.2.3</code> is the released version)</em>.<br>
<em><code>headers['accept']</code> defaults to <code>application/vnd.github.v3+json</code></em>.<br>
</td>
</tr>
<tr>
<th>
<code>options.mediaType.format</code>
</th>
<td>
String
</td>
<td>
Media type param, such as <code>raw</code>, <code>diff</code>, or <code>text+json</code>. See <a href="https://developer.github.com/v3/media/">Media Types</a>. Setting <code>options.mediaType.format</code> will amend the <code>headers.accept</code> value.
</td>
</tr>
<tr>
<th>
<code>options.data</code>
</th>
<td>
Any
</td>
<td>
Set request body directly instead of setting it to JSON based on additional parameters. See <a href="#data-parameter">"The <code>data</code> parameter"</a> below.
</td>
</tr>
<tr>
<th>
<code>options.request</code>
</th>
<td>
Object
</td>
<td>
Pass custom meta information for the request. The <code>request</code> object will be returned as is.
</td>
</tr>
</tbody>
</table>
All other options will be passed depending on the `method` and `url` options.
1. If the option key has a placeholder in the `url`, it will be used as the replacement. For example, if the passed options are `{url: '/orgs/{org}/repos', org: 'foo'}` the returned `options.url` is `https://api.github.com/orgs/foo/repos`.
2. If the `method` is `GET` or `HEAD`, the option is passed as a query parameter.
3. Otherwise, the parameter is passed in the request body as a JSON key.
**Result**
`endpoint()` is a synchronous method and returns an object with the following keys:
<table>
<thead align=left>
<tr>
<th>
key
</th>
<th>
type
</th>
<th width=100%>
description
</th>
</tr>
</thead>
<tbody align=left valign=top>
<tr>
<th><code>method</code></th>
<td>String</td>
<td>The http method. Always lowercase.</td>
</tr>
<tr>
<th><code>url</code></th>
<td>String</td>
<td>The url with placeholders replaced with passed parameters.</td>
</tr>
<tr>
<th><code>headers</code></th>
<td>Object</td>
<td>All header names are lowercased.</td>
</tr>
<tr>
<th><code>body</code></th>
<td>Any</td>
<td>The request body if one is present. Only for <code>PATCH</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code> requests.</td>
</tr>
<tr>
<th><code>request</code></th>
<td>Object</td>
<td>Request meta option, it will be returned as it was passed into <code>endpoint()</code></td>
</tr>
</tbody>
</table>
### `endpoint.defaults()`
Override or set default options. Example:
```js
const request = require("request");
const myEndpoint = require("@octokit/endpoint").defaults({
baseUrl: "https://github-enterprise.acme-inc.com/api/v3",
headers: {
"user-agent": "myApp/1.2.3",
authorization: `token 0000000000000000000000000000000000000001`,
},
org: "my-project",
per_page: 100,
});
request(myEndpoint(`GET /orgs/{org}/repos`));
```
You can call `.defaults()` again on the returned method, the defaults will cascade.
```js
const myProjectEndpoint = endpoint.defaults({
baseUrl: "https://github-enterprise.acme-inc.com/api/v3",
headers: {
"user-agent": "myApp/1.2.3",
},
org: "my-project",
});
const myProjectEndpointWithAuth = myProjectEndpoint.defaults({
headers: {
authorization: `token 0000000000000000000000000000000000000001`,
},
});
```
`myProjectEndpointWithAuth` now defaults the `baseUrl`, `headers['user-agent']`,
`org` and `headers['authorization']` on top of `headers['accept']` that is set
by the global default.
### `endpoint.DEFAULTS`
The current default options.
```js
endpoint.DEFAULTS.baseUrl; // https://api.github.com
const myEndpoint = endpoint.defaults({
baseUrl: "https://github-enterprise.acme-inc.com/api/v3",
});
myEndpoint.DEFAULTS.baseUrl; // https://github-enterprise.acme-inc.com/api/v3
```
### `endpoint.merge(route, options)` or `endpoint.merge(options)`
Get the defaulted endpoint options, but without parsing them into request options:
```js
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'
// }
```
### `endpoint.parse()`
Stateless method to turn endpoint options into request options. Calling
`endpoint(options)` is the same as calling `endpoint.parse(endpoint.merge(options))`.
## Special cases
<a name="data-parameter"></a>
### The `data` parameter set request body directly
Some endpoints such as [Render a Markdown document in raw mode](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode) dont have parameters that are sent as request body keys, instead, the request body needs to be set directly. In these cases, set the `data` parameter.
```js
const options = endpoint("POST /markdown/raw", {
data: "Hello world github/linguist#1 **cool**, and #1!",
headers: {
accept: "text/html;charset=utf-8",
"content-type": "text/plain",
},
});
// options is
// {
// method: 'post',
// url: 'https://api.github.com/markdown/raw',
// headers: {
// accept: 'text/html;charset=utf-8',
// 'content-type': 'text/plain',
// 'user-agent': userAgent
// },
// body: 'Hello world github/linguist#1 **cool**, and #1!'
// }
```
### Set parameters for both the URL/query and the request body
There are API endpoints that accept both query parameters as well as a body. In that case, you need to add the query parameters as templates to `options.url`, as defined in the [RFC 6570 URI Template specification](https://tools.ietf.org/html/rfc6570).
Example
```js
endpoint(
"POST https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}",
{
name: "example.zip",
label: "short description",
headers: {
"content-type": "text/plain",
"content-length": 14,
authorization: `token 0000000000000000000000000000000000000001`,
},
data: "Hello, world!",
},
);
```
## LICENSE
[MIT](LICENSE)

View file

@ -0,0 +1,346 @@
// pkg/dist-src/defaults.js
import { getUserAgent } from "universal-user-agent";
// pkg/dist-src/version.js
var VERSION = "0.0.0-development";
// pkg/dist-src/defaults.js
var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;
var DEFAULTS = {
method: "GET",
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent
},
mediaType: {
format: ""
}
};
// pkg/dist-src/util/lowercase-keys.js
function lowercaseKeys(object) {
if (!object) {
return {};
}
return Object.keys(object).reduce((newObj, key) => {
newObj[key.toLowerCase()] = object[key];
return newObj;
}, {});
}
// pkg/dist-src/util/is-plain-object.js
function isPlainObject(value) {
if (typeof value !== "object" || value === null) return false;
if (Object.prototype.toString.call(value) !== "[object Object]") return false;
const proto = Object.getPrototypeOf(value);
if (proto === null) return true;
const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
}
// pkg/dist-src/util/merge-deep.js
function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach((key) => {
if (isPlainObject(options[key])) {
if (!(key in defaults)) Object.assign(result, { [key]: options[key] });
else result[key] = mergeDeep(defaults[key], options[key]);
} else {
Object.assign(result, { [key]: options[key] });
}
});
return result;
}
// pkg/dist-src/util/remove-undefined-properties.js
function removeUndefinedProperties(obj) {
for (const key in obj) {
if (obj[key] === void 0) {
delete obj[key];
}
}
return obj;
}
// pkg/dist-src/merge.js
function merge(defaults, route, options) {
if (typeof route === "string") {
let [method, url] = route.split(" ");
options = Object.assign(url ? { method, url } : { url: method }, options);
} else {
options = Object.assign({}, route);
}
options.headers = lowercaseKeys(options.headers);
removeUndefinedProperties(options);
removeUndefinedProperties(options.headers);
const mergedOptions = mergeDeep(defaults || {}, options);
if (options.url === "/graphql") {
if (defaults && defaults.mediaType.previews?.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(
(preview) => !mergedOptions.mediaType.previews.includes(preview)
).concat(mergedOptions.mediaType.previews);
}
mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
}
return mergedOptions;
}
// pkg/dist-src/util/add-query-parameters.js
function addQueryParameters(url, parameters) {
const separator = /\?/.test(url) ? "&" : "?";
const names = Object.keys(parameters);
if (names.length === 0) {
return url;
}
return url + separator + names.map((name) => {
if (name === "q") {
return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
}
return `${name}=${encodeURIComponent(parameters[name])}`;
}).join("&");
}
// pkg/dist-src/util/extract-url-variable-names.js
var urlVariableRegex = /\{[^{}}]+\}/g;
function removeNonChars(variableName) {
return variableName.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g, "").split(/,/);
}
function extractUrlVariableNames(url) {
const matches = url.match(urlVariableRegex);
if (!matches) {
return [];
}
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}
// pkg/dist-src/util/omit.js
function omit(object, keysToOmit) {
const result = { __proto__: null };
for (const key of Object.keys(object)) {
if (keysToOmit.indexOf(key) === -1) {
result[key] = object[key];
}
}
return result;
}
// pkg/dist-src/util/url-template.js
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
}
return part;
}).join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
function encodeValue(operator, value, key) {
value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
} else {
return value;
}
}
function isDefined(value) {
return value !== void 0 && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key], result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(
encodeValue(operator, value, isKeyOperator(operator) ? key : "")
);
} else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function(value2) {
result.push(
encodeValue(operator, value2, isKeyOperator(operator) ? key : "")
);
});
} else {
Object.keys(value).forEach(function(k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function(value2) {
tmp.push(encodeValue(operator, value2));
});
} else {
Object.keys(value).forEach(function(k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
} else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
} else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
} else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
} else if (value === "") {
result.push("");
}
}
return result;
}
function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
template = template.replace(
/\{([^\{\}]+)\}|([^\{\}]+)/g,
function(_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function(variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
} else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
} else {
return values.join(",");
}
} else {
return encodeReserved(literal);
}
}
);
if (template === "/") {
return template;
} else {
return template.replace(/\/$/, "");
}
}
// pkg/dist-src/parse.js
function parse(options) {
let method = options.method.toUpperCase();
let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
let headers = Object.assign({}, options.headers);
let body;
let parameters = omit(options, [
"method",
"baseUrl",
"url",
"headers",
"request",
"mediaType"
]);
const urlVariableNames = extractUrlVariableNames(url);
url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) {
url = options.baseUrl + url;
}
const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
const remainingParameters = omit(parameters, omittedParameters);
const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
if (!isBinaryRequest) {
if (options.mediaType.format) {
headers.accept = headers.accept.split(/,/).map(
(format) => format.replace(
/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
`application/vnd$1$2.${options.mediaType.format}`
)
).join(",");
}
if (url.endsWith("/graphql")) {
if (options.mediaType.previews?.length) {
const previewsFromAcceptHeader = headers.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g) || [];
headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
return `application/vnd.github.${preview}-preview${format}`;
}).join(",");
}
}
}
if (["GET", "HEAD"].includes(method)) {
url = addQueryParameters(url, remainingParameters);
} else {
if ("data" in remainingParameters) {
body = remainingParameters.data;
} else {
if (Object.keys(remainingParameters).length) {
body = remainingParameters;
}
}
}
if (!headers["content-type"] && typeof body !== "undefined") {
headers["content-type"] = "application/json; charset=utf-8";
}
if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
body = "";
}
return Object.assign(
{ method, url, headers },
typeof body !== "undefined" ? { body } : null,
options.request ? { request: options.request } : null
);
}
// pkg/dist-src/endpoint-with-defaults.js
function endpointWithDefaults(defaults, route, options) {
return parse(merge(defaults, route, options));
}
// pkg/dist-src/with-defaults.js
function withDefaults(oldDefaults, newDefaults) {
const DEFAULTS2 = merge(oldDefaults, newDefaults);
const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
return Object.assign(endpoint2, {
DEFAULTS: DEFAULTS2,
defaults: withDefaults.bind(null, DEFAULTS2),
merge: merge.bind(null, DEFAULTS2),
parse
});
}
// pkg/dist-src/index.js
var endpoint = withDefaults(null, DEFAULTS);
export {
endpoint
};

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,17 @@
import { getUserAgent } from "universal-user-agent";
import { VERSION } from "./version.js";
const userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;
const DEFAULTS = {
method: "GET",
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent
},
mediaType: {
format: ""
}
};
export {
DEFAULTS
};

Some files were not shown because too many files have changed in this diff Show more