=============== LIBRARY RULES =============== From library maintainers: - Install with `npm install jira.js`. Import the specific client you need (`Version3Client`, `Version2Client`, `AgileClient`, `ServiceDeskClient`) for tree-shaking rather than the package root. - Use `Version3Client` for the Jira Cloud REST API v3 (rich text via Atlassian Document Format); use `Version2Client` for API v2 (wiki-markup/plain-string fields). - Provide `host` (e.g. `https://your-domain.atlassian.net`) for Basic and JWT auth — it is required. With OAuth 2.0 `host` is optional and the cloudId is resolved automatically from the access token. - Basic auth: `authentication: { basic: { email, apiToken } }`. Use an Atlassian API token, never an account password. - OAuth 2.0 (3LO): pass `authentication: { oauth2: { accessToken } }`, or enable automatic refresh by providing `refreshToken`, `clientId`, and `clientSecret` together. - Atlassian rotates the OAuth 2.0 refresh token on every refresh and invalidates the previous one — persist the new value via the `onTokenRefresh` callback so the next process start uses the latest token. - Never expose `clientSecret` in a browser; OAuth 2.0 token refresh is server-side only. - JWT (Atlassian Connect): `authentication: { jwt: { issuer, secret } }`, using the app-descriptor key as `issuer` and the installation handshake shared secret. - Every endpoint method takes a single typed parameters object and returns a Promise; an optional Node-style `callback` may be passed as the last argument. - Failed requests throw an `HttpException` (or an Axios error) — wrap calls in try/catch and inspect `status`/`response` to handle errors. - `getAttachmentContent` accepts an optional `range` (HTTP Range header, e.g. `bytes=0-1023`) for partial/byte-range downloads, returning 206 Partial Content. - Deep subpath imports are supported for types, e.g. `jira.js/version3/parameters` and `jira.js/version3/models`. ### Run Get All Worklogs Example Source: https://github.com/mrrefactoring/jira.js/blob/master/examples/README.md Executes the get all worklogs example script to create a task, add a worklog, and then retrieve all worklogs for that task. ```console npm run getAllWorklogs ``` -------------------------------- ### Jira Installation Payload Example Source: https://github.com/mrrefactoring/jira.js/blob/master/guides/jwt-authentication.md This is an example of the JSON payload received when a Jira app is installed. It contains essential tenant information. ```json { "key": "my-backend-integration", "clientKey": "unique-tenant-id", "sharedSecret": "DO-NOT-LOG-OR-EXPOSE-THIS", "baseUrl": "https://your-domain.atlassian.net", "displayUrl": "https://your-domain.atlassian.net", "productType": "jira", "eventType": "installed" } ``` -------------------------------- ### Install Dependencies Source: https://github.com/mrrefactoring/jira.js/blob/master/examples/README.md Installs the necessary Node.js packages for the jira.js examples. ```console npm i ``` -------------------------------- ### Get Issue Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Example demonstrating how to retrieve an issue by its key and expand its changelog. ```typescript const issue = await client.issues.getIssue({ issueIdOrKey: 'PROJ-123', expand: ['changelog'] }); ``` -------------------------------- ### Install jira.js Source: https://github.com/mrrefactoring/jira.js/blob/master/docs/guide/getting-started.md Install the jira.js library using npm. For other package managers like yarn or pnpm, refer to the installation guide. ```bash npm install jira.js ``` -------------------------------- ### Run Basic Example Source: https://github.com/mrrefactoring/jira.js/blob/master/examples/README.md Executes the basic example script to create a new project and task, or adds a task to an existing project. ```console npm run basic ``` -------------------------------- ### Run Add Worklog Example Source: https://github.com/mrrefactoring/jira.js/blob/master/examples/README.md Executes the add worklog example script to create a task and add a worklog to it. ```console npm run addWorklog ``` -------------------------------- ### Install jira.js with npm, yarn, or pnpm Source: https://github.com/mrrefactoring/jira.js/blob/master/docs/guide/installation.md Install the jira.js library using your preferred Node.js package manager. ```bash # npm npm install jira.js ``` ```bash # yarn yarn add jira.js ``` ```bash # pnpm pnpm add jira.js ``` -------------------------------- ### Fetch Current User and Search Issues Source: https://github.com/mrrefactoring/jira.js/blob/master/docs/guide/getting-started.md Make your first requests to the Jira API. This example shows how to get the current user's display name and search for issues using JQL. The results are logged to the console. ```typescript // Who am I? const me = await client.myself.getCurrentUser(); console.log(me.displayName); // Search with JQL const { issues } = await client.issueSearch.searchForIssuesUsingJql({ jql: 'project = TEST AND statusCategory != Done ORDER BY created DESC', maxResults: 20, }); for (const issue of issues ?? []) { console.log(issue.key, issue.fields.summary); } ``` -------------------------------- ### Start Sprint Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Starts a specified sprint. ```APIDOC ## Start Sprint ### Description Starts a specified sprint, changing its status to 'active'. ### Method POST (or similar, based on client method) ### Endpoint `/rest/agile/1.0/sprint/{sprintId}/start` (Hypothetical endpoint based on client method) ### Parameters #### Path Parameters - **sprintId** (integer) - Required - The ID of the sprint to start. ### Request Example ```typescript await client.sprint.startSprint({ sprintId: 1 }); ``` ### Response (Success response details not provided in source) ``` -------------------------------- ### Create Issue Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/parameters-and-models.md A practical example of creating an issue with specified fields, including project, summary, description, issue type, priority, assignee, components, labels, and fix versions. ```typescript const issue = await client.issues.createIssue({ fields: { project: { key: 'PROJ' }, summary: 'Bug: Login fails', description: 'Users cannot login via OAuth', issuetype: { name: 'Bug' }, priority: { name: 'High' }, assignee: { emailAddress: 'dev@example.com' }, components: [{ name: 'Authentication' }], labels: ['critical', 'oauth'], fixVersions: [{ name: '1.0.0' }] } }); ``` -------------------------------- ### Install Jira.js Package Source: https://github.com/mrrefactoring/jira.js/blob/master/README.md Install the Jira.js npm package using your preferred package manager. Requires Node.js 20.0.0 or newer. ```bash # Using npm npm install jira.js ``` ```bash # Using yarn yarn add jira.js ``` ```bash # Using pnpm pnpm add jira.js ``` -------------------------------- ### Creating a Custom Client Source: https://github.com/mrrefactoring/jira.js/blob/master/docs/guide/tree-shaking.md Compose a `BaseClient` with only the essential resources for the smallest possible bundle. This example demonstrates creating a client and using the `Issues` resource. ```typescript import { BaseClient } from 'jira.js'; import { Issues } from 'jira.js/version3'; const client = new BaseClient({ host, authentication }); const issues = new Issues(client); await issues.getIssue({ issueIdOrKey: 'TEST-1' }); ``` -------------------------------- ### Setup Jira Credentials Source: https://github.com/mrrefactoring/jira.js/blob/master/examples/README.md Configures Jira host, email, and API token for authentication in the jira.js library. ```typescript const host = 'https://your-domain.atlassian.net'; const email = 'YOUR_EMAIL'; const apiToken = 'YOUR_API_TOKEN'; ``` -------------------------------- ### BaseClient sendRequestFullResponse Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Example of using sendRequestFullResponse to retrieve the full response object. ```typescript const response = await client.sendRequestFullResponse({ url: '/rest/api/3/issue/KEY-1', method: 'GET' }); console.log(response.status); // 200 console.log(response.headers); // { ... } ``` -------------------------------- ### Search For Issues Using JQL Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Example of searching for open, high-priority issues and specifying the maximum number of results and fields to return. ```typescript const results = await client.issues.searchForIssuesUsingJql({ jql: 'status = Open AND priority = High', maxResults: 50, fields: ['key', 'summary', 'status'] }); ``` -------------------------------- ### Create Jira Issue with TypeScript Source: https://github.com/mrrefactoring/jira.js/blob/master/README.md Example demonstrating how to create a Jira issue using the TypeScript client. Ensure you have Node.js 20.0.0 or newer installed. Replace placeholders with your actual Jira domain, email, API token, and project ID/key. ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN', // Create one: https://id.atlassian.com/manage-profile/security/api-tokens }, }, }); async function createIssue() { const project = await client.projects.getProject({ projectIdOrKey: 'Your project id or key' }); const newIssue = await client.issues.createIssue({ fields: { summary: 'Hello Jira.js!', issuetype: { name: 'Task' }, project: { key: project.key }, }, }); console.log(`Issue created: ${newIssue.id}`); } createIssue(); ``` -------------------------------- ### Get Worklogs for a Jira Issue Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieve all worklog entries associated with a Jira issue. This example fetches issue details with the changelog expand option. ```typescript const issue = await client.issues.getIssue({ issueIdOrKey: 'PROJ-123', expand: ['changelog'] }); issue.fields.worklog.worklogs.forEach(log => { console.log(`${log.author.displayName}: ${log.timeSpent}`); }); ``` -------------------------------- ### BaseClient sendRequest Examples Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Demonstrates using sendRequest with both Promise-based and callback-based approaches. ```typescript // Promise-based const issue = await client.sendRequest({ url: '/rest/api/3/issue/KEY-1', method: 'GET' }); // Callback-based client.sendRequest( { url: '/rest/api/3/issue/KEY-1', method: 'GET' }, (error, data) => { if (error) console.error(error); else console.log(data); } ); ``` -------------------------------- ### Create Issue Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Example of how to use the createIssue method to create a new bug report in a project. ```typescript const issue = await client.issues.createIssue({ fields: { project: { key: 'PROJ' }, summary: 'Bug report', issuetype: { name: 'Bug' } } }); console.log(issue.id); ``` -------------------------------- ### Start Sprint Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Starts an existing sprint. Requires the sprint ID. ```typescript async startSprint( parameters: StartSprint, callback?: Callback ): Promise ``` -------------------------------- ### Get Issue with Expand Parameters Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/parameters-and-models.md Example of retrieving an issue and including nested data such as changelog, history, and transitions. Specify desired data in the `expand` array. ```typescript await client.issues.getIssue({ issueIdOrKey: 'PROJ-1', expand: ['changelog', 'history', 'transitions'] }); ``` -------------------------------- ### Get Boards Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieves a list of all available boards. ```APIDOC ## Get Boards ### Description Retrieves a list of all boards available in the Jira instance. ### Method GET (or similar, based on client method) ### Endpoint `/rest/agile/1.0/board` (Hypothetical endpoint based on client method) ### Parameters #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of boards to return. ### Response #### Success Response - **values** (array) - An array of board objects. - Each board object contains: - **id** (integer) - The ID of the board. - **name** (string) - The name of the board. ``` -------------------------------- ### Optional Parameters Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Demonstrates calling a method with optional parameters, both with and without providing them. This pattern is common for methods that do not require all parameters to be set. ```typescript await client.issues.searchForIssuesUsingJql(); // Optional params await client.issues.searchForIssuesUsingJql({ jql: 'status = Open' }); ``` -------------------------------- ### startSprint Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Starts an active sprint. Requires the sprint ID. ```APIDOC ## startSprint ### Description Starts a sprint. ### Parameters #### Request Body - **parameters.sprintId** (number) - Yes - Sprint ID ``` -------------------------------- ### Transition Issue Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/parameters-and-models.md Demonstrates how to transition an issue using the Jira API client. It shows how to specify the issue, the transition by name, and update fields like resolution. ```typescript await client.issues.transitionIssue({ issueIdOrKey: 'PROJ-1', transition: { name: 'Done' }, fields: { resolution: { name: 'Fixed' } } }); ``` -------------------------------- ### Authentication Token Encoding Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/configuration.md Illustrates how basic authentication credentials (email and API token) are Base64 encoded to form the Authorization header. ```typescript // Input email: 'user@example.com' apiToken: 'ATATT...' // Encoded header Authorization: 'Basic dXNlckBleGFtcGxlLmNvbTpBVEFUVA...' ``` -------------------------------- ### Importing Types from Root Export Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/types-and-callbacks.md Example of importing common types and client classes directly from the main 'jira.js' package export. ```typescript import { Callback, Paginated, HttpException, Version3Client, AgileClient, ServiceDeskClient, Version2Client, BaseClient } from 'jira.js'; ``` -------------------------------- ### Query Parameter Serialization Examples Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/parameters-and-models.md Illustrates how complex JavaScript parameters are automatically serialized into URL query parameters for Jira API requests. ```typescript // Arrays are comma-separated expand: ['changelog', 'history'] // becomes: ?expand=changelog,history // Objects are JSON stringified fields: { custom: { nested: 'value' } } // becomes: ?fields={"custom":{"nested":"value"}} // Dates are ISO formatted updated: new Date('2024-01-01') // becomes: ?updated=2024-01-01T00:00:00.000Z // Functions are executed filter: () => 'dynamic-value' // becomes: ?filter=dynamic-value ``` -------------------------------- ### Async Method Usage - Promise Pattern Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/types-and-callbacks.md Example of calling an asynchronous method using the Promise pattern and awaiting the result. ```typescript const issue: Issue = await client.issues.getIssue({ issueIdOrKey: 'KEY-1' }); ``` -------------------------------- ### Search Issues with Pagination Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/parameters-and-models.md Example of searching for issues using JQL with specified pagination parameters. Ensure `jql` is a valid Jira Query Language string. ```typescript await client.issues.searchForIssuesUsingJql({ jql: 'status = Open', startAt: 50, maxResults: 100 }); ``` -------------------------------- ### getProject Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Gets detailed project information using the project's ID or key. Allows expanding specific fields. ```APIDOC ## getProject ### Description Gets detailed project information using the project's ID or key. Allows expanding specific fields. ### Method GET ### Endpoint /rest/api/3/project/{projectIdOrKey} ### Parameters #### Path Parameters - **projectIdOrKey** (string) - Required - Project ID or key #### Query Parameters - **expand** (string[]) - Optional - Fields to expand ### Response #### Success Response (200) - **id** (string) - Project ID - **key** (string) - Project key - **name** (string) - Project name #### Response Example { "example": "{\"id\": \"10000\", \"key\": \"PROJ\", \"name\": \"My Project\"}" } ``` -------------------------------- ### Request Parameter Serialization Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/configuration.md Shows how various data types are serialized for request parameters, including arrays, dates, and objects, as handled by the BaseClient. ```typescript await client.issues.searchIssues({ jql: 'status = Open', expand: ['changelog', 'history'], // -> 'changelog,history' updated: new Date('2024-01-01'), // -> ISO string startAt: 0 }); ``` -------------------------------- ### Minimal Express Server for Jira Lifecycle Events Source: https://github.com/mrrefactoring/jira.js/blob/master/guides/jwt-authentication.md A basic Express.js server to handle the 'installed' and 'uninstalled' lifecycle events from Jira. It stores tenant credentials in memory for demonstration purposes. ```typescript import express from 'express'; const app = express(); app.use(express.json()); // Persist these securely (encrypted at rest). In-memory map shown for brevity only. const tenants = new Map(); app.post('/installed', (req, res) => { const { clientKey, sharedSecret, baseUrl } = req.body; tenants.set(clientKey, { sharedSecret, baseUrl }); res.sendStatus(204); }); app.post('/uninstalled', (req, res) => { tenants.delete(req.body.clientKey); res.sendStatus(204); }); app.listen(8080); ``` -------------------------------- ### Importing Specific Clients Source: https://github.com/mrrefactoring/jira.js/blob/master/docs/guide/tree-shaking.md Import only the necessary client modules to reduce bundle size. This example shows how to import `BaseClient` and `Issues` from `jira.js/version3`. ```typescript import { BaseClient } from 'jira.js'; import { Issues } from 'jira.js/version3'; ``` -------------------------------- ### Add Comment with ADF Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/parameters-and-models.md Shows how to construct a comment body using the Atlassian Document Format (ADF) and add it to an issue using the Jira API client. ```typescript const body = { type: 'doc', version: 1, content: [ { type: 'paragraph', content: [ { type: 'text', text: 'This is ' }, { type: 'text', text: 'bold', marks: [{ type: 'strong' }] }, { type: 'text', text: ' text.' } ] }, { type: 'hardBreak' }, { type: 'paragraph', content: [ { type: 'text', text: 'Click here', marks: [{ type: 'link', attrs: { href: 'https://example.com' } }] } ] } ] }; await client.issueComments.addComment({ issueIdOrKey: 'PROJ-1', body }); ``` -------------------------------- ### Get Issue using Promise or Callback Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/README.md Demonstrates fetching an issue using both the Promise pattern (with await) and the Callback pattern. Choose the pattern that best suits your asynchronous programming style. ```typescript // Promise pattern const issue = await client.issues.getIssue({ issueIdOrKey: 'KEY-1' }); ``` ```typescript // Callback pattern client.issues.getIssue( { issueIdOrKey: 'KEY-1' }, (error, issue) => { /* handle */ } ); ``` -------------------------------- ### createSprint Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Creates a new sprint for a given board. Requires board ID and sprint name, with optional start date, end date, and goal. ```APIDOC ## createSprint ### Description Creates a new sprint. ### Parameters #### Request Body - **parameters.boardId** (number) - Yes - Board ID - **parameters.name** (string) - Yes - Sprint name - **parameters.startDate** (string) - No - ISO 8601 start date - **parameters.endDate** (string) - No - ISO 8601 end date - **parameters.goal** (string) - No - Sprint goal/description ### Returns `Sprint` object ``` -------------------------------- ### OAuth 2.0 Authentication with Static Access Token Source: https://github.com/mrrefactoring/jira.js/blob/master/README.md Set up the Jira.js client for OAuth 2.0 authentication using a static access token. This is a simplified setup for OAuth 2.0. ```typescript const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { oauth2: { accessToken: 'YOUR_ACCESS_TOKEN' }, }, }); ``` -------------------------------- ### Get Jira Project Details Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Fetch detailed information about a specific Jira project using its key or ID. This includes the project's name, lead, type, and key. ```typescript const project = await client.projects.getProject({ projectIdOrKey: 'PROJ' }); console.log(`Project: ${project.name}`); console.log(`Lead: ${project.lead.displayName}`); console.log(`Type: ${project.projectTypeKey}`); console.log(`Key: ${project.key}`); ``` -------------------------------- ### Get Comments for a Jira Issue Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieve all comments associated with a Jira issue. This example expands the issue to include changelog information. ```typescript const issue = await client.issues.getIssue({ issueIdOrKey: 'PROJ-123', expand: ['changelog'] }); issue.fields.comment.comments.forEach(comment => { console.log(`${comment.author.displayName}: ${comment.body}`); }); ``` -------------------------------- ### Search Issues with Field Selectors Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/parameters-and-models.md Example of searching for issues and selecting specific fields to be returned, reducing the payload size. Use the `fields` array for desired field names. ```typescript await client.issues.searchForIssuesUsingJql({ jql: 'status = Open', fields: ['key', 'summary', 'status', 'assignee'] }); ``` -------------------------------- ### Implement Tree-Shaking with Minimal Client Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Demonstrates how to create a minimal client by only importing necessary modules, such as `BaseClient`, `Issues`, and `Board`. This approach helps reduce bundle size by enabling tree-shaking. Requires `BaseClient`, `Issues`, and `Board` from `jira.js`. ```typescript import { BaseClient } from 'jira.js'; import { Issues } from 'jira.js/version3'; import { Board } from 'jira.js/agile'; class MinimalClient extends BaseClient { issues = new Issues(this); board = new Board(this); } const client = new MinimalClient(config); ``` -------------------------------- ### Create a Jira Project Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Create a new project in Jira with specified details including key, name, project type, lead account ID, and description. Ensure you have the necessary permissions. ```typescript const newProject = await client.projects.createProject({ key: 'NEW', name: 'New Project', projectTypeKey: 'software', leadAccountId: 'accountId123', description: 'A new software project' }); console.log(`Project created with ID: ${newProject.id}`); ``` -------------------------------- ### Initialize Jira Client Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/README.md Instantiate a client for Jira API v3. Requires host and authentication details. Supports basic authentication with email and API token. ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'TOKEN' } } }); ``` -------------------------------- ### createProject Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Creates a new project with specified key, name, type, and lead. Optional fields include description, avatar, and category. ```APIDOC ## createProject ### Description Creates a new project with specified key, name, type, and lead. Optional fields include description, avatar, and category. ### Method POST ### Endpoint /rest/api/3/project ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - Unique project key - **name** (string) - Required - Project name - **projectTypeKey** (string) - Required - Project type (software, business, service_desk) - **leadAccountId** (string) - Required - Account ID of project lead - **description** (string) - Optional - Project description - **avatarId** (number) - Optional - Avatar ID - **categoryId** (number) - Optional - Project category ### Response #### Success Response (201) - **id** (string) - Project ID - **key** (string) - Project key #### Response Example { "example": "{\"id\": \"10001\", \"key\": \"NEWPROJ\"}" } ``` -------------------------------- ### Edit Issue Example Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Example of updating an issue's summary and priority using the editIssue method. ```typescript await client.issues.editIssue({ issueIdOrKey: 'PROJ-123', fields: { summary: 'Updated title', priority: { name: 'High' } } }); ``` -------------------------------- ### Minimal Jira Client Configuration Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/configuration.md Initialize the Jira client with the essential host and basic authentication details. ```typescript const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'YOUR_API_TOKEN' } } }); ``` -------------------------------- ### OAuth 2.0 (3LO) Authentication Setup Source: https://github.com/mrrefactoring/jira.js/blob/master/CHANGELOG.md Configure `authentication.oauth2` for stateless OAuth 2.0 (3LO) flow. Provide `refreshToken`, `clientId`, and `clientSecret`. Optional parameters include `cloudId`, `siteUrl`, `expiresAt`, and `onTokenRefresh` for custom token refresh logic. ```javascript const jira = new Jira({ authentication: { oauth2: { refreshToken: 'YOUR_REFRESH_TOKEN', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', // Optional parameters // cloudId: 'YOUR_CLOUD_ID', // siteUrl: 'https://your-domain.atlassian.net', // expiresAt: 1678886400, // onTokenRefresh: (token) => { console.log('New access token:', token.accessToken); } } } }); ``` -------------------------------- ### BaseClient Constructor Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Initializes the BaseClient with configuration, validating it and setting up an Axios instance for HTTP communication. ```APIDOC ## BaseClient Constructor ### Description Initializes the BaseClient with configuration, validating it and setting up an Axios instance for HTTP communication. ### Method ```typescript constructor(config: Config) ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Initialize and Use Version3Client Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Initialize the Version3Client with your Jira domain and authentication details. Use it to access various API groups like projects, issues, and comments. ```typescript const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'TOKEN' } } }); // Access API groups const projects = await client.projects.searchProjects(); const issue = await client.issues.createIssue({ fields: { ... } }); const comments = await client.issueComments.getComments({ issueIdOrKey: 'KEY-1' }); ``` -------------------------------- ### Client Instantiation Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/README.md The jira.js library provides several client classes for interacting with different Jira APIs. The `Version3Client` is recommended for most use cases. A factory function `createClient()` is available for type-safe instantiation. ```APIDOC ## Client Classes and Instantiation ### BaseClient Base class for all clients with HTTP request/response handling. ### Version3Client Main client for REST API v3 (recommended). Provides access to 100+ API groups for issues, projects, users, workflows, etc. ### Version2Client Legacy REST API v2 support. ### AgileClient Jira Software/Agile API for sprint, board, backlog, and epic management. ### ServiceDeskClient Jira Service Desk API for customer requests and service desk operations. ### createClient() Factory function with type-safe overloads for creating client instances. ``` -------------------------------- ### getBoard Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Retrieves the configuration details for a specific board. ```APIDOC ## getBoard ### Description Gets board configuration. ### Method GET ### Endpoint /rest/agile/1.0/board/{boardId} ### Parameters #### Path Parameters - **boardId** (number) - Yes - Board ID ### Response #### Success Response (200) - **id** (number) - The ID of the board - **name** (string) - The name of the board - **type** (string) - The type of the board (e.g., 'scrum', 'kanban') ``` -------------------------------- ### Get Comments Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieves all comments for a specific issue. ```APIDOC ## Get Comments ### Description Retrieves all comments associated with a specific issue. ### Method GET (or similar, based on client method) ### Endpoint `/rest/api/2/issue/{issueIdOrKey}` (Hypothetical endpoint, comments are part of issue details) ### Parameters #### Path Parameters - **issueIdOrKey** (string) - Required - The ID or key of the issue. #### Query Parameters - **expand** (string) - Optional - Use 'changelog' to expand comment details. ### Response #### Success Response - **fields.comment.comments** (array) - An array of comment objects. - Each comment object contains: - **author** (object) - Information about the comment author, including **displayName**. - **body** (string) - The content of the comment. ``` -------------------------------- ### Get Worklogs Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieves all worklog entries for a specific issue. ```APIDOC ## Get Worklogs ### Description Retrieves all worklog entries associated with a specific issue. ### Method GET (or similar, based on client method) ### Endpoint `/rest/api/2/issue/{issueIdOrKey}` (Hypothetical endpoint, worklogs are part of issue details) ### Parameters #### Path Parameters - **issueIdOrKey** (string) - Required - The ID or key of the issue. #### Query Parameters - **expand** (string) - Optional - Use 'changelog' to expand worklog details. ### Response #### Success Response - **fields.worklog.worklogs** (array) - An array of worklog objects. - Each worklog object contains: - **author** (object) - Information about the worklog author, including **displayName**. - **timeSpent** (string) - The amount of time spent for this worklog entry. ``` -------------------------------- ### Get Sprint Issues Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieves all issues associated with a specific sprint. ```APIDOC ## Get Sprint Issues ### Description Retrieves all issues that are part of a specified sprint. ### Method GET (or similar, based on client method) ### Endpoint `/rest/agile/1.0/sprint/{sprintId}/issue` (Hypothetical endpoint based on client method) ### Parameters #### Path Parameters - **sprintId** (integer) - Required - The ID of the sprint. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of issues to return. ### Response #### Success Response - **issues** (array) - An array of issue objects. - Each issue object contains: - **key** (string) - The key of the issue (e.g., 'PROJ-123'). - **summary** (string) - The summary or title of the issue. ``` -------------------------------- ### Manage User Properties Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Sets and gets custom properties for a user. ```APIDOC ## Manage User Properties ### Description Allows setting and retrieving custom key-value properties associated with a user. ### Method PUT (for setting), GET (for getting) (based on client methods) ### Endpoint `/rest/api/2/user/{accountId}/properties/{propertyKey}` (Hypothetical endpoint based on client methods) ### Parameters #### Set User Property ##### Path Parameters - **accountId** (string) - Required - The account ID of the user. - **propertyKey** (string) - Required - The key for the custom property. ##### Request Body - **value** (any) - Required - The data to store for the property. #### Get User Property ##### Path Parameters - **accountId** (string) - Required - The account ID of the user. - **propertyKey** (string) - Required - The key for the custom property. ### Request Example (Set) ```typescript await client.userProperties.setUserProperty({ accountId: 'accountId123', propertyKey: 'myCustomKey', value: { custom: 'data' } }); ``` ### Request Example (Get) ```typescript const property = await client.userProperties.getUserProperty({ accountId: 'accountId123', propertyKey: 'myCustomKey' }); console.log(property.value); ``` ### Response (Success response details for getting property not fully specified, but it returns the stored value.) ``` -------------------------------- ### Get User Avatar Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieves the avatar URL for a specific user. ```APIDOC ## Get User Avatar ### Description Retrieves the avatar URL for a specific user, typically by first fetching user details. ### Method GET (or similar, based on client method) ### Endpoint `/rest/api/2/user` (Hypothetical endpoint based on client method, avatar URL is part of user object) ### Parameters #### Query Parameters - **accountId** (string) - Required - The account ID of the user. ### Response #### Success Response - **avatarUrls** (object) - An object containing URLs for different avatar sizes. - **48x48** (string) - The URL for the 48x48 pixel avatar. ### Response Example ```typescript const user = await client.users.getUser({ accountId: 'accountId123' }); const avatarUrl = user.avatarUrls['48x48']; console.log(`Avatar: ${avatarUrl}`); ``` ``` -------------------------------- ### Full Jira Client Configuration with All Options Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/configuration.md Configure the Jira client with all available options, including authentication, GDPR compliance, token validation settings, custom HTTP configurations, and middleware hooks. ```typescript const client = new Version3Client({ host: 'https://your-domain.atlassian.net', // Authentication authentication: { basic: { email: 'user@example.com', apiToken: 'ATATT...' } }, // GDPR Compliance strictGDPR: true, // Skip token validation noCheckAtlassianToken: false, // Custom HTTP settings baseRequestConfig: { timeout: 30000, headers: { 'User-Agent': 'MyApp/1.0', 'X-Custom-Header': 'value' }, maxRedirects: 5 }, // Middleware hooks middlewares: { onResponse: (response) => { console.log('Response received:', response); }, onError: (error) => { console.error('Error occurred:', error.message); } } }); ``` -------------------------------- ### Get Current User Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieves details of the currently authenticated user. ```APIDOC ## Get Current User ### Description Retrieves details of the currently authenticated user, including display name, email, and account ID. ### Method GET (or similar, based on client method) ### Endpoint `/rest/api/2/myself` (Hypothetical endpoint based on client method) ### Parameters None ### Response #### Success Response - **displayName** (string) - The display name of the user. - **emailAddress** (string) - The email address of the user. - **accountId** (string) - The account ID of the user. ### Response Example ```typescript const currentUser = await client.myself.getCurrentUser(); console.log(`Name: ${currentUser.displayName}`); console.log(`Email: ${currentUser.emailAddress}`); console.log(`Account ID: ${currentUser.accountId}`); ``` ``` -------------------------------- ### addWorklog Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Logs the time spent on an issue. Can include a start time and a comment. ```APIDOC ## addWorklog ### Description Logs time spent on an issue. ### Parameters #### Path Parameters - **parameters.issueIdOrKey** (string) - Yes - Issue ID or key #### Request Body - **parameters.timeSpent** (string) - Yes - Time format (e.g., '2h 30m') - **parameters.started** (string) - No - ISO timestamp when work started - **parameters.comment** (ADF) - No - Comment about the work ### Returns `Worklog` object with worklog details ``` -------------------------------- ### Configure Jira JWT Client Source: https://github.com/mrrefactoring/jira.js/blob/master/guides/jwt-authentication.md Instantiate the Version3Client with JWT authentication details. Ensure the `issuer` matches your app's key and the `secret` is the shared secret from the installation handshake. The `host` should be the tenant's site URL. ```typescript import { Version3Client } from 'jira.js'; // Look up the tenant you installed on: const { sharedSecret, baseUrl } = tenants.get(clientKey)! const client = new Version3Client({ host: baseUrl, // the tenant's site URL from the installed payload authentication: { jwt: { issuer: 'my-backend-integration', // the `key` from atlassian-connect.json secret: sharedSecret, // sharedSecret from the installed handshake expiryTimeSeconds: 180, // optional, defaults to 180 (3 minutes) }, }, }); ``` -------------------------------- ### Get User Details Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieves detailed information for a specific user by account ID. ```APIDOC ## Get User Details ### Description Retrieves detailed information for a specific user using their account ID. ### Method GET (or similar, based on client method) ### Endpoint `/rest/api/2/user` (Hypothetical endpoint based on client method) ### Parameters #### Query Parameters - **accountId** (string) - Required - The account ID of the user. ### Response #### Success Response - **displayName** (string) - The display name of the user. - **active** (boolean) - Indicates if the user is active. - **groups** (object) - Contains a list of groups the user belongs to. - **items** (array) - Array of group objects, each with a **name** (string). ### Response Example ```typescript const user = await client.users.getUser({ accountId: 'accountId123' }); console.log(`Name: ${user.displayName}`); console.log(`Active: ${user.active}`); console.log(`Groups: ${user.groups.items.map(g => g.name).join(', ')}`); ``` ``` -------------------------------- ### getAllBoards Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Lists all available boards within the Jira instance. Supports pagination for large numbers of boards. ```APIDOC ## getAllBoards ### Description Lists all boards. ### Method GET ### Endpoint /rest/agile/1.0/board ### Parameters #### Query Parameters - **maxResults** (number) - No - Results per page (default: 50) - **startAt** (number) - No - Pagination offset ### Response #### Success Response (200) - **values** (BoardDetails[]) - List of board configurations - **maxResults** (number) - Max results returned - **startAt** (number) - Pagination offset - **total** (number) - Total number of boards - **isLast** (boolean) - Indicates if this is the last page ``` -------------------------------- ### Create Jira Client Instance Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Instantiate a specific Jira client (e.g., Version3) using the `createClient` factory function. Ensure you provide the correct `ClientType` and configuration object, including host and authentication details. ```typescript import { createClient, ClientType } from 'jira.js'; const client = createClient(ClientType.Version3, { host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'TOKEN' } } }); ``` -------------------------------- ### getCurrentUser Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Gets the authenticated user's details. Returns a CurrentUser object with user information. ```APIDOC ## getCurrentUser ### Description Gets the authenticated user's details. Returns a CurrentUser object with user information. ### Method GET ### Endpoint /rest/api/3/user/me ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **accountId** (string) - User's account ID - **displayName** (string) - User's display name #### Response Example { "example": "{\"accountId\": \"5b10ac8d82e05b22cc7d4349\", \"displayName\": \"John Doe\"}" } ``` -------------------------------- ### updateWorklog Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Updates an existing worklog entry for an issue. Allows modification of time spent and start time. ```APIDOC ## updateWorklog ### Description Updates a worklog entry. ### Parameters #### Path Parameters - **parameters.issueIdOrKey** (string) - Yes - Issue ID or key - **parameters.id** (string) - Yes - Worklog ID #### Request Body - **parameters.timeSpent** (string) - No - Updated time spent - **parameters.started** (string) - No - Updated start time ``` -------------------------------- ### Initialize and Use AgileClient Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Initialize the AgileClient for Jira Agile (Software) API operations. Use it to manage sprints, boards, and backlogs. ```typescript const client = new AgileClient({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'TOKEN' } } }); // Get all boards const boards = await client.board.getAllBoards(); // Create a sprint const sprint = await client.sprint.createSprint({ name: 'Sprint 1', boardId: boards[0].id }); // Get backlog const backlog = await client.backlog.getBacklog({ boardId: boards[0].id }); ``` -------------------------------- ### Start a Jira Sprint Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Initiate a Jira sprint, changing its status to 'active'. This requires the sprint ID. ```typescript await client.sprint.startSprint({ sprintId: 1 }); console.log('Sprint started'); ``` -------------------------------- ### Configure Basic Authentication Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/configuration.md Sets up basic authentication using an Atlassian account email and API token. API tokens are generated in Atlassian account settings. ```typescript { host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'ATATT...' } } } ``` -------------------------------- ### Get Jira User Avatar Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieve the URL for a user's avatar. You can specify the desired size, such as '48x48'. ```typescript const user = await client.users.getUser({ accountId: 'accountId123' }); const avatarUrl = user.avatarUrls['48x48']; console.log(`Avatar: ${avatarUrl}`); ``` -------------------------------- ### Initialize and Use ServiceDeskClient Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Initialize the ServiceDeskClient for Jira Service Desk API. Use it for customer request management and service desk operations. ```typescript const client = new ServiceDeskClient({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'TOKEN' } } }); // Get all service desks const serviceDesks = await client.serviceDesk.getServiceDesks(); // Create a customer request const request = await client.request.createCustomerRequest({ serviceDeskId: serviceDesks[0].id, requestTypeId: '1', fieldValues: { ... } }); ``` -------------------------------- ### Get Transitions Method Signature Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Signature for the getTransitions method, which retrieves the available workflow transitions for a given issue. ```typescript async getTransitions( parameters: GetTransitions, callback?: Callback ): Promise ``` -------------------------------- ### Configure Middleware Logging for Client Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/README.md This snippet shows how to initialize the Version3Client with custom middleware for logging successful responses and errors. Use this to integrate logging directly into API interactions. ```typescript const client = new Version3Client({ host: 'https://domain.atlassian.net', authentication: { basic: { email, apiToken } }, middlewares: { onResponse: (data) => console.log('✓', data.id), onError: (err) => console.error('✗', err.status, err.message) } }); ``` -------------------------------- ### Initialize and Use Version2Client Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/core-clients.md Initialize the Version2Client for legacy Jira Cloud API v2. It mirrors Version3Client but uses v2 endpoints. ```typescript const client = new Version2Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'user@example.com', apiToken: 'TOKEN' } } }); const issue = await client.issues.getIssue({ issueIdOrKey: 'KEY-1' }); ``` -------------------------------- ### Get Current User Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Retrieves the details of the currently authenticated user. This is useful for displaying user-specific information or verifying authentication. ```typescript async getCurrentUser( callback?: Callback ): Promise ``` ```typescript const user = await client.users.getCurrentUser(); console.log(user.displayName); ``` -------------------------------- ### Get Current Jira User Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieve details for the currently authenticated user. This is useful for identifying the user performing actions. ```typescript const currentUser = await client.myself.getCurrentUser(); console.log(`Name: ${currentUser.displayName}`); console.log(`Email: ${currentUser.emailAddress}`); console.log(`Account ID: ${currentUser.accountId}`); ``` -------------------------------- ### Configuration Options Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/README.md Configure the jira.js client with options such as the Jira instance URL, GDPR compliance, authentication methods, and custom Axios configurations. ```APIDOC ## Client Configuration Options ### host Jira instance URL (required). ### strictGDPR Enables GDPR compliance mode. ### noCheckAtlassianToken Bypasses Atlassian token validation. ### baseRequestConfig Allows custom Axios request configuration. ### authentication Supports Basic authentication or OAuth 2.0. ### middlewares Provides hooks for request and response interception. ``` -------------------------------- ### Get All Boards Signature Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Signature for the getAllBoards method, used to list all available boards in Jira. Supports result count and pagination. ```typescript async getAllBoards>( parameters?: GetAllBoards, callback?: Callback ): Promise ``` -------------------------------- ### Get Sprint Issues Signature Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/api-methods.md Signature for the getSprintIssues method, used to retrieve all issues within a specified sprint. It supports pagination. ```typescript async getSprintIssues( parameters: GetSprintIssues, callback?: Callback ): Promise ``` -------------------------------- ### Get Jira Boards Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/usage-examples.md Retrieve a list of available Jira boards. This snippet allows specifying the maximum number of results to return. ```typescript const response = await client.board.getAllBoards({ maxResults: 50 }); response.values.forEach(board => { console.log(`${board.id}: ${board.name}`); }); ``` -------------------------------- ### JWT (Atlassian Connect) Authentication Source: https://github.com/mrrefactoring/jira.js/blob/master/docs/guide/authentication.md Intended for existing Atlassian Connect app installations. JWT authentication requires an issuer and a shared secret. ```typescript const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { jwt: { issuer: 'your-app-key', secret: sharedSecret, }, }, }); ``` -------------------------------- ### Importing Individual Types Source: https://github.com/mrrefactoring/jira.js/blob/master/_autodocs/types-and-callbacks.md Shows how to import specific types or client classes individually for more granular control over imports. ```typescript import { Version3Client } from 'jira.js'; import type { Issue } from 'jira.js/version3'; import type { Paginated } from 'jira.js'; ```