Showing preview only (2,789K chars total). Download the full file or copy to clipboard to get everything.
Repository: zoubingwu/msw-auto-mock
Branch: master
Commit: 34356e4d2352
Files: 45
Total size: 2.7 MB
Directory structure:
gitextract_33neljsu/
├── .changeset/
│ ├── README.md
│ └── config.json
├── .editorconfig
├── .github/
│ └── workflows/
│ └── release.yaml
├── .gitignore
├── .prettierignore
├── .prettierrc.js
├── CHANGELOG.md
├── README.md
├── bin/
│ └── cli.js
├── example/
│ ├── .gitignore
│ ├── index.html
│ ├── package.json
│ ├── src/
│ │ ├── App.tsx
│ │ ├── index.css
│ │ ├── main.tsx
│ │ └── vite-env.d.ts
│ ├── tsconfig.app.json
│ ├── tsconfig.json
│ ├── tsconfig.node.json
│ └── vite.config.mjs
├── lefthook.yml
├── package.json
├── pnpm-workspace.yaml
├── scripts/
│ └── changelog.sh
├── src/
│ ├── cli.ts
│ ├── generate.ts
│ ├── swagger.ts
│ ├── template.ts
│ ├── transform.ts
│ ├── types.ts
│ └── utils.ts
├── test/
│ ├── ai-runtime.spec.ts
│ ├── fixture/
│ │ ├── githubapi.yaml
│ │ ├── petstore.json
│ │ ├── strings.yaml
│ │ └── test.yaml
│ ├── generate.spec.ts
│ ├── template.spec.ts
│ ├── transform.spec.ts
│ ├── typescript-generation.spec.ts
│ └── utils.spec.ts
├── tsconfig.json
├── tsup.config.ts
└── vitest.config.ts
================================================
FILE CONTENTS
================================================
================================================
FILE: .changeset/README.md
================================================
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
================================================
FILE: .changeset/config.json
================================================
{
"$schema": "https://unpkg.com/@changesets/config@3.0.2/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": []
}
================================================
FILE: .editorconfig
================================================
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
================================================
FILE: .github/workflows/release.yaml
================================================
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
name: Publish Github Packages
on:
push:
branches:
- master
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: '24'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Build Package
run: pnpm build
- name: Build Package
run: pnpm test
- name: Create Release Pull Request or Publish to npm
uses: changesets/action@v1
with:
commit: "release: bump versions"
title: "release: bump versions"
publish: pnpm release
================================================
FILE: .gitignore
================================================
node_modules/
dist/
example/src/mock.js
example/test*.js
.idea/
.vscode/
*.log
package-lock.json
================================================
FILE: .prettierignore
================================================
dist
node_modules
build
coverage
example/src/mock.js
fixture
================================================
FILE: .prettierrc.js
================================================
module.exports = {
singleQuote: true,
arrowParens: 'avoid',
semi: true,
printWidth: 120,
};
================================================
FILE: CHANGELOG.md
================================================
# msw-auto-mock
## 0.32.1
### Patch Changes
- 5ea0a3e: [WIP] Fix reference error for MAX_STRING_LENGTH in generated code
## 0.32.0
### Minor Changes
- a35c1ce: Multiple improvements and fixes since 0.31.0:
- feat: echo request JSON body into write responses
- fix: await response generators in handlers
- fix: handle OpenAPI regex patterns and other schema edge cases (date-time, max array length, example $ref)
- fix: improve handler ordering and default response selection
- chore: AI SDK upgrades and dependency/security updates
## 0.31.0
### Minor Changes
- 02bf90d: Enhance typescript support
## 0.30.0
### Minor Changes
- 83539f8: make next function to api scope instead of global
## 0.29.0
### Minor Changes
- 3d490b8: fix string pattern generation
## 0.28.0
### Minor Changes
- a526bf0: chore: switch to ts project for example and upgrade deps
## 0.27.0
### Minor Changes
- 37b63a0: - chore: switch to pnpm 10.6.1 and fix tests ([#83](https://github.com/zoubingwu/msw-auto-mock/pull/83))
- fix: resolve type object allOf recursively ([#69](https://github.com/zoubingwu/msw-auto-mock/pull/69))
- Allow for different resource keys than application/json ([#73](https://github.com/zoubingwu/msw-auto-mock/pull/73))
- Extend transform string logic to return faker's fromRegExp() if a regexp pattern is provided ([#74](https://github.com/zoubingwu/msw-auto-mock/pull/74))
- Change createOpenAI option baseURL source ([#77](https://github.com/zoubingwu/msw-auto-mock/pull/77))
- improved the handling of date-time strings and time strings. ([#80](https://github.com/zoubingwu/msw-auto-mock/pull/80))
## 0.26.0
### Minor Changes
- 61df9e8: Added TypeScript file generation option (--typescript) to generate TypeScript files instead of JavaScript files.
## 0.25.0
### Minor Changes
- d03bc3e: Fix generated code for string with max length
## 0.24.0
### Minor Changes
- b2bf101: Fix peer dependency version range
## 0.23.0
### Minor Changes
- 0fb95e1: cache one with static flag for ai mode
## 0.22.0
### Minor Changes
- 8d259bf: Only output ai code when enabled
## 0.21.0
### Minor Changes
- 72829cd: Update faker functions
## 0.20.0
### Minor Changes
- d95b565: Respect min/max constrain for string
## 0.19.0
### Breaking Changes
- Always output to a folder, removed `--node`, `--react-native` options
### Minor Changes
- e2b05fb: Support generate mock data using generative ai, currently support `openai`, `azure` and `anthropic`
================================================
FILE: README.md
================================================
# msw-auto-mock



A cli tool to generate random mock data from OpenAPI descriptions for [msw](https://github.com/mswjs/msw).
## Why
We already have all the type definitions from OpenAPI spec so hand-writing every response resolver is completely unnecessary.
## Generative AI Support
Since v0.19.0, msw-auto-mock can use generative AI to generate mock data instead of faker.
AI is configured via your `package.json` (or any config file supported by cosmiconfig) under the `msw-auto-mock` key:
```json
{
"msw-auto-mock": {
"ai": {
"enable": true,
"provider": "openai",
"openai": {
"apiKey": "process.env.OPENAI_API_KEY",
"model": "gpt-4o"
}
}
}
}
```
### Providers and Required Fields
Currently supported providers: `openai`, `azure`, `anthropic`.
When `ai.enable` is `true`, you must provide the model/deployment for the selected provider:
- `provider: "openai"` requires `ai.openai.model`
- `provider: "azure"` requires `ai.azure.deployment`
- `provider: "anthropic"` requires `ai.anthropic.model`
If a required field is missing, generation fails fast with a clear error (instead of generating broken code).
### How Config Values Are Interpreted
The AI config values are strings in JSON, but they are used to generate JavaScript code.
msw-auto-mock supports two styles:
- **Expression strings**: values that start with `process.env.` or `import.meta.env.` (or `Deno.env.`) are treated as JavaScript expressions and injected as-is.
- **Literal strings**: everything else is treated as a string literal and will be automatically quoted in the generated code.
This means you can write:
- `"model": "gpt-4o"` (literal string; recommended)
- `"apiKey": "process.env.OPENAI_API_KEY"` (expression string)
### Full Type Definition
```ts
interface Config {
ai?: {
enable?: boolean;
provider: 'openai' | 'azure' | 'anthropic';
openai?: {
baseURL?: string;
apiKey?: string;
model?: string;
};
azure?: {
apiKey?: string;
resource?: string;
deployment?: string;
};
anthropic?: {
apiKey?: string;
model?: string;
};
};
}
```
> [!IMPORTANT]
> For security, keep API keys in environment variables and reference them via `process.env.*` / `import.meta.env.*` in your config.
> You no longer need to wrap model names in extra quotes; `"model": "gpt-4o"` is valid.
## Usage
**This tool also requires @faker-js/faker >= 8 and msw >= 2.**
Install:
```sh
yarn add msw-auto-mock @faker-js/faker -D
```
Read from your OpenAPI descriptions and output generated code:
```sh
# can be http url or a file path on your machine, support both yaml and json.
npx msw-auto-mock http://your_openapi.json -o ./mock
```
Integrate with msw, see [Mock Service Worker's doc](https://mswjs.io/docs/getting-started/integrate/browser) for more detail:
```sh
# Install msw
yarn add msw --dev
# Init service worker
npx msw init public/ --save
```
Then import those mock definitions in you app entry:
```js
import { worker } from './mock/browser.js';
await worker.start();
```
For conditional mocking:
```js
async function enableMocking() {
if (process.env.NODE_ENV !== 'development') {
return;
}
const { worker } = await import('./mock/browser');
// `worker.start()` returns a Promise that resolves
// once the Service Worker is up and ready to intercept requests.
return worker.start();
}
function mountApp() {
const root = createRoot(document.getElementById('root'));
root.render(<App />);
}
enableMocking().then(mountApp);
```
For Node.js integration, you can import from `your_output/node.js`:
```js
import { worker } from './mock/node.js';
```
For React Native integration, you can import from `your_output/native.js`:
```js
import { worker } from './mock/native.js';
```
Run you app then you'll see a successful activation message from Mock Service Worker in your browser's console.
## Options
- `-o, --output`: specify output file path or output to stdout.
- `-m, --max-array-length <number>`: specify max array length in response, default value is `20`, it'll cost some time if you want to generate a huge chunk of random data.
- `-t, --includes <keywords>`: specify keywords to match if you want to generate mock data only for certain requests, multiple keywords can be seperated with comma.
- `-e, --excludes <keywords>`: specify keywords to exclude, multiple keywords can be seperated with comma.
- `--base-url`: output code with specified base url or fallback to server host specified in OpenAPI.
- `--static`: By default it will generate dynamic mocks, use this flag if you need it to be static.
- `-c, --codes <keywords>`: comma separated list of status codes to generate responses for
- `--typescript`: Generate TypeScript files instead of JavaScript files.
- `-h, --help`: show help info.
================================================
FILE: bin/cli.js
================================================
#! /usr/bin/env node
require('../dist/cli');
================================================
FILE: example/.gitignore
================================================
node_modules
.DS_Store
dist
dist-ssr
*.local
mock/
.env
public/mockServiceWorker.js
================================================
FILE: example/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
================================================
FILE: example/package.json
================================================
{
"name": "example",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"generate": "msw-auto-mock ../test/fixture/test.yaml -o src/mock "
},
"dependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@faker-js/faker": "9.6.0",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
"@vitejs/plugin-react": "5.1.2",
"msw": "2.7.3",
"msw-auto-mock": "workspace:*",
"typescript": "5.5.3",
"vite": "7.3.1"
},
"msw": {
"workerDirectory": "public"
},
"msw-auto-mock": {
"ai": {
"enable": false,
"provider": "azure",
"azure": {
"apiKey": "import.meta.env.VITE_AZURE_API_KEY",
"resource": "import.meta.env.VITE_AZURE_RESOURCE_NAME",
"deployment": "import.meta.env.VITE_AZURE_DEPLOYMENT"
}
}
}
}
================================================
FILE: example/src/App.tsx
================================================
import { useState } from 'react';
const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE'];
function App() {
const [method, setMethod] = useState(methods[0]);
const [endpoint, setEndpoint] = useState('/pet/1');
const [res, setRes] = useState<unknown>(null);
const [status, setStatus] = useState<number | null>(null);
const [loading, setLoading] = useState(false);
return (
<div className="App">
<h2>API mock playground</h2>
<label>Method</label>
<select value={method} onChange={e => setMethod(e.target.value)}>
{methods.map(i => (
<option key={i} value={i}>
{i}
</option>
))}
</select>
<br />
<label>Endpoint: </label>
<input type="text" value={endpoint} onChange={e => setEndpoint(e.target.value)} />
<br />
<button
type="button"
onClick={async () => {
try {
setLoading(true);
const res = await fetch(endpoint, { method });
setStatus(res.status);
const data = await res.json();
setRes(data);
} catch (e) {
setRes(e);
} finally {
setLoading(false);
}
}}
>
fetch
</button>
{loading && <div>Loading...</div>}
{status && <div>Status: {status}</div>}
<pre>
<code>{res ? JSON.stringify(res, null, 4) : 'null'}</code>
</pre>
</div>
);
}
export default App;
================================================
FILE: example/src/index.css
================================================
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-size: 11px;
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
================================================
FILE: example/src/main.tsx
================================================
import './index.css';
import { createRoot } from 'react-dom/client';
import App from './App';
async function enableMocking() {
const { worker } = await import('./mock/browser');
// `worker.start()` returns a Promise that resolves
// once the Service Worker is up and ready to intercept requests.
return worker.start();
}
function mountApp() {
const root = createRoot(document.getElementById('root')!);
root.render(<App />);
}
enableMocking().then(mountApp);
================================================
FILE: example/src/vite-env.d.ts
================================================
/// <reference types="vite/client" />
================================================
FILE: example/tsconfig.app.json
================================================
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
================================================
FILE: example/tsconfig.json
================================================
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
================================================
FILE: example/tsconfig.node.json
================================================
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
================================================
FILE: example/vite.config.mjs
================================================
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});
================================================
FILE: lefthook.yml
================================================
# EXAMPLE USAGE:
#
# Refer for explanation to following link:
# https://github.com/evilmartians/lefthook/blob/master/docs/configuration.md
#
# pre-push:
# commands:
# packages-audit:
# tags: frontend security
# run: yarn audit
# gems-audit:
# tags: backend security
# run: bundle audit
#
pre-commit:
parallel: true
commands:
prettier:
glob: "*.{js,ts,jsx,tsx}"
run: pnpx prettier --write {staged_files}
stage_fixed: true
================================================
FILE: package.json
================================================
{
"name": "msw-auto-mock",
"version": "0.32.1",
"description": "Generate random mock data from OpenAPI descriptions for msw.",
"main": "dist/cli.js",
"bin": {
"msw-auto-mock": "./bin/cli.js"
},
"scripts": {
"build": "tsup",
"fmt": "prettier {example,src}/**/*.{js,jsx,ts,tsx,css,md,html} --write",
"test": "vitest run",
"changeset": "changeset",
"release": "changeset publish"
},
"author": "zoubingwu<zoubingwu@gmail.com>",
"license": "MIT",
"dependencies": {
"@ai-sdk/anthropic": "3.0.31",
"@ai-sdk/azure": "3.0.24",
"@ai-sdk/openai": "3.0.23",
"@apidevtools/swagger-parser": "10.1.0",
"ai": "6.0.62",
"cac": "6.7.14",
"cosmiconfig": "9.0.0",
"lodash": "4.17.23",
"prettier": "3.3.2",
"swagger2openapi": "7.0.8",
"ts-pattern": "5.2.0"
},
"devDependencies": {
"@changesets/cli": "2.29.8",
"@types/lodash": "4.17.6",
"@types/node": "20.19.30",
"lefthook": "1.6.18",
"msw": "2.7.3",
"oazapfts": "6.1.0",
"openapi-types": "12.1.3",
"tsup": "8.5.1",
"typescript": "5.5.3",
"vitest": "4.0.18",
"zod": "^3.25.76"
},
"peerDependencies": {
"@faker-js/faker": ">=8",
"msw": ">=2"
},
"repository": {
"type": "git",
"url": "git+https://github.com/zoubingwu/msw-auto-mock.git"
},
"bugs": {
"url": "https://github.com/zoubingwu/msw-auto-mock/issues"
},
"homepage": "https://github.com/zoubingwu/msw-auto-mock",
"files": [
"dist"
],
"keywords": [
"msw",
"mock",
"service-worker",
"openapi"
],
"publishConfig": {
"access": "public"
},
"pnpm": {
"overrides": {
"js-yaml@3.14.1": "3.14.2",
"js-yaml@4.1.0": "4.1.1"
}
},
"packageManager": "pnpm@10.6.1"
}
================================================
FILE: pnpm-workspace.yaml
================================================
packages:
- example
- .
onlyBuiltDependencies:
- msw
================================================
FILE: scripts/changelog.sh
================================================
#!/bin/bash
# Get the repository URL from package.json
REPO_URL=$(node -e "console.log(require('./package.json').repository.url.replace(/\.git$/, ''))")
# Fetch all tags
git fetch --all --tags
# Get the last tag
LAST_TAG=$(git describe --tags --abbrev=0)
# Generate and store changelog
CHANGELOG=$(git log ${LAST_TAG}..HEAD --pretty=format:"- %s" | \
sed -E "s|#([0-9]+)|[#\1](${REPO_URL}/pull/\1)|g")
# Print to terminal
echo "Changelog since ${LAST_TAG}:"
echo "$CHANGELOG"
echo
# Copy to clipboard
echo "$CHANGELOG" | pbcopy
echo "Changelog has been copied to clipboard!"
================================================
FILE: src/cli.ts
================================================
import cac from 'cac';
import { generate } from './generate';
import { version } from '../package.json';
const cli = cac();
cli
.command(
'<spec>',
'Generate MSW mock definitions from an OpenAPI spec (faker by default; generative AI optional via config).',
)
.option('-o, --output <directory>', `Output to a folder.`)
.option('-m, --max-array-length <number>', `Max array length, default to 20.`)
.option('-t, --includes <keywords>', `Include the request path with given string, can be seperated with comma.`)
.option('-e, --excludes <keywords>', `Exclude the request path with given string, can be seperated with comma.`)
.option('--base-url [baseUrl]', `Use the one you specified or server url in OpenAPI description as base url.`)
.option('--static', 'By default it will generate dynamic mocks, use this flag if you want generate static mocks.')
.option('-c, --codes <keywords>', 'Comma separated list of status codes to generate responses for')
.option('--typescript', 'Generate TypeScript files instead of JavaScript files')
.option('--echo-request-body', 'Merge JSON request body into JSON response body for write requests (POST/PUT/PATCH)')
.example('msw-auto-mock ./githubapi.yaml -o mock.js')
.example('msw-auto-mock ./githubapi.yaml -o mock.js -t /admin,/repo -m 30')
.example('msw-auto-mock ./githubapi.yaml -o mock.js --typescript')
.example(
'package.json: { "msw-auto-mock": { "ai": { "enable": true, "provider": "openai", "openai": { "apiKey": "process.env.OPENAI_API_KEY", "model": "gpt-4o" } } } }',
)
.action(async (spec, options) => {
await generate(spec, options).catch(console.error);
});
cli.help();
cli.version(version);
cli.parse();
================================================
FILE: src/generate.ts
================================================
import * as fs from 'node:fs';
import * as path from 'node:path';
import ApiGenerator, { isReference } from 'oazapfts/generate';
import { OpenAPIV3 } from 'openapi-types';
import camelCase from 'lodash/camelCase';
import { cosmiconfig } from 'cosmiconfig';
import { getV3Doc } from './swagger';
import { prettify, toExpressLikePath } from './utils';
import { Operation } from './transform';
import { browserIntegration, mockTemplate, nodeIntegration, reactNativeIntegration } from './template';
import { CliOptions, ConfigOptions } from './types';
import { name as moduleName } from '../package.json';
export function generateOperationCollection(apiDoc: OpenAPIV3.Document, options: CliOptions) {
const apiGen = new ApiGenerator(apiDoc, {});
const operationDefinitions = getOperationDefinitions(apiDoc);
return operationDefinitions
.filter(op => operationFilter(op, options))
.map(op => codeFilter(op, options))
.map(definition => toOperation(definition, apiGen));
}
export async function generate(spec: string, inlineOptions: CliOptions) {
const explorer = cosmiconfig(moduleName);
const finalOptions: ConfigOptions = { ...inlineOptions };
try {
const result = await explorer.search();
if (!result?.isEmpty) {
Object.assign(finalOptions, result?.config);
}
} catch (e) {
console.log(e);
process.exit(1);
}
const { output: outputFolder } = finalOptions;
const targetFolder = path.resolve(process.cwd(), outputFolder);
const fileExt = finalOptions.typescript ? '.ts' : '.js';
let code: string;
const apiDoc = await getV3Doc(spec);
const operationCollection = generateOperationCollection(apiDoc, finalOptions);
let baseURL = '';
if (finalOptions.baseUrl === true) {
baseURL = getServerUrl(apiDoc);
} else if (typeof finalOptions.baseUrl === 'string') {
baseURL = finalOptions.baseUrl;
}
code = mockTemplate(operationCollection, baseURL, finalOptions);
try {
fs.mkdirSync(targetFolder);
} catch {}
fs.writeFileSync(path.resolve(process.cwd(), targetFolder, `native${fileExt}`), reactNativeIntegration);
fs.writeFileSync(path.resolve(process.cwd(), targetFolder, `node${fileExt}`), nodeIntegration);
fs.writeFileSync(path.resolve(process.cwd(), targetFolder, `browser${fileExt}`), browserIntegration);
fs.writeFileSync(
path.resolve(process.cwd(), targetFolder, `handlers${fileExt}`),
await prettify(`handlers${fileExt}`, code),
);
}
function getServerUrl(apiDoc: OpenAPIV3.Document) {
let server = apiDoc.servers?.at(0);
let url = '';
if (server) {
url = server.url;
}
if (server?.variables) {
Object.entries(server.variables).forEach(([key, value]) => {
url = url.replace(`{${key}}`, value.default);
});
}
return url;
}
const operationKeys = Object.values(OpenAPIV3.HttpMethods) as OpenAPIV3.HttpMethods[];
type OperationDefinition = {
path: string;
verb: string;
responses: OpenAPIV3.ResponsesObject;
id: string;
};
function getOperationDefinitions(v3Doc: OpenAPIV3.Document): OperationDefinition[] {
return Object.entries(v3Doc.paths).flatMap(([path, pathItem]) =>
!pathItem
? []
: Object.entries(pathItem)
.filter((arg): arg is [string, OpenAPIV3.OperationObject] => operationKeys.includes(arg[0] as any))
.map(([verb, operation]) => {
const id = camelCase(operation.operationId ?? verb + '/' + path);
return {
path,
verb,
id,
responses: operation.responses,
};
}),
);
}
function operationFilter(operation: OperationDefinition, options: CliOptions): boolean {
const includes = options?.includes?.split(',') ?? null;
const excludes = options?.excludes?.split(',') ?? null;
if (includes && !includes.includes(operation.path)) {
return false;
}
if (excludes?.includes(operation.path)) {
return false;
}
return true;
}
function codeFilter(operation: OperationDefinition, options: CliOptions): OperationDefinition {
const rawCodes = options?.codes;
const codes = rawCodes ? (rawCodes.indexOf(',') !== -1 ? rawCodes?.split(',') : [rawCodes]) : null;
const responses = Object.entries(operation.responses)
.filter(([code]) => {
if (codes && !codes.includes(code)) {
return false;
}
return true;
})
.map(([code, response]) => ({
[code]: response,
}))
.reduce((acc, curr) => Object.assign(acc, curr), {} as OpenAPIV3.ResponsesObject);
return {
...operation,
responses,
};
}
function toOperation(definition: OperationDefinition, apiGen: ApiGenerator): Operation {
const { verb, path, responses, id } = definition;
const responseMap = Object.entries(responses).map(([code, response]) => {
const content = apiGen.resolve(response).content;
if (!content) {
return { code, id: '', responses: {} };
}
const resolvedResponse = Object.keys(content).reduce(
(resolved, type) => {
const schema = content[type].schema;
if (typeof schema !== 'undefined') {
resolved[type] = recursiveResolveSchema(schema, apiGen);
}
return resolved;
},
{} as Record<string, OpenAPIV3.SchemaObject>,
);
return {
code,
id,
responses: resolvedResponse,
};
});
return {
verb,
path: toExpressLikePath(path),
response: responseMap,
};
}
const resolvingRefs: string[] = [];
function autoPopRefs<T>(cb: () => T) {
const n = resolvingRefs.length;
const res = cb();
resolvingRefs.length = n;
return res;
}
function resolve(schema: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject, apiGen: ApiGenerator) {
if (isReference(schema)) {
if (resolvingRefs.includes(schema.$ref)) {
console.warn(`circular reference for path ${[...resolvingRefs, schema.$ref].join(' -> ')} found`);
return {};
}
resolvingRefs.push(schema.$ref);
}
return { ...apiGen.resolve(schema) };
}
function recursiveResolveSchema(schema: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject, apiGen: ApiGenerator) {
return autoPopRefs(() => {
const resolvedSchema = resolve(schema, apiGen) as OpenAPIV3.SchemaObject;
// OpenAPI examples may reference components via $ref; resolve them early so
// we don't emit `{ $ref: ... }` as literal example data.
const exampleRef = (resolvedSchema as any)?.example?.$ref;
if (typeof exampleRef === 'string') {
resolvedSchema.example = resolve({ $ref: exampleRef } as any, apiGen) as any;
}
if (resolvedSchema.type === 'array') {
resolvedSchema.items = resolve(resolvedSchema.items, apiGen);
resolvedSchema.items = recursiveResolveSchema(resolvedSchema.items, apiGen);
} else if (resolvedSchema.type === 'object') {
if (!resolvedSchema.properties && typeof resolvedSchema.additionalProperties === 'object') {
if (isReference(resolvedSchema.additionalProperties)) {
resolvedSchema.additionalProperties = recursiveResolveSchema(
resolve(resolvedSchema.additionalProperties, apiGen),
apiGen,
);
}
}
if (resolvedSchema.properties) {
resolvedSchema.properties = Object.entries(resolvedSchema.properties).reduce(
(resolved, [key, value]) => {
resolved[key] = recursiveResolveSchema(value, apiGen);
return resolved;
},
{} as Record<string, OpenAPIV3.SchemaObject>,
);
}
}
if (resolvedSchema.allOf) {
resolvedSchema.allOf = resolvedSchema.allOf.map(item => recursiveResolveSchema(item, apiGen));
} else if (resolvedSchema.oneOf) {
resolvedSchema.oneOf = resolvedSchema.oneOf.map(item => recursiveResolveSchema(item, apiGen));
} else if (resolvedSchema.anyOf) {
resolvedSchema.anyOf = resolvedSchema.anyOf.map(item => recursiveResolveSchema(item, apiGen));
}
return resolvedSchema;
});
}
================================================
FILE: src/swagger.ts
================================================
import SwaggerParser from '@apidevtools/swagger-parser';
import type { OpenAPIV3 } from 'openapi-types';
// @ts-ignore lack of d.ts file
import converter from 'swagger2openapi';
export async function getV3Doc(spec: string): Promise<OpenAPIV3.Document> {
const doc = await SwaggerParser.bundle(spec);
const isOpenApiV3 = 'openapi' in doc && doc.openapi.startsWith('3');
if (isOpenApiV3) {
return doc as OpenAPIV3.Document;
} else {
const result = await converter.convertObj(doc, {});
return result.openapi as OpenAPIV3.Document;
}
}
================================================
FILE: src/template.ts
================================================
import { ConfigOptions } from './types';
import { OperationCollection, transformToHandlerCode, transformToGenerateResultFunctions } from './transform';
import { match } from 'ts-pattern';
import { DEFAULT_MAX_ARRAY_LENGTH, DEFAULT_MAX_STRING_LENGTH, normalizeNonNegativeInt } from './utils';
const getImportsCode = () => {
const imports = [`import { HttpResponse, http } from 'msw';`, `import { faker } from '@faker-js/faker';`];
return imports.join('\n');
};
const withApiCounterCode = (options: ConfigOptions) => `
// Map to store counters for each API endpoint
const apiCounters = new Map${options.typescript ? '<string, number>' : ''}();
const next = (apiKey${options.typescript ? ': string' : ''}) => {
let currentCount = apiCounters.get(apiKey) ?? 0;
if (currentCount === Number.MAX_SAFE_INTEGER - 1) {
currentCount = 0;
}
apiCounters.set(apiKey, currentCount + 1);
return currentCount;
};
`;
export const mockTemplate = (operationCollection: OperationCollection, baseURL: string, options: ConfigOptions) => {
assertAiConfig(options);
const maxArrayLength = normalizeNonNegativeInt(options?.maxArrayLength, DEFAULT_MAX_ARRAY_LENGTH);
return `/**
* This file is AUTO GENERATED by [msw-auto-mock](https://github.com/zoubingwu/msw-auto-mock)
* Feel free to commit/edit it as you need.
*/
/* eslint-disable */
/* tslint:disable */
// @ts-nocheck
${getImportsCode()}
${createAiGenerateText(options)}
${withCacheOne(options)}
${withCreatePrompt(options)}
faker.seed(1);
const baseURL = '${baseURL}';
${options.static ? '' : `const MAX_ARRAY_LENGTH = ${maxArrayLength};`}
${options.static ? '' : `const MAX_STRING_LENGTH = ${DEFAULT_MAX_STRING_LENGTH};`}
${withApiCounterCode(options)}
export const handlers = [
${transformToHandlerCode(operationCollection, options)}
];
${transformToGenerateResultFunctions(operationCollection, baseURL, options)}
`;
};
export const browserIntegration = [
`import { setupWorker } from 'msw/browser'`,
`import { handlers } from './handlers'`,
`export const worker = setupWorker(...handlers)`,
].join('\n');
export const nodeIntegration = [
`import { setupServer } from 'msw/node'`,
`import { handlers } from './handlers'`,
`export const server = setupServer(...handlers)`,
].join(`\n`);
export const reactNativeIntegration = [
`import { setupServer } from 'msw/native'`,
`import { handlers } from './handlers'`,
// Avoid TS4094 by erasing private/protected members from the inferred class type.
`type NativeServer = Pick<ReturnType<typeof setupServer>, 'listen' | 'close' | 'use' | 'restoreHandlers' | 'resetHandlers' | 'listHandlers' | 'events'>`,
`export const server: NativeServer = setupServer(...handlers)`,
].join(`\n`);
const toJsExpr = (value?: string) => {
if (value == null) return 'undefined';
const v = value.trim();
// If the user already provided an expression or explicit quotes, keep it.
if (v.startsWith('"') || v.startsWith("'") || v.startsWith('`')) return v;
if (v.startsWith('process.env.') || v.startsWith('import.meta.env.') || v.startsWith('Deno.env.')) return v;
if (v.startsWith('globalThis.') || v.startsWith('window.')) return v;
// Otherwise treat it as a plain string literal.
return JSON.stringify(v);
};
function assertAiConfig(options: ConfigOptions) {
if (!options.ai?.enable) return;
const provider = options.ai?.provider;
if (!provider) {
throw new Error('[msw-auto-mock] ai.enable is true but ai.provider is missing');
}
if (provider === 'openai') {
if (!options.ai?.openai?.model) {
throw new Error('[msw-auto-mock] ai.enable is true but ai.openai.model is missing');
}
return;
}
if (provider === 'azure') {
if (!options.ai?.azure?.deployment) {
throw new Error('[msw-auto-mock] ai.enable is true but ai.azure.deployment is missing');
}
return;
}
if (provider === 'anthropic') {
if (!options.ai?.anthropic?.model) {
throw new Error('[msw-auto-mock] ai.enable is true but ai.anthropic.model is missing');
}
}
}
const askOpenai = (options: ConfigOptions) => `
import { createOpenAI } from '@ai-sdk/openai';
import { generateText } from 'ai';
async function ask(operation) {
const { text } = await generateText({
model: createOpenAI({
apiKey: ${toJsExpr(options.ai?.openai?.apiKey)},
baseURL: ${toJsExpr(options.ai?.openai?.baseURL)},
})(${toJsExpr(options.ai?.openai?.model)}),
prompt: createPrompt(operation),
});
return JSON.parse(text);
}
`;
const askAzure = (options: ConfigOptions) => `
import { createAzure } from '@ai-sdk/azure';
import { generateText } from 'ai';
async function ask(operation) {
const { text } = await generateText({
model: createAzure({
resourceName: ${toJsExpr(options.ai?.azure?.resource)},
apiKey: ${toJsExpr(options.ai?.azure?.apiKey)}
})(${toJsExpr(options.ai?.azure?.deployment)}),
prompt: createPrompt(operation),
});
return JSON.parse(text);
}
`;
const askAnthropic = (options: ConfigOptions) => `
import { createAnthropic } from '@ai-sdk/anthropic';
import { generateText } from 'ai';
async function ask(operation) {
const { text } = await generateText({
model: createAnthropic({
apiKey: ${toJsExpr(options.ai?.anthropic?.apiKey)}
})(${toJsExpr(options.ai?.anthropic?.model)}),
prompt: createPrompt(operation),
});
return JSON.parse(text);
}
`;
const withCreatePrompt = (options: ConfigOptions) =>
options.ai?.enable
? `
function createPrompt(operation) {
return "Given the following Swagger (OpenAPI) definition, generate a mock data object that conforms to the specified response structure, ensuring each property adheres to its defined constraints, especially type, format, example, description, enum values, ignore the xml field. The generated JSON string should include all the properties defined in the Swagger schema as much as possible and the values should be valid based on the property definitions (e.g., integer, string, length etc.) and rules (e.g, int64 should be string in json etc.). Please only return the JSON string as the output, don't wrap it with markdown. The definition is like below: \\n" + "\`\`\`json" + JSON.stringify(operation, null, 4) + "\\n\`\`\`";
}
`
: '';
export function createAiGenerateText(options: ConfigOptions): string {
if (!options.ai?.enable) return '';
let code = match(options.ai?.provider)
.with('openai', () => askOpenai(options))
.with('azure', () => askAzure(options))
.with('anthropic', () => askAnthropic(options))
.otherwise(() => '');
return code;
}
export function withCacheOne(options: ConfigOptions) {
if (options.static && options.ai?.enable) {
return `
const cache = new Map();
const withCacheOne = (ask) => async (operation) => {
const key = operation.verb + ' ' + operation.path;
if (cache.has(key)) return cache.get(key);
const value = await ask(operation);
cache.set(key, value);
return value;
}`;
}
return '';
}
================================================
FILE: src/transform.ts
================================================
import vm from 'node:vm';
import { OpenAPIV3 } from 'openapi-types';
import merge from 'lodash/merge';
import camelCase from 'lodash/camelCase';
import { faker } from '@faker-js/faker';
import { ConfigOptions } from './types';
import { DEFAULT_MAX_ARRAY_LENGTH, DEFAULT_MAX_STRING_LENGTH, isValidRegExp, normalizeNonNegativeInt } from './utils';
const MAX_STRING_LENGTH = DEFAULT_MAX_STRING_LENGTH;
export interface ResponseMap {
code: string;
id: string;
responses?: Record<string, OpenAPIV3.SchemaObject>;
}
export interface Operation {
verb: string;
path: string;
response: ResponseMap[];
}
export type OperationCollection = Operation[];
export function getResIdentifierName(res: ResponseMap) {
if (!res.id) {
return '';
}
return camelCase(`get ${res.id}${res.code}Response`);
}
export function transformToGenerateResultFunctions(
operationCollection: OperationCollection,
baseURL: string,
options?: ConfigOptions,
): string {
const context = {
faker,
MAX_STRING_LENGTH,
MAX_ARRAY_LENGTH: normalizeNonNegativeInt(options?.maxArrayLength, DEFAULT_MAX_ARRAY_LENGTH),
baseURL: baseURL ?? '',
result: null,
};
vm.createContext(context);
return operationCollection
.map(op =>
op.response
.map(r => {
const name = getResIdentifierName(r);
if (!name) {
return '';
}
const useFaker = options?.ai?.enable !== true;
if (useFaker) {
if (!r.responses) {
return;
}
const jsonResponseKey = Object.keys(r.responses).filter(r => r.startsWith('application/json'))[0];
const fakerResult = transformJSONSchemaToFakerCode(r.responses?.[jsonResponseKey]);
if (options?.static) {
vm.runInContext(`result = ${fakerResult};`, context);
}
return [
`export function `,
`${name}() { `,
`return ${options?.static ? JSON.stringify(context.result) : fakerResult} `,
`};\n`,
].join('\n');
}
if (!r.responses) {
return;
}
const jsonResponseKey = Object.keys(r.responses).filter(r => r.startsWith('application/json'))[0];
const operationString = JSON.stringify(r.responses?.[jsonResponseKey], null, 4);
return [
`export async function `,
`${name}() { `,
`return await ${options.static ? `withCacheOne(ask)(${operationString})` : `ask(${operationString})`} `,
`};\n`,
].join('\n');
})
.join('\n'),
)
.join('\n');
}
function scoreHandlerPath(path: string) {
const segments = path.split('/').filter(Boolean);
const dynamicSegments = segments.filter(seg => seg.startsWith(':')).length;
return {
dynamicSegments,
totalSegments: segments.length,
normalized: segments.join('/'),
};
}
function compareOperationsForMsw(a: Operation, b: Operation) {
const sa = scoreHandlerPath(a.path);
const sb = scoreHandlerPath(b.path);
// MSW matches parameterized routes broadly, so put more specific/static routes first.
if (sa.dynamicSegments !== sb.dynamicSegments) {
return sa.dynamicSegments - sb.dynamicSegments;
}
// Prefer longer paths (more segments) first when they have the same dynamic count.
if (sa.totalSegments !== sb.totalSegments) {
return sb.totalSegments - sa.totalSegments;
}
// Keep output deterministic.
if (a.verb !== b.verb) {
return a.verb.localeCompare(b.verb);
}
return sa.normalized.localeCompare(sb.normalized);
}
export function transformToHandlerCode(operationCollection: OperationCollection, options: ConfigOptions): string {
return [...operationCollection]
.sort(compareOperationsForMsw)
.map(op => {
return `http.${op.verb}(\`\${baseURL}${op.path}\`, async ({ request }) => {
const shouldEchoRequestBody = ${Boolean((options as any)?.echoRequestBody)};
let requestJson = null;
if (shouldEchoRequestBody && ['post', 'put', 'patch'].includes(${JSON.stringify(op.verb)})) {
try {
requestJson = await request.clone().json();
} catch (e) {
requestJson = null;
}
}
const resultArray = [${op.response.map(response => {
const identifier = getResIdentifierName(response);
const statusCode = parseInt(response?.code!);
const safeStatusCode = Number.isFinite(statusCode) ? statusCode : 500;
const result =
safeStatusCode === 204
? `[undefined, { status: ${safeStatusCode} }]`
: `[${identifier ? `await ${identifier}()` : 'undefined'}, { status: ${safeStatusCode} }]`;
return result;
})}]${options.typescript ? `as [any, { status: number }][]` : ''};
const [body, init] = resultArray[next(\`${op.verb} ${op.path}\`) % resultArray.length];
const responseJson = requestJson && body && typeof body === 'object' && !Array.isArray(body) ? { ...body, ...requestJson } : body;
return HttpResponse.json(responseJson, init)
}),\n`;
})
.join(' ')
.trimEnd();
}
export function transformJSONSchemaToFakerCode(jsonSchema?: OpenAPIV3.SchemaObject, key?: string): string {
if (!jsonSchema) {
return 'null';
}
if (jsonSchema.example) {
if (jsonSchema.example.$ref) {
}
return JSON.stringify(jsonSchema.example);
}
if (Array.isArray(jsonSchema.type)) {
return `faker.helpers.arrayElement([${jsonSchema.type
.map(type => transformJSONSchemaToFakerCode({ ...jsonSchema, type }))
.join(',')}])`;
}
if (jsonSchema.enum) {
return `faker.helpers.arrayElement(${JSON.stringify(jsonSchema.enum)})`;
}
if (jsonSchema.allOf) {
const { allOf, ...rest } = jsonSchema;
return transformJSONSchemaToFakerCode(merge({}, ...allOf, rest));
}
if (jsonSchema.oneOf) {
const schemas = jsonSchema.oneOf as OpenAPIV3.SchemaObject[];
return `faker.helpers.arrayElement([${schemas.map(i => transformJSONSchemaToFakerCode(i))}])`;
}
if (jsonSchema.anyOf) {
const schemas = jsonSchema.anyOf as OpenAPIV3.SchemaObject[];
return `faker.helpers.arrayElement([${schemas.map(i => transformJSONSchemaToFakerCode(i))}])`;
}
switch (jsonSchema.type) {
case 'string':
return transformStringBasedOnFormat(jsonSchema, key);
case 'number':
case 'integer':
const params = JSON.stringify({ min: jsonSchema.minimum, max: jsonSchema.maximum });
if (jsonSchema.minimum || jsonSchema.maxItems) {
return `faker.number.int(${params})`;
}
return `faker.number.int()`;
case 'boolean':
return `faker.datatype.boolean()`;
case 'object':
if (!jsonSchema.properties && typeof jsonSchema.additionalProperties === 'object') {
return `[...new Array(5).keys()].map(_ => ({ [faker.lorem.word()]: ${transformJSONSchemaToFakerCode(
jsonSchema.additionalProperties as OpenAPIV3.SchemaObject,
)} })).reduce((acc, next) => Object.assign(acc, next), {})`;
}
return `{
${Object.entries(jsonSchema.properties ?? {})
.map(([k, v]) => {
return `${JSON.stringify(k)}: ${transformJSONSchemaToFakerCode(v as OpenAPIV3.SchemaObject, k)}`;
})
.join(',\n')}
}`;
case 'array': {
const minItems = normalizeNonNegativeInt(jsonSchema.minItems);
const maxItems = normalizeNonNegativeInt(jsonSchema.maxItems);
const minItemsValue = minItems ?? 1;
const maxItemsValue = maxItems !== undefined ? `Math.min(${maxItems}, MAX_ARRAY_LENGTH)` : 'MAX_ARRAY_LENGTH';
return `(() => {
const arrayMin = ${minItemsValue};
const arrayMax = ${maxItemsValue};
const safeMin = Math.min(arrayMin, arrayMax);
return [...new Array(faker.number.int({ min: safeMin, max: arrayMax })).keys()].map(_ => (${transformJSONSchemaToFakerCode(
jsonSchema.items as OpenAPIV3.SchemaObject,
)}));
})()`;
}
default:
return 'null';
}
}
/**
* See https://json-schema.org/understanding-json-schema/reference/string.html#built-in-formats
*/
function transformStringBasedOnFormat(schema: OpenAPIV3.NonArraySchemaObject, key?: string) {
const { format, minLength, maxLength, pattern } = schema;
if (format === 'date-time' || key?.toLowerCase().endsWith('_at')) {
return `faker.date.anytime().toISOString()`;
} else if (format === 'time') {
return `new Date().toISOString().substring(11, 16)`;
} else if (format === 'date') {
return `faker.date.past().toISOString().substring(0,10)`;
} else if (format === 'uuid' || key?.toLowerCase() === 'id' || key?.toLowerCase().endsWith('id')) {
return `faker.string.uuid()`;
} else if (['idn-email', 'email'].includes(format ?? '') || key?.toLowerCase().includes('email')) {
return `faker.internet.email()`;
} else if (['hostname', 'idn-hostname'].includes(format ?? '')) {
return `faker.internet.domainName()`;
} else if (format === 'ipv4') {
return `faker.internet.ip()`;
} else if (format === 'ipv6') {
return `faker.internet.ipv6()`;
} else if (
['uri', 'uri-reference', 'iri', 'iri-reference', 'uri-template'].includes(format ?? '') ||
key?.toLowerCase().includes('url')
) {
if (['photo', 'image', 'picture'].some(image => key?.toLowerCase().includes(image))) {
return `faker.image.url()`;
}
return `faker.internet.url()`;
} else if (key?.toLowerCase().endsWith('name')) {
return `faker.person.fullName()`;
} else if (key?.toLowerCase().includes('street')) {
return `faker.location.streetAddress()`;
} else if (key?.toLowerCase().includes('city')) {
return `faker.location.city()`;
} else if (key?.toLowerCase().includes('state')) {
return `faker.location.state()`;
} else if (key?.toLowerCase().includes('zip')) {
return `faker.location.zipCode()`;
}
if (minLength && maxLength) {
return `faker.string.alpha({ length: { min: ${minLength}, max: ${maxLength} }})`;
} else if (minLength) {
return `faker.string.alpha({ length: { min: ${minLength}, max: MAX_STRING_LENGTH }})`;
} else if (maxLength) {
return `faker.string.alpha({ length: { min: 0, max: ${maxLength} }})`;
}
if (pattern && isValidRegExp(pattern)) {
// OpenAPI `pattern` is a bare regex source (e.g. ^[a-z]{2,}$), not a JS literal.
// Some users still pass JS regex literals as strings (e.g. '/^foo$/i'); support both.
if (pattern.startsWith('/')) {
return `faker.helpers.fromRegExp(${pattern})`;
}
// Use `new RegExp()` with a JSON-escaped string to avoid syntax errors.
return `faker.helpers.fromRegExp(new RegExp(${JSON.stringify(pattern)}))`;
}
return `faker.lorem.words()`;
}
================================================
FILE: src/types.ts
================================================
export interface CliOptions {
output: string;
maxArrayLength?: number;
includes?: string;
excludes?: string;
baseUrl?: string | true;
codes?: string;
static?: boolean;
typescript?: boolean;
/**
* When enabled, JSON responses for write requests (POST/PUT/PATCH) will merge
* the request JSON body into the generated response body.
*/
echoRequestBody?: boolean;
}
export type ConfigOptions = CliOptions & {
typescript?: boolean;
ai?: {
enable?: boolean;
provider: 'openai' | 'azure' | 'anthropic';
openai?: {
baseURL?: string;
/**
* defaults to `OPENAI_API_KEY`
*/
apiKey?: string;
model?: string;
};
azure?: {
/**
* defaults to `AZURE_API_KEY`
*/
apiKey?: string;
resource?: string;
deployment?: string;
};
anthropic?: {
/**
* defaults to `ANTHROPIC_API_KEY`
*/
apiKey?: string;
model?: string;
};
};
};
================================================
FILE: src/utils.ts
================================================
import * as prettier from 'prettier';
import * as path from 'path';
import camelCase from 'lodash/camelCase';
export const DEFAULT_MAX_ARRAY_LENGTH = 20;
export const DEFAULT_MAX_STRING_LENGTH = 42;
export const normalizeNonNegativeInt = (value: unknown, fallback?: number) => {
if (value === undefined || value === null) {
return fallback;
}
const raw = typeof value === 'string' && value.trim() === '' ? NaN : Number(value);
if (!Number.isFinite(raw)) {
return fallback;
}
const normalized = Math.floor(raw);
if (normalized < 0) {
return 0;
}
return normalized;
};
const EXTENSION_TO_PARSER: Record<string, string> = {
ts: 'typescript',
tsx: 'typescript',
js: 'babel',
jsx: 'babel',
'js.flow': 'flow',
flow: 'flow',
gql: 'graphql',
graphql: 'graphql',
css: 'postcss',
scss: 'postcss',
less: 'postcss',
stylus: 'postcss',
markdown: 'markdown',
md: 'markdown',
json: 'json',
};
export async function prettify(filePath: string | null, content: string): Promise<string> {
let config = null;
let parser = 'typescript';
if (filePath) {
const fileExtension = path.extname(filePath).slice(1);
parser = EXTENSION_TO_PARSER[fileExtension];
config = await prettier.resolveConfig(process.cwd(), {
useCache: true,
editorconfig: true,
});
}
try {
return prettier.format(content, {
parser,
...config,
// disable plugins
plugins: [],
});
} catch (e) {
// ignore error
return content;
}
}
export const toExpressLikePath = (path: string) =>
// use `.+?` for lazy match
path.replace(/{(.+?)}/g, (_match, p1: string) => `:${camelCase(p1)}`);
export const isValidRegExp = (regExpCandidate: string) => {
var isValid = true;
try {
new RegExp(regExpCandidate);
} catch (e) {
isValid = false;
}
return isValid;
};
================================================
FILE: test/ai-runtime.spec.ts
================================================
import { describe, expect, it, vi } from 'vitest';
import { createAiGenerateText } from '../src/template';
// This test runs the generated `ask()` function with mocked dependencies.
// It ensures the generated runtime awaits the AI call and parses JSON correctly.
describe('ai runtime: generated ask()', () => {
it('awaits generateText() and returns parsed JSON', async () => {
const code = createAiGenerateText({
output: '',
ai: {
enable: true,
provider: 'openai',
openai: {
apiKey: 'process.env.OPENAI_API_KEY',
model: 'gpt-5.2',
},
},
} as any);
// Strip ESM imports so we can eval the function in this test environment.
const body = code
.split('\n')
.filter(line => !line.startsWith('import '))
.join('\n');
const createOpenAI = vi.fn(() => () => 'mock-model');
const generateText = vi.fn(async () => ({ text: '{"hello":"world"}' }));
// The generated code expects a `createPrompt()` function.
function createPrompt(_operation: unknown) {
return 'prompt';
}
// Evaluate the generated `ask()` and grab it back.
// eslint-disable-next-line no-eval
const ask = eval(`(() => {\n${body}\n; return ask; })()`);
const result = await ask({});
expect(createOpenAI).toHaveBeenCalledTimes(1);
expect(generateText).toHaveBeenCalledTimes(1);
expect(result).toEqual({ hello: 'world' });
});
});
================================================
FILE: test/fixture/githubapi.yaml
================================================
---
openapi: 3.0.3
info:
version: 1.1.4
title: GitHub v3 REST API
description: GitHub's v3 REST API.
license:
name: MIT
url: https://spdx.org/licenses/MIT
termsOfService: https://docs.github.com/articles/github-terms-of-service
contact:
name: Support
url: https://support.github.com/contact?tags=dotcom-rest-api
tags:
- name: actions
description: Endpoints to manage GitHub Actions using the REST API.
- name: activity
description: Activity APIs provide access to notifications, subscriptions, and timelines.
- name: apps
description: Information for integrations and installations.
- name: billing
description: Monitor charges and usage from Actions and Packages.
- name: checks
description: Rich interactions with checks run by your integrations.
- name: code-scanning
description: Retrieve code scanning alerts from a repository.
- name: codes-of-conduct
description: Insight into codes of conduct for your communities.
- name: codespaces
description: Endpoints to manage Codespaces using the REST API.
- name: emojis
description: List emojis available to use on GitHub.
- name: enterprise-admin
description: Administer a GitHub enterprise.
- name: gists
description: View, modify your gists.
- name: git
description: Raw Git functionality.
- name: gitignore
description: View gitignore templates
- name: interactions
description: Owner or admin management of users interactions.
- name: issues
description: Interact with GitHub Issues.
- name: licenses
description: View various OSS licenses.
- name: markdown
description: Render Github flavored markdown
- name: meta
description: Endpoints that give information about the API.
- name: migrations
description: Move projects to or from GitHub.
- name: oauth-authorizations
description: Manage access of OAuth applications
- name: orgs
description: Interact with GitHub Orgs.
- name: packages
description: Manage packages for authenticated users and organizations.
- name: projects
description: Interact with GitHub Projects.
- name: pulls
description: Interact with GitHub Pull Requests.
- name: rate-limit
description: Check your current rate limit status
- name: reactions
description: Interact with reactions to various GitHub entities.
- name: repos
description: Interact with GitHub Repos.
- name: scim
description: Provisioning of GitHub organization membership for SCIM-enabled providers.
- name: search
description: Look for stuff on GitHub.
- name: secret-scanning
description: Retrieve secret scanning alerts from a repository.
- name: server-statistics
description: GHES statistics
- name: teams
description: Interact with GitHub Teams.
- name: users
description: Interact with and view information about users and also current user.
servers:
- url: "{protocol}://{hostname}/api/v3"
variables:
hostname:
description: Self-hosted Enterprise Server or Enterprise Cloud hostname
default: HOSTNAME
protocol:
description: Self-hosted Enterprise Server or Enterprise Cloud protocol
default: http
externalDocs:
description: GitHub Enterprise Developer Docs
url: https://docs.github.com/enterprise-server@3.3/rest/
paths:
"/":
get:
summary: GitHub API Root
description: Get Hypermedia links to resources accessible in GitHub's REST API
tags:
- meta
operationId: meta/root
responses:
'200':
description: Response
content:
application/json:
schema:
type: object
properties:
current_user_url:
type: string
format: uri-template
current_user_authorizations_html_url:
type: string
format: uri-template
authorizations_url:
type: string
format: uri-template
code_search_url:
type: string
format: uri-template
commit_search_url:
type: string
format: uri-template
emails_url:
type: string
format: uri-template
emojis_url:
type: string
format: uri-template
events_url:
type: string
format: uri-template
feeds_url:
type: string
format: uri-template
followers_url:
type: string
format: uri-template
following_url:
type: string
format: uri-template
gists_url:
type: string
format: uri-template
hub_url:
type: string
format: uri-template
issue_search_url:
type: string
format: uri-template
issues_url:
type: string
format: uri-template
keys_url:
type: string
format: uri-template
label_search_url:
type: string
format: uri-template
notifications_url:
type: string
format: uri-template
organization_url:
type: string
format: uri-template
organization_repositories_url:
type: string
format: uri-template
organization_teams_url:
type: string
format: uri-template
public_gists_url:
type: string
format: uri-template
rate_limit_url:
type: string
format: uri-template
repository_url:
type: string
format: uri-template
repository_search_url:
type: string
format: uri-template
current_user_repositories_url:
type: string
format: uri-template
starred_url:
type: string
format: uri-template
starred_gists_url:
type: string
format: uri-template
topic_search_url:
type: string
format: uri-template
user_url:
type: string
format: uri-template
user_organizations_url:
type: string
format: uri-template
user_repositories_url:
type: string
format: uri-template
user_search_url:
type: string
format: uri-template
required:
- current_user_url
- current_user_authorizations_html_url
- authorizations_url
- code_search_url
- commit_search_url
- emails_url
- emojis_url
- events_url
- feeds_url
- followers_url
- following_url
- gists_url
- hub_url
- issue_search_url
- issues_url
- keys_url
- label_search_url
- notifications_url
- organization_url
- organization_repositories_url
- organization_teams_url
- public_gists_url
- rate_limit_url
- repository_url
- repository_search_url
- current_user_repositories_url
- starred_url
- starred_gists_url
- user_url
- user_organizations_url
- user_repositories_url
- user_search_url
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: meta
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/overview/resources-in-the-rest-api#root-endpoint
"/admin/hooks":
get:
summary: List global webhooks
description: ''
operationId: enterprise-admin/list-global-webhooks
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#list-global-webhooks
parameters:
- name: accept
description: This API is under preview and subject to change.
in: header
schema:
type: string
default: application/vnd.github.superpro-preview+json
required: true
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/global-hook"
examples:
default:
"$ref": "#/components/examples/global-hook-items"
headers:
Link:
"$ref": "#/components/headers/link"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: global-webhooks
post:
summary: Create a global webhook
description: ''
operationId: enterprise-admin/create-global-webhook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#create-a-global-webhook
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/global-hook"
examples:
default:
"$ref": "#/components/examples/global-hook"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
description: Must be passed as "web".
config:
type: object
description: Key/value pairs to provide settings for this webhook.
properties:
url:
type: string
description: The URL to which the payloads will be delivered.
content_type:
type: string
description: The media type used to serialize the payloads.
Supported values include `json` and `form`. The default is
`form`.
secret:
type: string
description: If provided, the `secret` will be used as the `key`
to generate the HMAC hex digest value in the [`X-Hub-Signature`](https://docs.github.com/enterprise-server@3.3/webhooks/event-payloads/#delivery-headers)
header.
insecure_ssl:
type: string
description: Determines whether the SSL certificate of the host
for `url` will be verified when delivering payloads. Supported
values include `0` (verification is performed) and `1` (verification
is not performed). The default is `0`. **We strongly recommend
not setting this to `1` as you are subject to man-in-the-middle
and other attacks.**
required:
- url
events:
type: array
description: 'The [events](https://docs.github.com/enterprise-server@3.3/webhooks/event-payloads)
that trigger this webhook. A global webhook can be triggered by
`user` and `organization` events. Default: `user` and `organization`.'
items:
type: string
active:
type: boolean
description: Determines if notifications are sent when the webhook
is triggered. Set to `true` to send notifications.
default: true
required:
- name
- config
example:
name: web
events:
- organization
- user
config:
url: https://example.com/webhook
content_type: json
secret: secret
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: global-webhooks
"/admin/hooks/{hook_id}":
get:
summary: Get a global webhook
description: ''
operationId: enterprise-admin/get-global-webhook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-a-global-webhook
parameters:
- "$ref": "#/components/parameters/hook-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/global-hook"
examples:
default:
"$ref": "#/components/examples/global-hook"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: global-webhooks
patch:
summary: Update a global webhook
description: Parameters that are not provided will be overwritten with the default
value or removed if no default exists.
operationId: enterprise-admin/update-global-webhook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-a-global-webhook
parameters:
- "$ref": "#/components/parameters/hook-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/global-hook-2"
examples:
default:
"$ref": "#/components/examples/global-hook-2"
requestBody:
content:
application/json:
schema:
type: object
properties:
config:
type: object
description: Key/value pairs to provide settings for this webhook.
properties:
url:
type: string
description: The URL to which the payloads will be delivered.
content_type:
type: string
description: The media type used to serialize the payloads.
Supported values include `json` and `form`. The default is
`form`.
secret:
type: string
description: If provided, the `secret` will be used as the `key`
to generate the HMAC hex digest value in the [`X-Hub-Signature`](https://docs.github.com/enterprise-server@3.3/webhooks/event-payloads/#delivery-headers)
header.
insecure_ssl:
type: string
description: Determines whether the SSL certificate of the host
for `url` will be verified when delivering payloads. Supported
values include `0` (verification is performed) and `1` (verification
is not performed). The default is `0`. **We strongly recommend
not setting this to `1` as you are subject to man-in-the-middle
and other attacks.**
required:
- url
events:
type: array
description: 'The [events](https://docs.github.com/enterprise-server@3.3/webhooks/event-payloads)
that trigger this webhook. A global webhook can be triggered by
`user` and `organization` events. Default: `user` and `organization`.'
items:
type: string
active:
type: boolean
description: Determines if notifications are sent when the webhook
is triggered. Set to `true` to send notifications.
default: true
example:
events:
- organization
config:
url: https://example.com/webhook
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: global-webhooks
delete:
summary: Delete a global webhook
description: ''
operationId: enterprise-admin/delete-global-webhook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#delete-a-global-webhook
parameters:
- name: accept
description: This API is under preview and subject to change.
in: header
schema:
type: string
default: application/vnd.github.superpro-preview+json
required: true
- "$ref": "#/components/parameters/hook-id"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: global-webhooks
"/admin/hooks/{hook_id}/pings":
post:
summary: Ping a global webhook
description: This will trigger a [ping event](https://docs.github.com/enterprise-server@3.3/webhooks/#ping-event)
to be sent to the webhook.
operationId: enterprise-admin/ping-global-webhook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#ping-a-global-webhook
parameters:
- name: accept
description: This API is under preview and subject to change.
in: header
schema:
type: string
default: application/vnd.github.superpro-preview+json
required: true
- "$ref": "#/components/parameters/hook-id"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: global-webhooks
"/admin/keys":
get:
summary: List public keys
description: ''
operationId: enterprise-admin/list-public-keys
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#list-public-keys
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
- "$ref": "#/components/parameters/direction"
- name: sort
in: query
required: false
schema:
type: string
enum:
- created
- updated
- accessed
default: created
- name: since
description: Only show public keys accessed after the given time.
in: query
required: false
schema:
type: string
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/public-key-full"
examples:
default:
"$ref": "#/components/examples/enterprise-public-key-items"
headers:
Link:
"$ref": "#/components/headers/link"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
"/admin/keys/{key_ids}":
delete:
summary: Delete a public key
description: ''
operationId: enterprise-admin/delete-public-key
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#delete-a-public-key
parameters:
- "$ref": "#/components/parameters/key-ids"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
"/admin/ldap/teams/{team_id}/mapping":
patch:
summary: Update LDAP mapping for a team
description: Updates the [distinguished name](https://www.ldap.com/ldap-dns-and-rdns)
(DN) of the LDAP entry to map to a team. [LDAP synchronization](https://help.github.com/enterprise/admin/guides/user-management/using-ldap/#enabling-ldap-sync)
must be enabled to map LDAP entries to a team. Use the [Create a team](https://docs.github.com/enterprise-server@3.3/rest/reference/teams/#create-a-team)
endpoint to create a team with LDAP mapping.
operationId: enterprise-admin/update-ldap-mapping-for-team
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-ldap-mapping-for-a-team
parameters:
- "$ref": "#/components/parameters/team-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/ldap-mapping-team"
examples:
default:
"$ref": "#/components/examples/ldap-mapping-team"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
ldap_dn:
type: string
description: The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns)
(DN) of the LDAP entry to map to a team.
required:
- ldap_dn
example:
ldap_dn: cn=Enterprise Ops,ou=teams,dc=github,dc=com
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: ldap
"/admin/ldap/teams/{team_id}/sync":
post:
summary: Sync LDAP mapping for a team
description: Note that this API call does not automatically initiate an LDAP
sync. Rather, if a `201` is returned, the sync job is queued successfully,
and is performed when the instance is ready.
operationId: enterprise-admin/sync-ldap-mapping-for-team
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#sync-ldap-mapping-for-a-team
parameters:
- "$ref": "#/components/parameters/team-id"
responses:
'201':
description: Response
content:
application/json:
schema:
type: object
properties:
status:
type: string
example:
status: queued
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: ldap
"/admin/ldap/users/{username}/mapping":
patch:
summary: Update LDAP mapping for a user
description: ''
operationId: enterprise-admin/update-ldap-mapping-for-user
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-ldap-mapping-for-a-user
parameters:
- "$ref": "#/components/parameters/username"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/ldap-mapping-user"
examples:
default:
"$ref": "#/components/examples/ldap-mapping-user"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
ldap_dn:
type: string
description: The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns)
(DN) of the LDAP entry to map to a team.
required:
- ldap_dn
example:
ldap_dn: uid=asdf,ou=users,dc=github,dc=com
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: ldap
"/admin/ldap/users/{username}/sync":
post:
summary: Sync LDAP mapping for a user
description: Note that this API call does not automatically initiate an LDAP
sync. Rather, if a `201` is returned, the sync job is queued successfully,
and is performed when the instance is ready.
operationId: enterprise-admin/sync-ldap-mapping-for-user
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#sync-ldap-mapping-for-a-user
parameters:
- "$ref": "#/components/parameters/username"
responses:
'201':
description: Response
content:
application/json:
schema:
type: object
properties:
status:
type: string
example:
status: queued
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: ldap
"/admin/organizations":
post:
summary: Create an organization
description: ''
operationId: enterprise-admin/create-org
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#create-an-organization
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/organization-simple"
examples:
default:
"$ref": "#/components/examples/organization-simple"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
login:
type: string
description: The organization's username.
admin:
type: string
description: The login of the user who will manage this organization.
profile_name:
type: string
description: The organization's display name.
required:
- login
- admin
example:
login: github
profile_name: GitHub, Inc.
admin: monalisaoctocat
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: orgs
"/admin/organizations/{org}":
patch:
summary: Update an organization name
description: ''
operationId: enterprise-admin/update-org-name
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-an-organization-name
parameters:
- "$ref": "#/components/parameters/org"
responses:
'202':
description: Response
content:
application/json:
schema:
type: object
properties:
message:
type: string
url:
type: string
example:
message: Job queued to rename organization. It may take a few minutes
to complete.
url: https://<hostname>/api/v3/organizations/1
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
login:
type: string
description: The organization's new name.
required:
- login
example:
login: the-new-octocats
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: orgs
"/admin/pre-receive-environments":
get:
summary: List pre-receive environments
description: ''
operationId: enterprise-admin/list-pre-receive-environments
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#list-pre-receive-environments
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
- "$ref": "#/components/parameters/direction"
- name: sort
in: query
required: false
schema:
type: string
enum:
- created
- updated
- name
default: created
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/pre-receive-environment"
examples:
default:
"$ref": "#/components/examples/pre-receive-environment-items"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-environments
post:
summary: Create a pre-receive environment
description: ''
operationId: enterprise-admin/create-pre-receive-environment
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#create-a-pre-receive-environment
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-environment"
examples:
default:
"$ref": "#/components/examples/pre-receive-environment"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
description: The new pre-receive environment's name.
image_url:
type: string
description: URL from which to download a tarball of this environment.
required:
- name
- image_url
example:
name: DevTools Hook Env
image_url: https://my_file_server/path/to/devtools_env.tar.gz
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-environments
"/admin/pre-receive-environments/{pre_receive_environment_id}":
get:
summary: Get a pre-receive environment
description: ''
operationId: enterprise-admin/get-pre-receive-environment
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-a-pre-receive-environment
parameters:
- "$ref": "#/components/parameters/pre-receive-environment-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-environment"
examples:
default:
"$ref": "#/components/examples/pre-receive-environment"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-environments
patch:
summary: Update a pre-receive environment
description: You cannot modify the default environment. If you attempt to modify
the default environment, you will receive a `422 Unprocessable Entity` response.
operationId: enterprise-admin/update-pre-receive-environment
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-a-pre-receive-environment
parameters:
- "$ref": "#/components/parameters/pre-receive-environment-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-environment"
examples:
default-response:
"$ref": "#/components/examples/pre-receive-environment-default-response"
'422':
description: Client Errors
content:
application/json:
schema:
type: object
properties:
message:
type: string
errors:
type: array
items:
type: object
properties:
resource:
type: string
code:
type: string
message:
type: string
examples:
client-errors:
value:
message: Validation Failed
errors:
- resource: PreReceiveEnvironment
code: custom
message: Cannot modify or delete the default environment
requestBody:
content:
application/json:
schema:
type: object
properties:
name:
type: string
description: This pre-receive environment's new name.
image_url:
type: string
description: URL from which to download a tarball of this environment.
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-environments
delete:
summary: Delete a pre-receive environment
description: |-
If you attempt to delete an environment that cannot be deleted, you will receive a `422 Unprocessable Entity` response.
The possible error messages are:
* _Cannot modify or delete the default environment_
* _Cannot delete environment that has hooks_
* _Cannot delete environment when download is in progress_
operationId: enterprise-admin/delete-pre-receive-environment
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#delete-a-pre-receive-environment
parameters:
- "$ref": "#/components/parameters/pre-receive-environment-id"
responses:
'204':
description: Response
'422':
description: Client Errors
content:
application/json:
schema:
type: object
properties:
message:
type: string
errors:
type: array
items:
type: object
properties:
resource:
type: string
code:
type: string
message:
type: string
examples:
client-errors:
value:
message: Validation Failed
errors:
- resource: PreReceiveEnvironment
code: custom
message: Cannot modify or delete the default environment
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-environments
"/admin/pre-receive-environments/{pre_receive_environment_id}/downloads":
post:
summary: Start a pre-receive environment download
description: |-
Triggers a new download of the environment tarball from the environment's `image_url`. When the download is finished, the newly downloaded tarball will overwrite the existing environment.
If a download cannot be triggered, you will receive a `422 Unprocessable Entity` response.
The possible error messages are:
* _Cannot modify or delete the default environment_
* _Can not start a new download when a download is in progress_
operationId: enterprise-admin/start-pre-receive-environment-download
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#start-a-pre-receive-environment-download
parameters:
- "$ref": "#/components/parameters/pre-receive-environment-id"
responses:
'202':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-environment-download-status"
examples:
default-response:
"$ref": "#/components/examples/pre-receive-environment-download-status-default-response"
'422':
description: Client Errors
content:
application/json:
schema:
type: object
properties:
message:
type: string
errors:
type: array
items:
type: object
properties:
resource:
type: string
code:
type: string
message:
type: string
examples:
client-errors:
value:
message: Validation Failed
errors:
- resource: PreReceiveEnvironment
code: custom
message: Can not start a new download when a download is in
progress
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-environments
"/admin/pre-receive-environments/{pre_receive_environment_id}/downloads/latest":
get:
summary: Get the download status for a pre-receive environment
description: In addition to seeing the download status at the "[Get a pre-receive
environment](#get-a-pre-receive-environment)" endpoint, there is also this
separate endpoint for just the download status.
operationId: enterprise-admin/get-download-status-for-pre-receive-environment
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-the-download-status-for-a-pre-receive-environment
parameters:
- "$ref": "#/components/parameters/pre-receive-environment-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-environment-download-status"
examples:
default:
"$ref": "#/components/examples/pre-receive-environment-download-status"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-environments
"/admin/pre-receive-hooks":
get:
summary: List pre-receive hooks
description: ''
operationId: enterprise-admin/list-pre-receive-hooks
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#list-pre-receive-hooks
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
- "$ref": "#/components/parameters/direction"
- name: sort
description: One of `created` (when the repository was starred) or `updated`
(when it was last pushed to) or `name`.
in: query
required: false
schema:
type: string
enum:
- created
- updated
- name
default: created
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/pre-receive-hook"
examples:
default:
"$ref": "#/components/examples/pre-receive-hook-items"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-hooks
post:
summary: Create a pre-receive hook
description: ''
operationId: enterprise-admin/create-pre-receive-hook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#create-a-pre-receive-hook
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-hook"
examples:
default:
"$ref": "#/components/examples/pre-receive-hook"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
description: The name of the hook.
script:
type: string
description: The script that the hook runs.
script_repository:
type: object
description: The GitHub repository where the script is kept.
properties: {}
additionalProperties: true
environment:
type: object
description: The pre-receive environment where the script is executed.
properties: {}
additionalProperties: true
enforcement:
type: string
description: 'The state of enforcement for this hook. default: `disabled`'
allow_downstream_configuration:
type: boolean
description: 'Whether enforcement can be overridden at the org or
repo level. default: `false`'
required:
- name
- script
- script_repository
- environment
example:
name: Check Commits
script: scripts/commit_check.sh
enforcement: disabled
allow_downstream_configuration: false
script_repository:
full_name: DevIT/hooks
environment:
id: 2
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-hooks
"/admin/pre-receive-hooks/{pre_receive_hook_id}":
get:
summary: Get a pre-receive hook
description: ''
operationId: enterprise-admin/get-pre-receive-hook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-a-pre-receive-hook
parameters:
- "$ref": "#/components/parameters/pre-receive-hook-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-hook"
examples:
default:
"$ref": "#/components/examples/pre-receive-hook"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-hooks
patch:
summary: Update a pre-receive hook
description: ''
operationId: enterprise-admin/update-pre-receive-hook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-a-pre-receive-hook
parameters:
- "$ref": "#/components/parameters/pre-receive-hook-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/pre-receive-hook"
examples:
default:
"$ref": "#/components/examples/pre-receive-hook-2"
requestBody:
content:
application/json:
schema:
type: object
properties:
name:
type: string
description: The name of the hook.
script:
type: string
description: The script that the hook runs.
script_repository:
type: object
description: The GitHub repository where the script is kept.
properties: {}
additionalProperties: true
environment:
type: object
description: The pre-receive environment where the script is executed.
properties: {}
additionalProperties: true
enforcement:
type: string
description: The state of enforcement for this hook.
allow_downstream_configuration:
type: boolean
description: Whether enforcement can be overridden at the org or
repo level.
example:
name: Check Commits
environment:
id: 1
allow_downstream_configuration: true
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-hooks
delete:
summary: Delete a pre-receive hook
description: ''
operationId: enterprise-admin/delete-pre-receive-hook
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#delete-a-pre-receive-hook
parameters:
- "$ref": "#/components/parameters/pre-receive-hook-id"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: pre-receive-hooks
"/admin/tokens":
get:
summary: List personal access tokens
description: Lists personal access tokens for all users, including admin users.
operationId: enterprise-admin/list-personal-access-tokens
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#list-personal-access-tokens
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-items"
headers:
Link:
"$ref": "#/components/headers/link"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
"/admin/tokens/{token_id}":
delete:
summary: Delete a personal access token
description: Deletes a personal access token. Returns a `403 - Forbidden` status
when a personal access token is in use. For example, if you access this endpoint
with the same personal access token that you are trying to delete, you will
receive this error.
operationId: enterprise-admin/delete-personal-access-token
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#delete-a-personal-access-token
parameters:
- "$ref": "#/components/parameters/token-id"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
"/admin/users":
post:
summary: Create a user
description: |-
If an external authentication mechanism is used, the login name should match the login name in the external system. If you are using LDAP authentication, you should also [update the LDAP mapping](https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-ldap-mapping-for-a-user) for the user.
The login name will be normalized to only contain alphanumeric characters or single hyphens. For example, if you send `"octo_cat"` as the login, a user named `"octo-cat"` will be created.
If the login name or email address is already associated with an account, the server will return a `422` response.
operationId: enterprise-admin/create-user
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#create-a-user
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/simple-user"
examples:
default:
"$ref": "#/components/examples/simple-user"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
login:
type: string
description: The user's username.
email:
type: string
description: "**Required for built-in authentication.** The user's
email address. This parameter can be omitted when using CAS, LDAP,
or SAML. For details on built-in and centrally-managed authentication,
see the the [GitHub authentication guide](https://help.github.com/enterprise/2.18/admin/guides/user-management/authenticating-users-for-your-github-enterprise-server-instance/)."
required:
- login
example:
login: monalisa
email: octocat@github.com
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
"/admin/users/{username}":
patch:
summary: Update the username for a user
description: ''
operationId: enterprise-admin/update-username-for-user
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#update-the-username-for-a-user
parameters:
- "$ref": "#/components/parameters/username"
responses:
'202':
description: Response
content:
application/json:
schema:
type: object
properties:
message:
type: string
url:
type: string
example:
message: Job queued to rename user. It may take a few minutes to complete.
url: https://api.github.com/user/1
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
login:
type: string
description: The user's new username.
required:
- login
example:
login: thenewmonalisa
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
delete:
summary: Delete a user
description: |-
Deleting a user will delete all their repositories, gists, applications, and personal settings. [Suspending a user](https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#suspend-a-user) is often a better option.
You can delete any user account except your own.
operationId: enterprise-admin/delete-user
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#delete-a-user
parameters:
- "$ref": "#/components/parameters/username"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
"/admin/users/{username}/authorizations":
post:
summary: Create an impersonation OAuth token
description: ''
operationId: enterprise-admin/create-impersonation-o-auth-token
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#create-an-impersonation-oauth-token
parameters:
- "$ref": "#/components/parameters/username"
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
scopes:
type: array
description: A list of [scopes](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).
items:
type: string
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
delete:
summary: Delete an impersonation OAuth token
description: ''
operationId: enterprise-admin/delete-impersonation-o-auth-token
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#delete-an-impersonation-oauth-token
parameters:
- "$ref": "#/components/parameters/username"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: users
"/app":
get:
summary: Get the authenticated app
description: |-
Returns the GitHub App associated with the authentication credentials used. To see how many app installations are associated with this GitHub App, see the `installations_count` in the response. For more details about your app's installations, see the "[List installations for the authenticated app](https://docs.github.com/enterprise-server@3.3/rest/reference/apps#list-installations-for-the-authenticated-app)" endpoint.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/get-authenticated
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#get-the-authenticated-app
parameters: []
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/integration"
examples:
default:
"$ref": "#/components/examples/integration"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: apps
subcategory:
"/app-manifests/{code}/conversions":
post:
summary: Create a GitHub App from a manifest
description: Use this endpoint to complete the handshake necessary when implementing
the [GitHub App Manifest flow](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/creating-github-apps-from-a-manifest/).
When you create a GitHub App with the manifest flow, you receive a temporary
`code` used to retrieve the GitHub App's `id`, `pem` (private key), and `webhook_secret`.
tags:
- apps
operationId: apps/create-from-manifest
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#create-a-github-app-from-a-manifest
parameters:
- name: code
in: path
required: true
schema:
type: string
requestBody:
required: false
content:
application/json:
schema:
type: object
additionalProperties: false
responses:
'201':
description: Response
content:
application/json:
schema:
allOf:
- "$ref": "#/components/schemas/integration"
- type: object
properties:
client_id:
type: string
client_secret:
type: string
webhook_secret:
type: string
nullable: true
pem:
type: string
required:
- client_id
- client_secret
- webhook_secret
- pem
additionalProperties: true
examples:
default:
"$ref": "#/components/examples/integration-from-manifest"
'404':
"$ref": "#/components/responses/not_found"
'422':
"$ref": "#/components/responses/validation_failed_simple"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory:
"/app/hook/config":
get:
summary: Get a webhook configuration for an app
description: |-
Returns the webhook configuration for a GitHub App. For more information about configuring a webhook for your app, see "[Creating a GitHub App](/developers/apps/creating-a-github-app)."
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/get-webhook-config-for-app
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#get-a-webhook-configuration-for-an-app
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/webhook-config"
examples:
default:
"$ref": "#/components/examples/webhook-config"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: webhooks
patch:
summary: Update a webhook configuration for an app
description: |-
Updates the webhook configuration for a GitHub App. For more information about configuring a webhook for your app, see "[Creating a GitHub App](/developers/apps/creating-a-github-app)."
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/update-webhook-config-for-app
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#update-a-webhook-configuration-for-an-app
requestBody:
required: false
content:
application/json:
schema:
type: object
properties:
url:
"$ref": "#/components/schemas/webhook-config-url"
content_type:
"$ref": "#/components/schemas/webhook-config-content-type"
secret:
"$ref": "#/components/schemas/webhook-config-secret"
insecure_ssl:
"$ref": "#/components/schemas/webhook-config-insecure-ssl"
example:
content_type: json
insecure_ssl: '0'
secret: "********"
url: https://example.com/webhook
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/webhook-config"
examples:
default:
"$ref": "#/components/examples/webhook-config"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: webhooks
"/app/hook/deliveries":
get:
summary: List deliveries for an app webhook
description: |-
Returns a list of webhook deliveries for the webhook configured for a GitHub App.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/list-webhook-deliveries
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#list-deliveries-for-an-app-webhook
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/cursor"
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/hook-delivery-item"
examples:
default:
"$ref": "#/components/examples/hook-delivery-items"
'400':
"$ref": "#/components/responses/bad_request"
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: webhooks
"/app/hook/deliveries/{delivery_id}":
get:
summary: Get a delivery for an app webhook
description: |-
Returns a delivery for the webhook configured for a GitHub App.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/get-webhook-delivery
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#get-a-delivery-for-an-app-webhook
parameters:
- "$ref": "#/components/parameters/delivery-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/hook-delivery"
examples:
default:
"$ref": "#/components/examples/hook-delivery"
'400':
"$ref": "#/components/responses/bad_request"
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: webhooks
"/app/hook/deliveries/{delivery_id}/attempts":
post:
summary: Redeliver a delivery for an app webhook
description: |-
Redeliver a delivery for the webhook configured for a GitHub App.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/redeliver-webhook-delivery
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#redeliver-a-delivery-for-an-app-webhook
parameters:
- "$ref": "#/components/parameters/delivery-id"
responses:
'202':
"$ref": "#/components/responses/accepted"
'400':
"$ref": "#/components/responses/bad_request"
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: webhooks
"/app/installations":
get:
summary: List installations for the authenticated app
description: |-
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
The permissions the installation has are included under the `permissions` key.
tags:
- apps
operationId: apps/list-installations
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#list-installations-for-the-authenticated-app
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
- "$ref": "#/components/parameters/since"
- name: outdated
in: query
required: false
schema:
type: string
responses:
'200':
description: The permissions the installation has are included under the
`permissions` key.
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/installation"
examples:
default:
"$ref": "#/components/examples/base-installation-items"
headers:
Link:
"$ref": "#/components/headers/link"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: apps
subcategory:
"/app/installations/{installation_id}":
get:
summary: Get an installation for the authenticated app
description: |-
Enables an authenticated GitHub App to find an installation's information using the installation id. The installation's account type (`target_type`) will be either an organization or a user account, depending which account the repository belongs to.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/get-installation
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#get-an-installation-for-the-authenticated-app
parameters:
- "$ref": "#/components/parameters/installation-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/installation"
examples:
default:
"$ref": "#/components/examples/base-installation"
'404':
"$ref": "#/components/responses/not_found"
'415':
"$ref": "#/components/responses/preview_header_missing"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: apps
subcategory:
delete:
summary: Delete an installation for the authenticated app
description: |-
Uninstalls a GitHub App on a user, organization, or business account. If you prefer to temporarily suspend an app's access to your account's resources, then we recommend the "[Suspend an app installation](https://docs.github.com/enterprise-server@3.3/rest/reference/apps/#suspend-an-app-installation)" endpoint.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/delete-installation
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#delete-an-installation-for-the-authenticated-app
parameters:
- "$ref": "#/components/parameters/installation-id"
responses:
'204':
description: Response
'404':
"$ref": "#/components/responses/not_found"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory:
"/app/installations/{installation_id}/access_tokens":
post:
summary: Create an installation access token for an app
description: |-
Creates an installation access token that enables a GitHub App to make authenticated API requests for the app's installation on an organization or individual account. Installation tokens expire one hour from the time you create them. Using an expired token produces a status code of `401 - Unauthorized`, and requires creating a new installation token. By default the installation token has access to all repositories that the installation can access. To restrict the access to specific repositories, you can provide the `repository_ids` when creating the token. When you omit `repository_ids`, the response does not contain the `repositories` key.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/create-installation-access-token
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps/#create-an-installation-access-token-for-an-app
parameters:
- "$ref": "#/components/parameters/installation-id"
requestBody:
required: false
content:
application/json:
schema:
type: object
properties:
repositories:
description: List of repository names that the token should have
access to
type: array
items:
type: string
example: rails
repository_ids:
description: List of repository IDs that the token should have access
to
example:
- 1
type: array
items:
type: integer
permissions:
"$ref": "#/components/schemas/app-permissions"
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/installation-token"
examples:
default:
"$ref": "#/components/examples/installation-token"
'403':
"$ref": "#/components/responses/forbidden"
'415':
"$ref": "#/components/responses/preview_header_missing"
'401':
"$ref": "#/components/responses/requires_authentication"
'404':
"$ref": "#/components/responses/not_found"
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: apps
subcategory:
"/app/installations/{installation_id}/suspended":
put:
summary: Suspend an app installation
description: |-
Suspends a GitHub App on a user, organization, or business account, which blocks the app from accessing the account's resources. When a GitHub App is suspended, the app's access to the GitHub Enterprise Server API or webhook events is blocked for that account.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/suspend-installation
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#suspend-an-app-installation
parameters:
- "$ref": "#/components/parameters/installation-id"
responses:
'204':
description: Response
'404':
"$ref": "#/components/responses/not_found"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory:
delete:
summary: Unsuspend an app installation
description: |-
Removes a GitHub App installation suspension.
You must use a [JWT](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.
tags:
- apps
operationId: apps/unsuspend-installation
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#unsuspend-an-app-installation
parameters:
- "$ref": "#/components/parameters/installation-id"
responses:
'204':
description: Response
'404':
"$ref": "#/components/responses/not_found"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory:
"/applications/grants":
get:
summary: List your grants
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).
You can use this API to list the set of OAuth applications that have been granted access to your account. Unlike the [list your authorizations](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#list-your-authorizations) API, this API does not manage individual tokens. This API will return one entry for each OAuth application that has been granted access to your account, regardless of the number of tokens an application has generated for your user. The list of OAuth applications returned matches what is shown on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized). The `scopes` returned are the union of scopes authorized for the application. For example, if an application has one token with `repo` scope and another token with `user` scope, the grant will return `["repo", "user"]`.
tags:
- oauth-authorizations
operationId: oauth-authorizations/list-grants
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#list-your-grants
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
- name: client_id
in: query
required: false
description: The client ID of your GitHub app.
schema:
type: string
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/application-grant"
examples:
default:
"$ref": "#/components/examples/application-grant-items"
headers:
Link:
"$ref": "#/components/headers/link"
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
'404':
"$ref": "#/components/responses/not_found"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
"/applications/grants/{grant_id}":
get:
summary: Get a single grant
description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue
the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations),
which is used by integrations to create personal access tokens and OAuth tokens,
and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow).
The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations)
will be removed on November, 13, 2020. For more information, including scheduled
brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)."
tags:
- oauth-authorizations
operationId: oauth-authorizations/get-grant
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#get-a-single-grant
parameters:
- "$ref": "#/components/parameters/grant-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/application-grant"
examples:
default:
"$ref": "#/components/examples/application-grant"
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
delete:
summary: Delete a grant
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations/) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).
Deleting an OAuth application's grant will also delete all OAuth tokens associated with the application for your user. Once deleted, the application has no access to your account and is no longer listed on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized).
tags:
- oauth-authorizations
operationId: oauth-authorizations/delete-grant
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#delete-a-grant
parameters:
- "$ref": "#/components/parameters/grant-id"
responses:
'204':
description: Response
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
"/applications/{client_id}/grant":
delete:
summary: Delete an app authorization
description: |-
OAuth application owners can revoke a grant for their OAuth application and a specific user. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. You must also provide a valid OAuth `access_token` as an input parameter and the grant for the token's owner will be deleted.
Deleting an OAuth application's grant will also delete all OAuth tokens associated with the application for the user. Once deleted, the application will have no access to the user's account and will no longer be listed on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized).
operationId: apps/delete-authorization
tags:
- apps
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#delete-an-app-authorization
parameters:
- "$ref": "#/components/parameters/client-id"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
access_token:
type: string
description: The OAuth access token used to authenticate to the
GitHub API.
required:
- access_token
example:
access_token: e72e16c7e42f292c6912e7710c838347ae178b4a
responses:
'204':
description: Response
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: oauth-applications
"/applications/{client_id}/grants/{access_token}":
delete:
summary: Revoke a grant for an application
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).
OAuth application owners can revoke a grant for their OAuth application and a specific user. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. You must also provide a valid token as `:access_token` and the grant for the token's owner will be deleted.
Deleting an OAuth application's grant will also delete all OAuth tokens associated with the application for the user. Once deleted, the application will have no access to the user's account and will no longer be listed on [the Applications settings page under "Authorized OAuth Apps" on GitHub Enterprise Server](https://github.com/settings/applications#authorized).
tags:
- apps
operationId: apps/revoke-grant-for-application
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#revoke-a-grant-for-an-application
parameters:
- "$ref": "#/components/parameters/client-id"
- "$ref": "#/components/parameters/access-token"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2021-05-05'
deprecationDate: '2020-02-14'
category: apps
subcategory: oauth-applications
deprecated: true
"/applications/{client_id}/token":
post:
summary: Check a token
description: OAuth applications can use a special API method for checking OAuth
token validity without exceeding the normal rate limits for failed login attempts.
Authentication works differently with this particular endpoint. You must use
[Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication)
to use this endpoint, where the username is the OAuth application `client_id`
and the password is its `client_secret`. Invalid tokens will return `404 NOT
FOUND`.
tags:
- apps
operationId: apps/check-token
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#check-a-token
parameters:
- "$ref": "#/components/parameters/client-id"
requestBody:
required: true
content:
application/json:
schema:
properties:
access_token:
description: The access_token of the OAuth application.
type: string
required:
- access_token
type: object
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-with-user"
'422':
"$ref": "#/components/responses/validation_failed"
'404':
"$ref": "#/components/responses/not_found"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: oauth-applications
patch:
summary: Reset a token
description: OAuth applications can use this API method to reset a valid OAuth
token without end-user involvement. Applications must save the "token" property
in the response because changes take effect immediately. You must use [Basic
Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication)
when accessing this endpoint, using the OAuth application's `client_id` and
`client_secret` as the username and password. Invalid tokens will return `404
NOT FOUND`.
tags:
- apps
operationId: apps/reset-token
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#reset-a-token
parameters:
- "$ref": "#/components/parameters/client-id"
requestBody:
required: true
content:
application/json:
schema:
properties:
access_token:
description: The access_token of the OAuth application.
type: string
required:
- access_token
type: object
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-with-user"
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: oauth-applications
delete:
summary: Delete an app token
description: OAuth application owners can revoke a single token for an OAuth
application. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication)
when accessing this endpoint, using the OAuth application's `client_id` and
`client_secret` as the username and password.
tags:
- apps
operationId: apps/delete-token
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#delete-an-app-token
parameters:
- "$ref": "#/components/parameters/client-id"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
access_token:
type: string
description: The OAuth access token used to authenticate to the
GitHub API.
required:
- access_token
example:
access_token: e72e16c7e42f292c6912e7710c838347ae178b4a
responses:
'204':
description: Response
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: oauth-applications
"/applications/{client_id}/token/scoped":
post:
summary: Create a scoped access token
description: Use a non-scoped user-to-server OAuth access token to create a
repository scoped and/or permission scoped user-to-server OAuth access token.
You can specify which repositories the token can access and which permissions
are granted to the token. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication)
when accessing this endpoint, using the OAuth application's `client_id` and
`client_secret` as the username and password. Invalid tokens will return `404
NOT FOUND`.
tags:
- apps
operationId: apps/scope-token
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#create-a-scoped-access-token
parameters:
- "$ref": "#/components/parameters/client-id"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
access_token:
type: string
description: The OAuth access token used to authenticate to the
GitHub API.
example: e72e16c7e42f292c6912e7710c838347ae178b4a
target:
description: The name of the user or organization to scope the user-to-server
access token to. **Required** unless `target_id` is specified.
type: string
example: octocat
target_id:
description: The ID of the user or organization to scope the user-to-server
access token to. **Required** unless `target` is specified.
example: 1
type: integer
repositories:
description: The list of repository names to scope the user-to-server
access token to. `repositories` may not be specified if `repository_ids`
is specified.
type: array
items:
type: string
example: rails
repository_ids:
description: The list of repository IDs to scope the user-to-server
access token to. `repository_ids` may not be specified if `repositories`
is specified.
example:
- 1
type: array
items:
type: integer
permissions:
"$ref": "#/components/schemas/app-permissions"
required:
- access_token
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/scope-token"
'401':
"$ref": "#/components/responses/requires_authentication"
'403':
"$ref": "#/components/responses/forbidden"
'404':
"$ref": "#/components/responses/not_found"
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: apps
subcategory: oauth-applications
"/applications/{client_id}/tokens/{access_token}":
get:
summary: Check an authorization
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).
OAuth applications can use a special API method for checking OAuth token validity without exceeding the normal rate limits for failed login attempts. Authentication works differently with this particular endpoint. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`.
tags:
- apps
operationId: apps/check-authorization
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#check-an-authorization
parameters:
- "$ref": "#/components/parameters/client-id"
- "$ref": "#/components/parameters/access-token"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/nullable-authorization"
examples:
default:
"$ref": "#/components/examples/authorization-with-user"
'404':
"$ref": "#/components/responses/not_found"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2021-05-05'
deprecationDate: '2020-02-14'
category: apps
subcategory: oauth-applications
deprecated: true
post:
summary: Reset an authorization
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).
OAuth applications can use this API method to reset a valid OAuth token without end-user involvement. Applications must save the "token" property in the response because changes take effect immediately. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`.
tags:
- apps
operationId: apps/reset-authorization
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#reset-an-authorization
parameters:
- "$ref": "#/components/parameters/client-id"
- "$ref": "#/components/parameters/access-token"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-with-user"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2021-05-05'
deprecationDate: '2020-02-14'
category: apps
subcategory: oauth-applications
deprecated: true
delete:
summary: Revoke an authorization for an application
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).
OAuth application owners can revoke a single token for an OAuth application. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password.
tags:
- apps
operationId: apps/revoke-authorization-for-application
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#revoke-an-authorization-for-an-application
parameters:
- "$ref": "#/components/parameters/client-id"
- "$ref": "#/components/parameters/access-token"
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2021-05-05'
deprecationDate: '2020-02-14'
category: apps
subcategory: oauth-applications
deprecated: true
"/apps/{app_slug}":
get:
summary: Get an app
description: |-
**Note**: The `:app_slug` is just the URL-friendly name of your GitHub App. You can find this on the settings page for your GitHub App (e.g., `https://github.com/settings/apps/:app_slug`).
If the GitHub App you specify is public, you can access this endpoint without authenticating. If the GitHub App you specify is private, you must authenticate with a [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) or an [installation access token](https://docs.github.com/enterprise-server@3.3/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint.
tags:
- apps
operationId: apps/get-by-slug
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/apps/#get-an-app
parameters:
- "$ref": "#/components/parameters/app-slug"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/integration"
examples:
default:
"$ref": "#/components/examples/integration"
'403':
"$ref": "#/components/responses/forbidden"
'404':
"$ref": "#/components/responses/not_found"
'415':
"$ref": "#/components/responses/preview_header_missing"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: apps
subcategory:
"/authorizations":
get:
summary: List your authorizations
description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue
the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations),
which is used by integrations to create personal access tokens and OAuth tokens,
and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow).
The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations)
will be removed on November, 13, 2020. For more information, including scheduled
brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)."
tags:
- oauth-authorizations
operationId: oauth-authorizations/list-authorizations
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#list-your-authorizations
parameters:
- "$ref": "#/components/parameters/per-page"
- "$ref": "#/components/parameters/page"
- name: client_id
in: query
required: false
description: The client ID of your GitHub app.
schema:
type: string
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-items"
headers:
Link:
"$ref": "#/components/headers/link"
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
'404':
"$ref": "#/components/responses/not_found"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
post:
summary: Create a new authorization
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).
**Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api).
Creates OAuth tokens using [Basic Authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#basic-authentication). If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#working-with-two-factor-authentication)."
To create tokens for a particular OAuth application using this endpoint, you must authenticate as the user you want to create an authorization for and provide the app's client ID and secret, found on your OAuth application's settings page. If your OAuth application intends to create multiple tokens for one user, use `fingerprint` to differentiate between them.
You can also create tokens on GitHub Enterprise Server from the [personal access tokens settings](https://github.com/settings/tokens) page. Read more about these tokens in [the GitHub Help documentation](https://help.github.com/articles/creating-an-access-token-for-command-line-use).
Organizations that enforce SAML SSO require personal access tokens to be allowed. Read more about allowing tokens in [the GitHub Help documentation](https://help.github.com/articles/about-identity-and-access-management-with-saml-single-sign-on).
tags:
- oauth-authorizations
operationId: oauth-authorizations/create-authorization
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#create-a-new-authorization
parameters: []
requestBody:
required: false
content:
application/json:
schema:
type: object
properties:
scopes:
description: A list of scopes that this authorization is in.
type: array
items:
type: string
example:
- public_repo
- user
nullable: true
note:
description: A note to remind you what the OAuth token is for.
type: string
example: Update all gems
note_url:
description: A URL to remind you what app the OAuth token is for.
type: string
client_id:
description: The OAuth app client key for which to create the token.
maxLength: 20
type: string
client_secret:
description: The OAuth app client secret for which to create the
token.
maxLength: 40
type: string
fingerprint:
description: A unique string to distinguish an authorization from
others created for the same client ID and user.
type: string
responses:
'201':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization"
headers:
Location:
example: https://api.github.com/authorizations/1
schema:
type: string
'422':
"$ref": "#/components/responses/validation_failed"
'410':
"$ref": "#/components/responses/gone"
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
"/authorizations/clients/{client_id}":
put:
summary: Get-or-create an authorization for a specific app
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).
**Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api).
Creates a new authorization for the specified OAuth application, only if an authorization for that application doesn't already exist for the user. The URL includes the 20 character client ID for the OAuth app that is requesting the token. It returns the user's existing authorization for the application if one is present. Otherwise, it creates and returns a new one.
If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#working-with-two-factor-authentication)."
**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).
tags:
- oauth-authorizations
operationId: oauth-authorizations/get-or-create-authorization-for-app
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#get-or-create-an-authorization-for-a-specific-app
parameters:
- "$ref": "#/components/parameters/client-id"
requestBody:
required: true
content:
application/json:
schema:
properties:
client_secret:
description: The OAuth app client secret for which to create the
token.
maxLength: 40
type: string
scopes:
description: A list of scopes that this authorization is in.
type: array
items:
type: string
example:
- public_repo
- user
nullable: true
note:
description: A note to remind you what the OAuth token is for.
type: string
example: Update all gems
note_url:
description: A URL to remind you what app the OAuth token is for.
type: string
fingerprint:
description: A unique string to distinguish an authorization from
others created for the same client ID and user.
type: string
required:
- client_secret
type: object
responses:
'200':
description: if returning an existing token
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
response-if-returning-an-existing-token:
"$ref": "#/components/examples/authorization-response-if-returning-an-existing-token-2"
headers:
Location:
example: https://api.github.com/authorizations/1
schema:
type: string
'201':
description: "**Deprecation Notice:** GitHub will discontinue the [OAuth
Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations),
which is used by integrations to create personal access tokens and OAuth
tokens, and you must now create these tokens using our [web application
flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow).
The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations)
will be removed on November, 13, 2020. For more information, including
scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)."
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization"
headers:
Location:
example: https://api.github.com/authorizations/1
schema:
type: string
'422':
"$ref": "#/components/responses/validation_failed"
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
"/authorizations/clients/{client_id}/{fingerprint}":
put:
summary: Get-or-create an authorization for a specific app and fingerprint
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).
**Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api).
This method will create a new authorization for the specified OAuth application, only if an authorization for that application and fingerprint do not already exist for the user. The URL includes the 20 character client ID for the OAuth app that is requesting the token. `fingerprint` is a unique string to distinguish an authorization from others created for the same client ID and user. It returns the user's existing authorization for the application if one is present. Otherwise, it creates and returns a new one.
If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#working-with-two-factor-authentication)."
tags:
- oauth-authorizations
operationId: oauth-authorizations/get-or-create-authorization-for-app-and-fingerprint
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#get-or-create-an-authorization-for-a-specific-app-and-fingerprint
parameters:
- "$ref": "#/components/parameters/client-id"
- name: fingerprint
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
application/json:
schema:
properties:
client_secret:
description: The OAuth app client secret for which to create the
token.
maxLength: 40
type: string
scopes:
description: A list of scopes that this authorization is in.
type: array
items:
type: string
example:
- public_repo
- user
nullable: true
note:
description: A note to remind you what the OAuth token is for.
type: string
example: Update all gems
note_url:
description: A URL to remind you what app the OAuth token is for.
type: string
required:
- client_secret
type: object
responses:
'200':
description: if returning an existing token
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
response-if-returning-an-existing-token:
"$ref": "#/components/examples/authorization-response-if-returning-an-existing-token"
headers:
Location:
example: https://api.github.com/authorizations/1
schema:
type: string
'201':
description: Response if returning a new token
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-3"
headers:
Location:
example: https://api.github.com/authorizations/1
schema:
type: string
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
"/authorizations/{authorization_id}":
get:
summary: Get a single authorization
description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue
the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations),
which is used by integrations to create personal access tokens and OAuth tokens,
and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow).
The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations)
will be removed on November, 13, 2020. For more information, including scheduled
brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)."
tags:
- oauth-authorizations
operationId: oauth-authorizations/get-authorization
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#get-a-single-authorization
parameters:
- "$ref": "#/components/parameters/authorization-id"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-2"
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
patch:
summary: Update an existing authorization
description: |-
**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).
If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.3/rest/overview/other-authentication-methods#working-with-two-factor-authentication)."
You can only send one of these scope keys at a time.
tags:
- oauth-authorizations
operationId: oauth-authorizations/update-authorization
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#update-an-existing-authorization
parameters:
- "$ref": "#/components/parameters/authorization-id"
requestBody:
required: false
content:
application/json:
schema:
type: object
properties:
scopes:
description: A list of scopes that this authorization is in.
type: array
items:
type: string
example:
- public_repo
- user
nullable: true
add_scopes:
description: A list of scopes to add to this authorization.
type: array
items:
type: string
remove_scopes:
description: A list of scopes to remove from this authorization.
type: array
items:
type: string
note:
description: A note to remind you what the OAuth token is for.
type: string
example: Update all gems
note_url:
description: A URL to remind you what app the OAuth token is for.
type: string
fingerprint:
description: A unique string to distinguish an authorization from
others created for the same client ID and user.
type: string
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/authorization"
examples:
default:
"$ref": "#/components/examples/authorization-2"
'422':
"$ref": "#/components/responses/validation_failed"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
delete:
summary: Delete an authorization
description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue
the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations),
which is used by integrations to create personal access tokens and OAuth tokens,
and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.3/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow).
The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations)
will be removed on November, 13, 2020. For more information, including scheduled
brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)."
tags:
- oauth-authorizations
operationId: oauth-authorizations/delete-authorization
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/oauth-authorizations#delete-an-authorization
parameters:
- "$ref": "#/components/parameters/authorization-id"
responses:
'204':
description: Response
'304':
"$ref": "#/components/responses/not_modified"
'403':
"$ref": "#/components/responses/forbidden"
'401':
"$ref": "#/components/responses/requires_authentication"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
removalDate: '2020-11-13'
deprecationDate: '2020-02-14'
category: oauth-authorizations
subcategory:
deprecated: true
"/codes_of_conduct":
get:
summary: Get all codes of conduct
description: ''
tags:
- codes-of-conduct
operationId: codes-of-conduct/get-all-codes-of-conduct
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/codes-of-conduct#get-all-codes-of-conduct
parameters: []
responses:
'200':
description: Response
content:
application/json:
schema:
type: array
items:
"$ref": "#/components/schemas/code-of-conduct"
examples:
default:
"$ref": "#/components/examples/code-of-conduct-simple-items"
'304':
"$ref": "#/components/responses/not_modified"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: codes-of-conduct
subcategory:
"/codes_of_conduct/{key}":
get:
summary: Get a code of conduct
description: ''
tags:
- codes-of-conduct
operationId: codes-of-conduct/get-conduct-code
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/codes-of-conduct#get-a-code-of-conduct
parameters:
- name: key
in: path
required: true
schema:
type: string
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/code-of-conduct"
examples:
default:
"$ref": "#/components/examples/code-of-conduct"
'404':
"$ref": "#/components/responses/not_found"
'304':
"$ref": "#/components/responses/not_modified"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: codes-of-conduct
subcategory:
"/emojis":
get:
summary: Get emojis
description: Lists all the emojis available to use on GitHub Enterprise Server.
operationId: emojis/get
tags:
- emojis
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/emojis#get-emojis
parameters: []
responses:
'200':
content:
application/json:
schema:
type: object
additionalProperties:
type: string
description: Response
'304':
"$ref": "#/components/responses/not_modified"
x-github:
githubCloudOnly: false
enabledForGitHubApps: true
category: emojis
subcategory:
"/enterprise/announcement":
get:
summary: Get the global announcement banner
description: Gets the current message and expiration date of the global announcement
banner in your enterprise.
tags:
- enterprise-admin
operationId: enterprise-admin/get-announcement
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/announcement"
examples:
default:
"$ref": "#/components/examples/announcement"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: announcement
patch:
summary: Set the global announcement banner
description: Sets the message and expiration time for the global announcement
banner in your enterprise.
tags:
- enterprise-admin
operationId: enterprise-admin/set-announcement
requestBody:
required: true
content:
application/json:
schema:
"$ref": "#/components/schemas/announcement"
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/announcement"
examples:
default:
"$ref": "#/components/examples/announcement"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: announcement
delete:
summary: Remove the global announcement banner
description: Removes the global announcement banner in your enterprise.
tags:
- enterprise-admin
operationId: enterprise-admin/remove-announcement
responses:
'204':
description: Response
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: announcement
"/enterprise/settings/license":
get:
summary: Get license information
description: ''
operationId: enterprise-admin/get-license-information
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-license-information
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/license-info"
examples:
default:
"$ref": "#/components/examples/license-info"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: license
"/enterprise/stats/all":
get:
summary: Get all statistics
description: ''
operationId: enterprise-admin/get-all-stats
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-statistics
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/enterprise-overview"
examples:
default:
"$ref": "#/components/examples/enterprise-overview"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: admin-stats
"/enterprise/stats/comments":
get:
summary: Get comment statistics
description: ''
operationId: enterprise-admin/get-comment-stats
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-comment-statistics
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/enterprise-comment-overview"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: admin-stats
"/enterprise/stats/gists":
get:
summary: Get gist statistics
description: ''
operationId: enterprise-admin/get-gist-stats
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-gist-statistics
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/enterprise-gist-overview"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: admin-stats
"/enterprise/stats/hooks":
get:
summary: Get hooks statistics
operationId: enterprise-admin/get-hooks-stats
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-hooks-statistics
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/enterprise-hook-overview"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: admin-stats
"/enterprise/stats/issues":
get:
summary: Get issue statistics
description: ''
operationId: enterprise-admin/get-issue-stats
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-issues-statistics
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/enterprise-issue-overview"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: admin-stats
"/enterprise/stats/milestones":
get:
summary: Get milestone statistics
description: ''
operationId: enterprise-admin/get-milestone-stats
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-milestone-statistics
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/enterprise-milestone-overview"
x-github:
githubCloudOnly: false
enabledForGitHubApps: false
category: enterprise-admin
subcategory: admin-stats
"/enterprise/stats/orgs":
get:
summary: Get organization statistics
description: ''
operationId: enterprise-admin/get-org-stats
tags:
- enterprise-admin
externalDocs:
description: API method documentation
url: https://docs.github.com/enterprise-server@3.3/rest/reference/enterprise-admin#get-organization-statistics
responses:
'200':
description: Response
content:
application/json:
schema:
"$ref": "#/components/schemas/enterprise-organization-overview"
x-github:
git
gitextract_33neljsu/ ├── .changeset/ │ ├── README.md │ └── config.json ├── .editorconfig ├── .github/ │ └── workflows/ │ └── release.yaml ├── .gitignore ├── .prettierignore ├── .prettierrc.js ├── CHANGELOG.md ├── README.md ├── bin/ │ └── cli.js ├── example/ │ ├── .gitignore │ ├── index.html │ ├── package.json │ ├── src/ │ │ ├── App.tsx │ │ ├── index.css │ │ ├── main.tsx │ │ └── vite-env.d.ts │ ├── tsconfig.app.json │ ├── tsconfig.json │ ├── tsconfig.node.json │ └── vite.config.mjs ├── lefthook.yml ├── package.json ├── pnpm-workspace.yaml ├── scripts/ │ └── changelog.sh ├── src/ │ ├── cli.ts │ ├── generate.ts │ ├── swagger.ts │ ├── template.ts │ ├── transform.ts │ ├── types.ts │ └── utils.ts ├── test/ │ ├── ai-runtime.spec.ts │ ├── fixture/ │ │ ├── githubapi.yaml │ │ ├── petstore.json │ │ ├── strings.yaml │ │ └── test.yaml │ ├── generate.spec.ts │ ├── template.spec.ts │ ├── transform.spec.ts │ ├── typescript-generation.spec.ts │ └── utils.spec.ts ├── tsconfig.json ├── tsup.config.ts └── vitest.config.ts
SYMBOL INDEX (38 symbols across 10 files)
FILE: example/src/App.tsx
function App (line 5) | function App() {
FILE: example/src/main.tsx
function enableMocking (line 5) | async function enableMocking() {
function mountApp (line 12) | function mountApp() {
FILE: src/generate.ts
function generateOperationCollection (line 16) | function generateOperationCollection(apiDoc: OpenAPIV3.Document, options...
function generate (line 26) | async function generate(spec: string, inlineOptions: CliOptions) {
function getServerUrl (line 71) | function getServerUrl(apiDoc: OpenAPIV3.Document) {
type OperationDefinition (line 88) | type OperationDefinition = {
function getOperationDefinitions (line 95) | function getOperationDefinitions(v3Doc: OpenAPIV3.Document): OperationDe...
function operationFilter (line 113) | function operationFilter(operation: OperationDefinition, options: CliOpt...
function codeFilter (line 126) | function codeFilter(operation: OperationDefinition, options: CliOptions)...
function toOperation (line 149) | function toOperation(definition: OperationDefinition, apiGen: ApiGenerat...
function autoPopRefs (line 186) | function autoPopRefs<T>(cb: () => T) {
function resolve (line 193) | function resolve(schema: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObj...
function recursiveResolveSchema (line 204) | function recursiveResolveSchema(schema: OpenAPIV3.ReferenceObject | Open...
FILE: src/swagger.ts
function getV3Doc (line 6) | async function getV3Doc(spec: string): Promise<OpenAPIV3.Document> {
FILE: src/template.ts
function assertAiConfig (line 88) | function assertAiConfig(options: ConfigOptions) {
function createAiGenerateText (line 174) | function createAiGenerateText(options: ConfigOptions): string {
function withCacheOne (line 184) | function withCacheOne(options: ConfigOptions) {
FILE: src/transform.ts
constant MAX_STRING_LENGTH (line 9) | const MAX_STRING_LENGTH = DEFAULT_MAX_STRING_LENGTH;
type ResponseMap (line 11) | interface ResponseMap {
type Operation (line 17) | interface Operation {
type OperationCollection (line 23) | type OperationCollection = Operation[];
function getResIdentifierName (line 25) | function getResIdentifierName(res: ResponseMap) {
function transformToGenerateResultFunctions (line 32) | function transformToGenerateResultFunctions(
function scoreHandlerPath (line 92) | function scoreHandlerPath(path: string) {
function compareOperationsForMsw (line 102) | function compareOperationsForMsw(a: Operation, b: Operation) {
function transformToHandlerCode (line 123) | function transformToHandlerCode(operationCollection: OperationCollection...
function transformJSONSchemaToFakerCode (line 159) | function transformJSONSchemaToFakerCode(jsonSchema?: OpenAPIV3.SchemaObj...
function transformStringBasedOnFormat (line 243) | function transformStringBasedOnFormat(schema: OpenAPIV3.NonArraySchemaOb...
FILE: src/types.ts
type CliOptions (line 1) | interface CliOptions {
type ConfigOptions (line 18) | type ConfigOptions = CliOptions & {
FILE: src/utils.ts
constant DEFAULT_MAX_ARRAY_LENGTH (line 5) | const DEFAULT_MAX_ARRAY_LENGTH = 20;
constant DEFAULT_MAX_STRING_LENGTH (line 6) | const DEFAULT_MAX_STRING_LENGTH = 42;
constant EXTENSION_TO_PARSER (line 23) | const EXTENSION_TO_PARSER: Record<string, string> = {
function prettify (line 41) | async function prettify(filePath: string | null, content: string): Promi...
FILE: test/ai-runtime.spec.ts
function createPrompt (line 31) | function createPrompt(_operation: unknown) {
FILE: test/typescript-generation.spec.ts
constant TEST_OUTPUT_DIR (line 7) | const TEST_OUTPUT_DIR = 'test-output';
constant TEST_SPEC_PATH (line 8) | const TEST_SPEC_PATH = './test/fixture/test.yaml';
Condensed preview — 45 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (2,877K chars).
[
{
"path": ".changeset/README.md",
"chars": 510,
"preview": "# Changesets\n\nHello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that wo"
},
{
"path": ".changeset/config.json",
"chars": 277,
"preview": "{\n \"$schema\": \"https://unpkg.com/@changesets/config@3.0.2/schema.json\",\n \"changelog\": \"@changesets/cli/changelog\",\n \""
},
{
"path": ".editorconfig",
"chars": 228,
"preview": "# EditorConfig is awesome: https://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n[*]\nindent_style = space\n"
},
{
"path": ".github/workflows/release.yaml",
"chars": 1053,
"preview": "# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created\n# For "
},
{
"path": ".gitignore",
"chars": 99,
"preview": "node_modules/\ndist/\nexample/src/mock.js\nexample/test*.js\n\n.idea/\n.vscode/\n\n*.log\npackage-lock.json\n"
},
{
"path": ".prettierignore",
"chars": 60,
"preview": "dist\nnode_modules\nbuild\ncoverage\nexample/src/mock.js\nfixture"
},
{
"path": ".prettierrc.js",
"chars": 100,
"preview": "module.exports = {\n singleQuote: true,\n arrowParens: 'avoid',\n semi: true,\n printWidth: 120,\n};\n"
},
{
"path": "CHANGELOG.md",
"chars": 2499,
"preview": "# msw-auto-mock\n\n## 0.32.1\n\n### Patch Changes\n\n- 5ea0a3e: [WIP] Fix reference error for MAX_STRING_LENGTH in generated c"
},
{
"path": "README.md",
"chars": 5093,
"preview": "# msw-auto-mock\n\n;\n"
},
{
"path": "example/.gitignore",
"chars": 85,
"preview": "node_modules\n.DS_Store\ndist\ndist-ssr\n*.local\nmock/\n.env\n\npublic/mockServiceWorker.js\n"
},
{
"path": "example/index.html",
"chars": 279,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width,"
},
{
"path": "example/package.json",
"chars": 906,
"preview": "{\n \"name\": \"example\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\":"
},
{
"path": "example/src/App.tsx",
"chars": 1511,
"preview": "import { useState } from 'react';\n\nconst methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE']"
},
{
"path": "example/src/index.css",
"chars": 385,
"preview": "body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Can"
},
{
"path": "example/src/main.tsx",
"chars": 473,
"preview": "import './index.css';\nimport { createRoot } from 'react-dom/client';\nimport App from './App';\n\nasync function enableMock"
},
{
"path": "example/src/vite-env.d.ts",
"chars": 38,
"preview": "/// <reference types=\"vite/client\" />\n"
},
{
"path": "example/tsconfig.app.json",
"chars": 665,
"preview": "{\n \"compilerOptions\": {\n \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.app.tsbuildinfo\",\n \"target\": \"ES2020\",\n"
},
{
"path": "example/tsconfig.json",
"chars": 119,
"preview": "{\n \"files\": [],\n \"references\": [\n { \"path\": \"./tsconfig.app.json\" },\n { \"path\": \"./tsconfig.node.json\" }\n ]\n}\n"
},
{
"path": "example/tsconfig.node.json",
"chars": 593,
"preview": "{\n \"compilerOptions\": {\n \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.node.tsbuildinfo\",\n \"target\": \"ES2022\","
},
{
"path": "example/vite.config.mjs",
"chars": 166,
"preview": "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport def"
},
{
"path": "lefthook.yml",
"chars": 485,
"preview": "# EXAMPLE USAGE:\n#\n# Refer for explanation to following link:\n# https://github.com/evilmartians/lefthook/blob/master"
},
{
"path": "package.json",
"chars": 1773,
"preview": "{\n \"name\": \"msw-auto-mock\",\n \"version\": \"0.32.1\",\n \"description\": \"Generate random mock data from OpenAPI description"
},
{
"path": "pnpm-workspace.yaml",
"chars": 59,
"preview": "packages:\n - example\n - .\nonlyBuiltDependencies:\n - msw\n"
},
{
"path": "scripts/changelog.sh",
"chars": 584,
"preview": "#!/bin/bash\n\n# Get the repository URL from package.json\nREPO_URL=$(node -e \"console.log(require('./package.json').reposi"
},
{
"path": "src/cli.ts",
"chars": 1714,
"preview": "import cac from 'cac';\n\nimport { generate } from './generate';\nimport { version } from '../package.json';\n\nconst cli = c"
},
{
"path": "src/generate.ts",
"chars": 7978,
"preview": "import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport ApiGenerator, { isReference } from 'oazapfts/g"
},
{
"path": "src/swagger.ts",
"chars": 555,
"preview": "import SwaggerParser from '@apidevtools/swagger-parser';\nimport type { OpenAPIV3 } from 'openapi-types';\n// @ts-ignore l"
},
{
"path": "src/template.ts",
"chars": 6985,
"preview": "import { ConfigOptions } from './types';\nimport { OperationCollection, transformToHandlerCode, transformToGenerateResult"
},
{
"path": "src/transform.ts",
"chars": 10869,
"preview": "import vm from 'node:vm';\nimport { OpenAPIV3 } from 'openapi-types';\nimport merge from 'lodash/merge';\nimport camelCase "
},
{
"path": "src/types.ts",
"chars": 980,
"preview": "export interface CliOptions {\n output: string;\n maxArrayLength?: number;\n includes?: string;\n excludes?: string;\n b"
},
{
"path": "src/utils.ts",
"chars": 1864,
"preview": "import * as prettier from 'prettier';\nimport * as path from 'path';\nimport camelCase from 'lodash/camelCase';\n\nexport co"
},
{
"path": "test/ai-runtime.spec.ts",
"chars": 1456,
"preview": "import { describe, expect, it, vi } from 'vitest';\n\nimport { createAiGenerateText } from '../src/template';\n\n// This tes"
},
{
"path": "test/fixture/githubapi.yaml",
"chars": 2688861,
"preview": "---\nopenapi: 3.0.3\ninfo:\n version: 1.1.4\n title: GitHub v3 REST API\n description: GitHub's v3 REST API.\n license:\n "
},
{
"path": "test/fixture/petstore.json",
"chars": 21268,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server. You can find out more ab"
},
{
"path": "test/fixture/strings.yaml",
"chars": 789,
"preview": "openapi: 3.0.0\ninfo:\n title: (title)\n version: 0.0.0\ntags: []\npaths:\n /test:\n get:\n operationId: strings\n "
},
{
"path": "test/fixture/test.yaml",
"chars": 3328,
"preview": "openapi: '3.0.2'\ninfo:\n title: Test\n version: '1.0'\ncomponents:\n examples:\n customerData:\n value:\n id:"
},
{
"path": "test/generate.spec.ts",
"chars": 2793,
"preview": "import get from 'lodash/get';\nimport keys from 'lodash/keys';\nimport { OpenAPIV3 } from 'openapi-types';\nimport { before"
},
{
"path": "test/template.spec.ts",
"chars": 2049,
"preview": "import { describe, expect, it } from 'vitest';\n\nimport { mockTemplate } from '../src/template';\n\ndescribe('template:cons"
},
{
"path": "test/transform.spec.ts",
"chars": 7532,
"preview": "import { describe, expect, it, vi } from 'vitest';\n\nimport {\n transformToGenerateResultFunctions,\n transformJSONSchema"
},
{
"path": "test/typescript-generation.spec.ts",
"chars": 2729,
"preview": "import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { beforeAll, afterAll, describe, it, expect } f"
},
{
"path": "test/utils.spec.ts",
"chars": 792,
"preview": "import { describe, expect, it } from 'vitest';\n\nimport { isValidRegExp, toExpressLikePath } from '../src/utils';\n\ndescri"
},
{
"path": "tsconfig.json",
"chars": 380,
"preview": "{\n \"compilerOptions\": {\n \"module\": \"ESNext\",\n \"target\": \"esnext\",\n \"lib\": [\"ESNext\", \"DOM\"],\n \"esModuleInte"
},
{
"path": "tsup.config.ts",
"chars": 208,
"preview": "import type { Options } from 'tsup';\n\nexport const tsup: Options = {\n splitting: false,\n sourcemap: false,\n clean: tr"
},
{
"path": "vitest.config.ts",
"chars": 107,
"preview": "import { defineConfig } from 'vitest/config';\n\nexport default defineConfig({\n test: {\n // ...\n },\n});\n"
}
]
About this extraction
This page contains the full source code of the zoubingwu/msw-auto-mock GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 45 files (2.7 MB), approximately 697.2k tokens, and a symbol index with 38 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.