or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-octokit--core

Extendable client for GitHub's REST & GraphQL APIs

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@octokit/core@7.0.x

To install, run

npx @tessl/cli install tessl/npm-octokit--core@7.0.0

0

# Octokit Core

1

2

Octokit Core is an extendable TypeScript client library for GitHub's REST & GraphQL APIs. It provides a minimal foundation with a plugin architecture for building comprehensive GitHub API clients with customizable authentication strategies, lifecycle hooks, and extensible functionality.

3

4

## Package Information

5

6

- **Package Name**: @octokit/core

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @octokit/core`

10

11

## Core Imports

12

13

```typescript

14

import { Octokit, type OctokitOptions } from "@octokit/core";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { Octokit } = require("@octokit/core");

21

```

22

23

Types-only import:

24

25

```typescript

26

import type { OctokitOptions, OctokitPlugin, Hooks } from "@octokit/core/types";

27

```

28

29

Version import:

30

31

```typescript

32

import { VERSION } from "@octokit/core";

33

```

34

35

## Basic Usage

36

37

```typescript

38

import { Octokit } from "@octokit/core";

39

40

// Basic GitHub API client

41

const octokit = new Octokit({

42

auth: "github_pat_11ABCDEFG_...", // personal access token

43

});

44

45

// Make REST API requests

46

const { data: user } = await octokit.request("GET /user");

47

console.log(`Hello ${user.login}`);

48

49

// Make GraphQL requests

50

const { viewer } = await octokit.graphql(`

51

query {

52

viewer {

53

login

54

name

55

}

56

}

57

`);

58

59

// Use authentication

60

const userAuth = await octokit.auth();

61

console.log("Token type:", userAuth.type);

62

```

63

64

## Architecture

65

66

Octokit Core is built on several key architectural principles:

67

68

- **Minimal Core**: Provides only essential functionality (REST, GraphQL, auth, logging, hooks)

69

- **Plugin System**: Extensible architecture via static `plugin()` method for adding functionality

70

- **Authentication Strategies**: Pluggable authentication system supporting multiple token types

71

- **Request Lifecycle**: Hook system for intercepting and modifying requests/responses

72

- **Framework Integration**: Seamless integration with other @octokit packages

73

74

## Capabilities

75

76

### Client Instantiation

77

78

Create Octokit clients with various configuration options.

79

80

```typescript { .api }

81

/**

82

* Main Octokit client class

83

*/

84

class Octokit {

85

/**

86

* Create a new Octokit client instance

87

* @param options - Configuration options for the client

88

*/

89

constructor(options?: OctokitOptions);

90

}

91

```

92

93

### Package Version

94

95

Access the package version string.

96

97

```typescript { .api }

98

/**

99

* Version string of the @octokit/core package

100

*/

101

const VERSION: string;

102

```

103

104

### Static Class Methods

105

106

Configure and extend the Octokit class with plugins and defaults.

107

108

```typescript { .api }

109

/**

110

* Version string of the @octokit/core package

111

*/

112

static VERSION: string;

113

114

/**

115

* Array of registered plugins

116

*/

117

static plugins: OctokitPlugin[];

118

119

/**

120

* Create a new Octokit class with preset default options

121

* @param defaults - Default options or a function returning default options

122

* @returns Extended Octokit class with preset defaults

123

*/

124

static defaults<S extends Constructor<any>>(

125

this: S,

126

defaults: OctokitOptions | Function

127

): typeof this;

128

129

/**

130

* Extend Octokit class with plugins

131

* @param newPlugins - One or more plugin functions to attach

132

* @returns Extended Octokit class with plugin functionality

133

*/

134

static plugin<S extends Constructor<any> & { plugins: any[] }, T extends OctokitPlugin[]>(

135

this: S,

136

...newPlugins: T

137

): typeof this & Constructor<UnionToIntersection<ReturnTypeOf<T>>>;

138

```

139

140

**Usage Examples:**

141

142

```typescript

143

// Create class with default options

144

const MyOctokit = Octokit.defaults({

145

baseUrl: "https://github.company.com/api/v3",

146

auth: "token",

147

});

148

149

// Create class with plugins

150

const ExtendedOctokit = Octokit.plugin(restPlugin, paginatePlugin);

151

const octokit = new ExtendedOctokit({ auth: "token" });

152

```

153

154

### REST API Requests

155

156

Make HTTP requests to GitHub's REST API.

157

158

```typescript { .api }

159

/**

160

* REST API client from @octokit/request

161

* Supports all GitHub REST API endpoints

162

*/

163

request: typeof request;

164

```

165

166

**Usage Examples:**

167

168

```typescript

169

// GET request

170

const { data: repos } = await octokit.request("GET /user/repos", {

171

sort: "updated",

172

per_page: 50,

173

});

174

175

// POST request

176

const { data: issue } = await octokit.request("POST /repos/{owner}/{repo}/issues", {

177

owner: "octokit",

178

repo: "core.js",

179

title: "New issue",

180

body: "Issue description",

181

});

182

183

// Request with custom headers

184

const response = await octokit.request("GET /user", {

185

headers: {

186

"X-GitHub-Media-Type": "github.v3+json",

187

},

188

});

189

```

190

191

### GraphQL API Requests

192

193

Execute GraphQL queries and mutations against GitHub's GraphQL API.

194

195

```typescript { .api }

196

/**

197

* GraphQL API client from @octokit/graphql

198

* Supports GitHub's GraphQL API v4

199

*/

200

graphql: typeof graphql;

201

```

202

203

**Usage Examples:**

204

205

```typescript

206

// Simple query

207

const { repository } = await octokit.graphql(`

208

query($owner: String!, $name: String!) {

209

repository(owner: $owner, name: $name) {

210

description

211

stargazerCount

212

}

213

}

214

`, {

215

owner: "octokit",

216

name: "core.js",

217

});

218

219

// Mutation

220

const { createIssue } = await octokit.graphql(`

221

mutation($repositoryId: ID!, $title: String!, $body: String!) {

222

createIssue(input: {

223

repositoryId: $repositoryId,

224

title: $title,

225

body: $body

226

}) {

227

issue {

228

number

229

url

230

}

231

}

232

}

233

`, {

234

repositoryId: "MDEwOlJlcG9zaXRvcnkxMzc4NDI1MjE=",

235

title: "New issue",

236

body: "Created via GraphQL",

237

});

238

```

239

240

### Authentication

241

242

Authenticate requests using various GitHub authentication strategies.

243

244

```typescript { .api }

245

/**

246

* Authentication method - returns authentication details

247

* The actual signature depends on the authentication strategy used

248

*/

249

auth: (...args: unknown[]) => Promise<unknown>;

250

```

251

252

**Usage Examples:**

253

254

```typescript

255

// Get current authentication details

256

const auth = await octokit.auth();

257

console.log(auth.type); // "token", "oauth-token", "installation", etc.

258

259

// Use with different auth strategies

260

const octokit = new Octokit({

261

authStrategy: createAppAuth,

262

auth: {

263

appId: 123,

264

privateKey: "-----BEGIN PRIVATE KEY-----\n...",

265

installationId: 456,

266

},

267

});

268

```

269

270

### Logging

271

272

Configurable logging system for debugging and monitoring.

273

274

```typescript { .api }

275

/**

276

* Logger instance with configurable methods

277

*/

278

log: {

279

/** Log debug information (no-op by default) */

280

debug: (message: string, additionalInfo?: object) => any;

281

/** Log informational messages (no-op by default) */

282

info: (message: string, additionalInfo?: object) => any;

283

/** Log warning messages (uses console.warn by default) */

284

warn: (message: string, additionalInfo?: object) => any;

285

/** Log error messages (uses console.error by default) */

286

error: (message: string, additionalInfo?: object) => any;

287

/** Additional custom log methods */

288

[key: string]: any;

289

};

290

```

291

292

**Usage Examples:**

293

294

```typescript

295

// Custom logger

296

const octokit = new Octokit({

297

log: {

298

debug: (msg, info) => console.debug(`DEBUG: ${msg}`, info),

299

info: (msg, info) => console.info(`INFO: ${msg}`, info),

300

warn: (msg, info) => console.warn(`WARN: ${msg}`, info),

301

error: (msg, info) => console.error(`ERROR: ${msg}`, info),

302

},

303

});

304

305

// Default logging

306

octokit.log.debug("Making request", { endpoint: "/user" });

307

octokit.log.error("Request failed", { error: "Not found" });

308

```

309

310

### Request Lifecycle Hooks

311

312

Intercept and modify requests and responses using the hook system.

313

314

```typescript { .api }

315

/**

316

* Hook collection for request lifecycle management

317

* Uses the before-after-hook library

318

*/

319

hook: HookCollection<Hooks>;

320

```

321

322

**Usage Examples:**

323

324

```typescript

325

// Add request interceptor

326

octokit.hook.before("request", async (options) => {

327

console.log(`Making request to ${options.url}`);

328

options.headers["x-custom-header"] = "custom-value";

329

});

330

331

// Add response interceptor

332

octokit.hook.after("request", async (response, options) => {

333

console.log(`Request completed with status ${response.status}`);

334

});

335

336

// Add error handler

337

octokit.hook.error("request", async (error, options) => {

338

console.error(`Request failed: ${error.message}`);

339

throw error;

340

});

341

```

342

343

## Configuration Options

344

345

```typescript { .api }

346

/**

347

* Configuration options for Octokit constructor

348

*/

349

interface OctokitOptions {

350

/** Authentication strategy constructor (defaults to token auth) */

351

authStrategy?: any;

352

/** Authentication configuration (token, app credentials, etc.) */

353

auth?: any;

354

/** Custom User-Agent string */

355

userAgent?: string;

356

/** GitHub API preview features to enable */

357

previews?: string[];

358

/** Base URL for GitHub API (for GitHub Enterprise) */

359

baseUrl?: string;

360

/** Custom logger configuration */

361

log?: {

362

debug: (message: string) => unknown;

363

info: (message: string) => unknown;

364

warn: (message: string) => unknown;

365

error: (message: string) => unknown;

366

};

367

/** Request-specific options */

368

request?: OctokitTypes.RequestRequestOptions;

369

/** Timezone header for API requests */

370

timeZone?: string;

371

/** Additional custom options */

372

[option: string]: any;

373

}

374

```

375

376

## Plugin System Types

377

378

```typescript { .api }

379

/**

380

* Plugin function signature

381

* @param octokit - Octokit instance being extended

382

* @param options - Options passed to the constructor

383

* @returns Object with methods/properties to add to the instance, or void

384

*/

385

type OctokitPlugin = (

386

octokit: Octokit,

387

options: OctokitOptions

388

) => { [key: string]: any } | void;

389

```

390

391

## Hook System Types

392

393

```typescript { .api }

394

/**

395

* Hook system type definitions for request lifecycle

396

*/

397

type Hooks = {

398

request: {

399

Options: Required<OctokitTypes.EndpointDefaults>;

400

Result: OctokitTypes.OctokitResponse<any>;

401

Error: RequestError | Error;

402

};

403

[key: string]: {

404

Options: unknown;

405

Result: unknown;

406

Error: unknown;

407

};

408

};

409

```

410

411

## Utility Types

412

413

```typescript { .api }

414

/**

415

* Constructor function type

416

*/

417

type Constructor<T> = new (...args: any[]) => T;

418

419

/**

420

* Any function type

421

*/

422

type AnyFunction = (...args: any) => any;

423

424

/**

425

* Extract return type from function or array of functions

426

*/

427

type ReturnTypeOf<T extends AnyFunction | AnyFunction[]> =

428

T extends AnyFunction

429

? ReturnType<T>

430

: T extends AnyFunction[]

431

? // exclude `void` from intersection, see octokit/octokit.js#2115

432

UnionToIntersection<Exclude<ReturnType<T[number]>, void>>

433

: never;

434

435

/**

436

* Convert union types to intersection types

437

*/

438

type UnionToIntersection<Union> = (

439

Union extends any ? (argument: Union) => void : never

440

) extends (argument: infer Intersection) => void

441

? Intersection

442

: never;

443

444

/**

445

* Strict version of TypeScript's Omit utility type

446

*/

447

type StrictOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

448

449

/**

450

* Request parameters type from @octokit/types

451

*/

452

type RequestParameters = OctokitTypes.RequestParameters;

453

```

454

455

## Error Handling

456

457

Octokit Core integrates with @octokit/request-error for consistent error handling:

458

459

```typescript

460

try {

461

await octokit.request("GET /repos/nonexistent/repo");

462

} catch (error) {

463

if (error.status === 404) {

464

console.log("Repository not found");

465

}

466

console.error("Request failed:", error.message);

467

}

468

```

469

470

Common error scenarios:

471

- **401 Unauthorized**: Invalid or missing authentication

472

- **403 Forbidden**: Insufficient permissions or rate limit exceeded

473

- **404 Not Found**: Resource does not exist

474

- **422 Unprocessable Entity**: Validation errors in request data