# CI HUB Integration SDK (/integration) Write an integration that translates your platform's API into CI HUB's handler format using `defineIntegration`. CI HUB calls your handlers; you return data in the expected shape. ``` Your Platform API ←→ Your Integration ←→ CI HUB Plugin(s) ``` Not a developer? The [Partner Journey](/integration/getting-started/partner-journey) covers what your customers get and each step to going live, without code. ## Quick start [#quick-start] Scaffold a new project: ```bash npm create @ci-hub/integration my-integration ``` ```bash pnpm create @ci-hub/integration my-integration ``` ```bash yarn create @ci-hub/integration my-integration ``` ```bash bun create @ci-hub/integration my-integration ``` ```bash cd my-integration npm run dev ``` ## Minimum handlers [#minimum-handlers] Five handlers are required for a working integration: | Handler | Purpose | | -------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `login` | Complete the login flow. Render the login screen, exchange credentials or OAuth code for tokens | | `checkToken` | Validate the stored token. Return an error to force re-login | | `refreshToken` | Called when `checkToken` fails. Refresh the access token, or return an error to force re-login | | `logout` | End the session. If your platform has no logout endpoint, return `sendStatus(200)`. CI HUB deletes stored tokens automatically | | `info` | Return basic metadata about the authenticated user and the remote system | Add `search` for read-only asset browsing. Add `createAsset` / `updateAsset` for write support. Every other handler is optional. ## Handler categories [#handler-categories] | Category | Handlers | | ----------------- | ----------------------------------------------------------------------------------------------------------------------- | | **Auth** | `login`, `logout`, `checkToken`, `refreshToken` | | **Assets** | `search`, `getFolder`, `createAsset`, `updateAsset`, `deleteAsset`, `download` | | **Folders** | `createFolder`, `renameFolder`, `deleteFolder`, `moveFolder` | | **Asset actions** | `lockAsset`, `renameAsset`, `moveAsset`, `getAssetVersions` | | **Tasks** | `searchTasks`, `getTask`, `getTaskAssets`, `addTaskComment`, `addTaskAsset`, `deleteTaskAsset`, `updateCustomTaskState` | | **Brand** | `getBrandConfig`, `getBrandAssets` | | **Advanced** | `doTransformation`, `additionalRendition`, `saveAssetRelations` | ## Next steps [#next-steps] # MCP Server Setup (/integration/mcp-setup) This puts the Integration SDK docs right inside your coding agent. Your agent can search the SDK, pull up any page as Markdown, and see the full outline, all over one endpoint. The point is that it works from the real docs instead of guessing from whatever it picked up in training. `https://developer.ci-hub.com/integration/mcp` It runs over Streamable HTTP, so any MCP-capable agent can use it. There's no sign-in and no API key. You paste the URL and you're done. Once it's connected your agent gets three tools: `search_docs`, `get_page`, and `list_sections`. ## How connecting works [#how-connecting-works] ### Add the server [#add-the-server] Every client is one of two kinds. Most take the URL directly. A few only speak the local (stdio) transport, and those need the `mcp-remote` bridge, which just needs Node.js on your machine. The section for your tool below has the exact file and snippet. ### Restart if you need to [#restart-if-you-need-to] Usually the tools show up right away. Some clients only read their MCP config at startup, so if nothing appears, restart the client or use its refresh action. ### Build [#build] Ask for what you want in plain language, something like "using the CI HUB Integration SDK, scaffold the login flow and auth handlers." The agent searches the docs, reads the pages it needs, and writes the code. *** ## Clients that take the URL directly [#clients-that-take-the-url-directly] These are the easy ones. Paste the endpoint and you're set. ### Claude Code [#claude-code] One command, nothing to edit: ```bash claude mcp add --transport http ci-hub-integration https://developer.ci-hub.com/integration/mcp ``` Run `claude mcp list` to check it's there. Claude Code also reads a project-level `.mcp.json`, so if you commit that file the whole team gets the server. ### Claude Desktop [#claude-desktop] Add it under Settings, Connectors, Add custom connector, with the URL above. Custom connectors work on every plan, and Free accounts can hold one at a time. If connectors are switched off for your workspace, the `mcp-remote` bridge does the same job: ```json title="claude_desktop_config.json" { "mcpServers": { "ci-hub-integration": { "command": "npx", "args": ["-y", "mcp-remote", "https://developer.ci-hub.com/integration/mcp"] } } } ``` ### Cursor [#cursor] Drop this in `~/.cursor/mcp.json` for every project, or `.cursor/mcp.json` for just this one: ```json title=".cursor/mcp.json" { "mcpServers": { "ci-hub-integration": { "url": "https://developer.ci-hub.com/integration/mcp" } } } ``` You'll see the server and its tools under Settings, MCP. A green dot means it connected. ### VS Code [#vs-code] Add this to `.vscode/mcp.json` in your workspace. Copilot's Agent mode reads it: ```json title=".vscode/mcp.json" { "servers": { "ci-hub-integration": { "type": "http", "url": "https://developer.ci-hub.com/integration/mcp" } } } ``` Open the Chat view in Agent mode and the CI HUB tools show up in the tools picker. ### GitHub Copilot [#github-copilot] In VS Code, Copilot uses the same `.vscode/mcp.json` shown above. For the Copilot coding agent on github.com, add the server under Repository, Settings, Copilot, MCP with the same `type: "http"` and URL. ### Windsurf [#windsurf] Add this to `~/.codeium/windsurf/mcp_config.json`: ```json title="mcp_config.json" { "mcpServers": { "ci-hub-integration": { "serverUrl": "https://developer.ci-hub.com/integration/mcp" } } } ``` Then hit Refresh in the Cascade MCP panel. Heads up: Windsurf uses `serverUrl`, not `url`. ### Cline, Roo Code, Kilo Code [#cline-roo-code-kilo-code] These VS Code extensions use the same shape. In the extension's MCP settings, add a remote server: ```json title="cline_mcp_settings.json" { "mcpServers": { "ci-hub-integration": { "type": "streamableHttp", "url": "https://developer.ci-hub.com/integration/mcp" } } } ``` ### OpenCode [#opencode] Add this to `opencode.json`: ```json title="opencode.json" { "mcp": { "ci-hub-integration": { "type": "remote", "url": "https://developer.ci-hub.com/integration/mcp", "enabled": true } } } ``` ### Conductor [#conductor] Conductor doesn't have its own MCP format. It uses whatever the underlying agent loads for that workspace, so you set it up for Claude Code (or Codex, or Cursor) and Conductor picks it up. For Claude Code, commit a `.mcp.json` at the repo root and every workspace inherits it: ```json title=".mcp.json" { "mcpServers": { "ci-hub-integration": { "type": "http", "url": "https://developer.ci-hub.com/integration/mcp" } } } ``` ### Zed [#zed] Register the endpoint as a context server in Zed's `settings.json`, or add it under Settings, AI, MCP Servers, Add Server, Add Remote Server: ```json title="settings.json" { "context_servers": { "ci-hub-integration": { "url": "https://developer.ci-hub.com/integration/mcp" } } } ``` Zed calls the key `context_servers`, not `mcpServers`. Leave the `Authorization` header out, since this endpoint needs no auth. *** ## Clients that need the bridge [#clients-that-need-the-bridge] A few clients only speak the local stdio transport. `mcp-remote` bridges your HTTP endpoint into a stdio process for them. It runs through `npx`, so there's no install, but it does need Node.js on the machine. ### Codex CLI [#codex-cli] Codex reads `~/.codex/config.toml`. Point a server at the bridge: ```toml title="~/.codex/config.toml" [mcp_servers.ci-hub-integration] command = "npx" args = ["-y", "mcp-remote", "https://developer.ci-hub.com/integration/mcp"] ``` ### Anything else [#anything-else] If your client only takes a `command` and `args` (stdio) server, the same bridge works everywhere. Just drop it into that client's config file: ```json title="mcp config" { "command": "npx", "args": ["-y", "mcp-remote", "https://developer.ci-hub.com/integration/mcp"] } ``` *** ## Check that it worked [#check-that-it-worked] Once the server is added, ask your tool something like: ```text Search the CI HUB Integration SDK docs for the login flow, then read that page. ``` It should call `search_docs` and then `get_page`. Asking it to "list the CI HUB Integration SDK sections" is a quick way to exercise `list_sections` too. ## If something's off [#if-somethings-off] There's no auth here, so problems are almost always about the config path or the connection, not credentials. * The tools don't show up. The client cached its config at startup. Restart it or use its refresh action. * It won't connect at all. Check the URL is exactly `https://developer.ci-hub.com/integration/mcp` with no trailing slash. You can't test it by opening it in a browser, that's a GET and the server only answers MCP requests over POST, so a healthy endpoint looks broken that way. Send a POST instead: ```bash curl -i -X POST https://developer.ci-hub.com/integration/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' ``` A `200` means it's up. A `404` means the URL or path is wrong. * A stdio client won't start the server. `mcp-remote` needs Node.js, so make sure `node` and `npx` are on your PATH. * You're getting the wrong docs. This endpoint only serves the Integration SDK. The Access SDK has [its own endpoint](/access/mcp-setup). # Asset Types (/integration/advanced/asset-types) The `type` field on an asset controls how CI HUB displays it and what actions are available. Three modes exist: default (file), `PRODUCT`, and `SNIPPET`. ## Default (file asset) [#default-file-asset] When `type` is omitted or `undefined`, CI HUB treats the asset as a regular file. It has a thumbnail, a downloadable file, and can be placed into creative documents. This is the most common type. Most DAM integrations return file assets exclusively. ## `PRODUCT` [#product] Entity/composite content that has no single downloadable file. The asset card shows metadata and nested child assets instead of a download button. Use `PRODUCT` when: * The item is a content object containing references to other files * The platform models structured content (product data, content items) alongside media files When `type: 'PRODUCT'`, set `thumbnailUrl` and `downloadUrl` to `undefined`. The asset's `values` array becomes the primary display. These are the metadata entries shown on the asset card. Child files appear as `values` entries with `type: 'ASSET'`. **Example** - some integrations uses `PRODUCT` for ContentItem and Virtual content types: ```ts if (item.content && ['ContentItem', 'Virtual'].includes(item.contentType)) { const content = item.content asset.thumbnailUrl = undefined asset.downloadUrl = undefined asset.type = 'PRODUCT' asset.values = await getValues(req, content, selectedSystem) } ``` The `getValues` function resolves linked content into an array of metadata entries. Linked files become `values` entries with `type: 'ASSET'` containing a mini-asset object (`id`, `name`, `thumbnailUrl`, `downloadUrl`, `conversions`, `capabilities`): ```ts const getValues = async (req, item, selectedSystem) => { let values = [] const contentIds = [] for (const [key, value] of Object.entries(item || {})) { if (value instanceof Array) { value.forEach(entry => { if (entry instanceof Object && entry._targetId) { contentIds.push(entry._targetId) } }) } else if (value instanceof Object && value._targetId) { contentIds.push(value._targetId) } else if (value['x-default']) { values.push({ id: key, name: key, type: 'TEXT', value: getXDefault(item[key]) }) } } if (contentIds.length > 0) { const contentValues = await getContentValues(req, selectedSystem, contentIds) values = values.concat(contentValues) } return values } ``` ## `SNIPPET` [#snippet] Non-file metadata-only content. The asset has no downloadable file and no thumbnail. CI HUB shows the asset name and metadata but disables download and placement actions. Use `SNIPPET` when the item is purely textual or structural: notes, text blocks, non-renderable entries. **Example** - some integrations marks OneNote items as `SNIPPET`: ```ts const asset = { id: item.id, name: item.name, fileSize: item.size, mimeType: (item.file && item.file.mimeType) || mime.lookup(item.name) || 'application/octet-stream', version: 1, type: (isOneNote && 'SNIPPET') || undefined, values: [], capabilities: { ...defaultAssetCapabilities, canUpdateAsset: !isOneNote, canRenameAsset: !isOneNote } } ``` ## Summary [#summary] | `type` | Has file | Thumbnail | Download | Placement | Primary display | | --------- | -------- | --------- | -------- | --------- | ----------------------------------------- | | *(empty)* | Yes | Yes | Yes | Yes | File preview | | `PRODUCT` | No | No | No | No | `values` array (metadata + nested assets) | | `SNIPPET` | No | No | No | No | Asset name + metadata | See [Metadata Values](/integration/advanced/metadata-values) for how to populate the `values` array on `PRODUCT` assets. # Brand Hub (/integration/advanced/brand-hub) Brand Hub is a CI HUB feature that lets users browse structured brand assets (logos, color palettes, fonts, and branded imagery) organized by category. It shows your platform's brand guidelines directly in creative tools. ## When to implement [#when-to-implement] Implement Brand Hub if your platform has: * A structured brand asset library with categorized content (logos, icons, color swatches) * Assets tagged or organized by brand category type If your platform is a general-purpose DAM without brand-specific structure, you can skip Brand Hub. It is optional. ## Enabling Brand Hub [#enabling-brand-hub] Set `supportsBrandHub: true` in your integration capabilities: ```ts defineIntegration({ capabilities: { category: CategoryEnum.DAM, supportsBrandHub: true, // ... }, // ... }) ``` This tells CI HUB to show the Brand Hub tab and call `getBrandConfig` and `getBrandAssets`. ## Brand asset tagging [#brand-asset-tagging] Brand Hub uses a tagging convention to categorize assets. Assets in your platform are tagged with two types of prefixes: | Prefix | Meaning | Example tag | | ---------- | ----------------------- | -------------------------------------- | | `CIH_BCT_` | Brand Category **Type** | `CIH_BCT_logo`, `CIH_BCT_color` | | `CIH_BCN_` | Brand Category **Name** | `CIH_BCN_Primary`, `CIH_BCN_Secondary` | Your platform stores these as regular tags on assets. When CI HUB requests brand assets, filter by these prefixes. ## `getBrandConfig` [#getbrandconfig] Returns the brand structure: what categories and sub-categories of brand assets exist. All parameters come from `requestData.query`: ```ts getBrandConfig: async (locals, requestData) => { try { const brandAssets = await callApi(locals, '/api/assets', { params: { tags: 'CIH_BCT_' }, }) const categories = extractBrandCategories(brandAssets) return send({ categories, }) } catch (error) { return sendError(`Error fetching brand config: ${error}`, 400) } }, ``` ## `getBrandAssets` [#getbrandassets] Returns assets for a specific brand category. The `folderId` and `categoryType` come from `requestData.query`: ```ts getBrandAssets: async (locals, requestData) => { const { folderId, categoryType } = requestData.query const size = Math.min(parseInt(requestData.query.size || '25', 10), 100) const more = parseInt(requestData.query.more || '1', 10) try { const results = await callApi(locals, '/api/assets', { params: { tags: `CIH_BCN_${folderId}`, size, page: more, }, }) return send({ categoryType, assets: results.items.map(mapToAsset), totalAssetsCount: results.total, more: results.hasNextPage ? more + 1 : undefined, }) } catch (error) { return sendError(`Error fetching brand assets: ${error}`, 400) } }, ``` ## Extracting brand categories from tags [#extracting-brand-categories-from-tags] A helper to derive the brand category tree from tagged assets: ```ts const extractBrandCategories = (assets: any[]) => { const typeSet = new Set() const nameMap = new Map>() assets.forEach(asset => { const tags: string[] = asset.tags ?? [] const type = tags.find(t => t.startsWith('CIH_BCT_'))?.replace('CIH_BCT_', '') const name = tags.find(t => t.startsWith('CIH_BCN_'))?.replace('CIH_BCN_', '') if (type) typeSet.add(type) if (type && name) { if (!nameMap.has(type)) nameMap.set(type, new Set()) nameMap.get(type)!.add(name) } }) return Array.from(typeSet).map(type => ({ id: type, name: type.charAt(0).toUpperCase() + type.slice(1), children: Array.from(nameMap.get(type) ?? []).map(name => ({ id: name, name: name, })), })) } ``` **Example** - DAM queries brand collections from a search facet and filters by `CIH_BCT_` prefix: ```ts getBrandConfig: async (locals, requestData) => { try { const result = { dataModelVersion: '1.0.0', provider: locals.provider, categories: [], errors: [] } const collectionTypes = (await callApi(locals, 'POST', '/api/search', null, { defaults: 'CIHubAssetSearchConfig', culture: defaultLanguage, skip: 0, take: 1, view: 'table', component: 819 })).facets.find(facet => facet.propertyName === 'CollectionType')?.children if (!collectionTypes) { return sendError('There are no Collections available') } const brandTypes = collectionTypes .map(collectionType => collectionType.value) .filter(item => item.startsWith(BRAND_TAG_PREFIXES.CATEGORY_TYPE.toLowerCase())) const brandCollections = await callApi(locals, 'POST', '/api/search', null, { defaults: 'CIHubAssetSearchConfig', culture: defaultLanguage, skip: 0, take: 1000, view: 'table', component: 819, filters: [{ name: 'properties.invariant.collectiontype', label: 'Collection type', type: 'InFilter', values: brandTypes, operator: 'AnyOf', group: 'properties.invariant.collectiontype', visible: true }] }) result.categories = brandCollections.items.map(folder => ({ folderId: `${folder.id}`, title: folder.properties.CollectionName, categoryType: folder.properties.CollectionType.identifier .replace(BRAND_TAG_PREFIXES.CATEGORY_TYPE, '') })).filter(collection => ['colors', 'images'].includes(collection.categoryType)) return send(result) } catch (error) { return sendError('Error getting folders and items:', error) } }, ``` ## Brand asset metadata [#brand-asset-metadata] Brand assets use the same `values` array as regular assets. See [Metadata Values](/integration/advanced/metadata-values) for grouping patterns and value types. Brand Hub is additive. Start without it and add it later once your core asset browsing works. It requires no changes to your existing handlers. # Capabilities Reference (/integration/advanced/capabilities-reference) Capabilities control what features CI HUB enables for your integration: which buttons appear, which actions are allowed, and how the plugin UI behaves. They exist at three levels: integration-wide, per-folder, and per-asset. ## Integration-level capabilities [#integration-level-capabilities] Returned once in the `info` handler inside `capabilities`. These are static for the entire connection session. | Key | Type | UI effect | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `category` | `'DAM'` \| `'Cloud Filehosting'` \| `'Stock Provider'` \| `'Service Provider'` \| `'Work Management'` \| `'PIM'` \| `'Automation'` \| `'Custom'` | Groups the integration in the connection list | | `assetUploadLimitInMB` | `number` | Maximum upload file size. CI HUB rejects files exceeding this before calling `createAsset` | | `enableCustomUpdateFilenames` | `boolean` | When `true`, allows updating an asset with a file that has a different filename | | `directAssetDownload` | `boolean` | When `true`, the client downloads assets directly from the provider URL without proxying through the server | | `directAssetUpload` | `boolean` | When `true`, files upload directly to the provider instead of through the server | | `supportsBrandHub` | `boolean` | When `true`, shows the Brand Hub tab and calls `getBrandConfig`/`getBrandAssets` | | `supportsNewLoginUrl` | `boolean` | Default `false`. When `true`, CI HUB uses unified login at `/api/v1/auth/login`; when `false`, `/api/v1/auth/login/:provider`. **Recommended:** set to `true`. See [Login Flow](/integration/building-an-integration/login-flow#supportsnewloginurl) | | `assetHashAlgorithm` | `'Md5'` \| `'Sha1'` \| `'Sha256Split4MB'` \| `'Sha256First16MB'` \| `'Sha256'` \| `'Sha512'` \| `'FileAttributes'` \| `'Crc32'` | Hash algorithm for file content checksums. See [Download Hashes](/integration/advanced/download-hashes) | | `assetSearch` | `object \| false` | Search configuration. `false` disables search entirely | | `description` | `Record` | Localized description shown in the connection list (`{ "en": "...", "de": "..." }`) | | `uploadWithRelinkOptionEnabled` | `boolean` | Shows the "Upload & Relink" option when placing a local file | | `requestHeaders` | `Record` | Additional HTTP headers for direct provider requests | | `assetComment` | `boolean` | When `true`, shows a comment field on the upload dialog | | `disableDuplicateCheck` | `boolean` | When `true`, allows uploading even when a file with the same name exists in the target folder | | `folderNavigationDisabled` | `boolean` | When `true`, hides folder navigation, so only search is available | | `tasking` | `boolean` | When `true`, enables the Tasks tab and task-related handlers | | `restrictSameNameUpdatesOnly` | `boolean` | When `true`, asset updates are only allowed when the replacement file has the exact same filename | | `maxMultipleAssetVersions` | `number` | Maximum assets in a single batch asset versions request | | `preferredNavigationMode` | `'search'` \| `'folder'` \| `'tasks'` | Default view when the user connects | | `directAccessHelper` | `string` | Embeds a browser-side upload function for direct provider uploads. See [Direct Access Helper](/integration/building-an-integration/direct-access-helper) | | `supportsAddAssetInSearch` | `boolean` | When `true`, the upload button appears in search results, not just in folders | ### `assetSearch` sub-options [#assetsearch-sub-options] When `assetSearch` is an object: | Key | Type | UI effect | | ------------------------ | ------------------------ | -------------------------------------------------------------------------------- | | `help` | `Record` | Localized placeholder text in the search bar | | `supportsParentId` | `boolean` | Search can be scoped to a specific folder | | `alwaysSearchInFolder` | `boolean` | All searches are scoped to the current folder. Requires `supportsParentId: true` | | `similarSearch` | `boolean` | Enables visual similarity search | | `externalUrl` | `string` | Link to external search syntax documentation, shown as a help icon | | `autoSearchQuery` | `string` | Default query that runs when search view opens | | `canParallelSearch` | `boolean` | Set to `false` to disable parallel search requests (default `true`) | | `supportsParallelRelink` | `boolean` | Enables multiple concurrent relink operations | | `parallelRelinkMax` | `number` | Max concurrent relink operations | | `searchByHash` | `string` | Hash algorithm name for hash-based asset search | ## Per-folder capabilities [#per-folder-capabilities] Returned on each folder object in `search` and `getFolder` responses. Control what actions are available in the folder context menu. | Key | Type | Default | UI effect | | ----------------- | --------- | ----------- | -------------------------------------------------------------------------------------------- | | `canDeleteFolder` | `boolean` | `false` | Shows "Delete folder" in context menu | | `canAddFolder` | `boolean` | `false` | Shows "Create folder" button | | `canAddAsset` | `boolean` | `false` | Shows upload button in that folder. In search results, enables uploading without a folder ID | | `canRenameFolder` | `boolean` | `undefined` | Shows "Rename folder" in context menu | The SDK provides `defaultFolderCapabilities` with all values set to `false`: ```ts import { defaultFolderCapabilities } from '@ci-hub/integration-sdk' const folder = { id: item.id, name: item.name, capabilities: { ...defaultFolderCapabilities, canAddAsset: item.permissions.includes('upload'), canAddFolder: item.permissions.includes('create'), }, } ``` ## Per-asset capabilities [#per-asset-capabilities] Returned on each asset object. Control which actions appear in the asset context menu. | Key | Type | Default | UI effect | | ------------------ | ---------- | ----------- | ------------------------------------------------------- | | `canDeleteAsset` | `boolean` | `false` | Shows "Delete" in context menu | | `canUpdateAsset` | `boolean` | `false` | Shows "Update" (replace file) in context menu | | `canLockAsset` | `boolean` | `false` | Shows "Lock" / "Unlock" toggle | | `canUnlockAsset` | `boolean` | `false` | Shows "Unlock" option | | `canRenameAsset` | `boolean` | `undefined` | Shows "Rename" in context menu | | `uploadExtensions` | `string[]` | `undefined` | Restricts which file extensions can be used for updates | The SDK provides `defaultAssetCapabilities` with all values set to `false`: ```ts import { defaultAssetCapabilities } from '@ci-hub/integration-sdk' const asset = { id: item.id, name: item.name, capabilities: { ...defaultAssetCapabilities, canUpdateAsset: true, canDeleteAsset: item.userCanDelete, }, } ``` ## Real patterns [#real-patterns] **Example** - some integrations checks per-item permissions from the API: ```ts capabilities: { ...defaultAssetCapabilities, canDeleteAsset: folderPermissions.canRemoveAsset, } ``` **Example** - some integrations disables update/rename for non-file assets: ```ts capabilities: { ...defaultAssetCapabilities, canUpdateAsset: !isOneNote, canRenameAsset: !isOneNote, } ``` See [Integration Info](/integration/reference/integration-info) for the full `info` response schema. # Custom Metadata (/integration/advanced/custom-metadata) Custom metadata lets you expose platform-specific fields that aren't part of the standard CI HUB asset schema: project codes, expiry dates, approval status, or any domain-specific attribute your platform tracks. `customMetadata` in the `info` response defines the **schema**: what fields exist and their types. The `values` array on each asset is the **runtime display** of metadata. These are two separate systems: `customMetadata` enables editing and filtering; `values` controls what appears in the asset detail panel. See [Metadata Values](/integration/advanced/metadata-values) for the `values` array reference. ## Overview [#overview] Custom metadata involves two things: **Declare the fields** in the `info` handler. This tells CI HUB what fields exist and their types **Return the values** on each asset, populated per-asset in `search`, `getFolder`, etc. ## Declaring fields in `info` [#declaring-fields-in-info] The `info` handler is called once when the user connects. Return `customMetadata` as a list of field definitions: ```ts info: async (locals) => { return send({ customMetadata: [ { id: 'projectCode', name: 'Project Code', type: 'TEXT', }, { id: 'expiryDate', name: 'Expiry Date', type: 'DATE', }, { id: 'approved', name: 'Approved', type: 'BOOLEAN', }, { id: 'region', name: 'Region', type: 'SELECT', options: [ { id: 'eu', name: 'Europe' }, { id: 'us', name: 'Americas' }, { id: 'apac', name: 'Asia Pacific' }, ], }, ], }) }, ``` ### Field types [#field-types] | Type | Description | | -------------- | ---------------------------------------------------- | | `TEXT` | Free-form string | | `DATE` | ISO date string (`2024-03-15`) | | `BOOLEAN` | `true` / `false` | | `SELECT` | One value from a predefined list, requires `options` | | `MULTI_SELECT` | Multiple values from a predefined list | ## Returning values on assets [#returning-values-on-assets] In `search`, `getFolder`, and other content handlers, include `customMetadata` on each asset: ```ts const mapToAsset = (item: any) => ({ id: item.id, name: item.title, // ...standard asset fields... customMetadata: { projectCode: item.project?.code ?? null, expiryDate: item.expiryDate ?? null, approved: item.status === 'APPROVED', region: item.regionId ?? null, }, }) ``` Return `null` for missing fields rather than omitting them. This keeps the field in the UI as empty rather than removing it. ## Editable metadata [#editable-metadata] To allow users to edit custom metadata fields in CI HUB, declare them in `updateAssetOptions` in the `info` response: ```ts info: async (locals) => { return send({ customMetadata: [ { id: 'projectCode', name: 'Project Code', type: 'TEXT' }, { id: 'expiryDate', name: 'Expiry Date', type: 'DATE' }, ], updateAssetOptions: { editableFields: ['projectCode', 'expiryDate'], }, }) }, ``` The `updateAsset` handler will then receive the changed values in `requestData.body.customMetadata`: ```ts updateAsset: async (locals, requestData) => { const { assetId } = requestData.params const { customMetadata } = requestData.body try { if (customMetadata) { await callApi(locals, `/api/assets/${assetId}/metadata`, { method: 'PATCH', data: { projectCode: customMetadata.projectCode, expiryDate: customMetadata.expiryDate, }, }) } return send({ id: assetId }) } catch (error) { return sendError(`Error updating metadata: ${error}`, 400) } }, ``` ## Localized (multi-language) metadata [#localized-multi-language-metadata] If your platform stores metadata in multiple languages, return them as an object keyed by locale code: ```ts const mapToAsset = (item: any) => ({ id: item.id, name: item.title, customMetadata: { description: { en: item.descriptions?.en ?? null, de: item.descriptions?.de ?? null, fr: item.descriptions?.fr ?? null, }, keywords: { en: item.keywords?.en?.join(', ') ?? null, de: item.keywords?.de?.join(', ') ?? null, }, }, }) ``` You must also declare the available locales in the `info` response so CI HUB shows the locale switcher: ```ts info: async (locals) => { return send({ customMetadata: [ { id: 'description', name: 'Description', type: 'TEXT' }, { id: 'keywords', name: 'Keywords', type: 'TEXT' }, ], dataLocales: ['en', 'de', 'fr'], }) }, ``` ## Custom metadata as search filters [#custom-metadata-as-search-filters] You can also expose custom metadata fields as searchable filters. See [Filters →](/integration/building-an-integration/filters) for how to read active filter values and pass them to your API. A typical pattern is to list the metadata field as both a `customMetadata` declaration (for display) and as a filter option (for searching): ```ts info: async (locals) => { const regions = await callApi(locals, '/api/regions') return send({ customMetadata: [ { id: 'region', name: 'Region', type: 'SELECT', options: regions.map((r: any) => ({ id: r.id, name: r.label })), }, ], searchConfigs: [ { id: 'region', name: 'Region', type: 'SELECT', options: regions.map((r: any) => ({ id: r.id, name: r.label })), }, ], }) }, ``` # Download Hashes (/integration/advanced/download-hashes) Download hashes let CI HUB detect whether a placed asset has changed since it was last downloaded. When a user opens a document, CI HUB compares the stored hash against the current hash from the integration. If they differ, the asset is flagged as updated. ## Hash fields [#hash-fields] Return one hash field per asset. The field name determines the algorithm: | Field | Algorithm | Description | | ----------------------------- | -------------------- | ----------------------------------------------------------------- | | `downloadHashMd5` | MD5 | Standard MD5 hash of the full file | | `downloadHashSha1` | SHA-1 | SHA-1 hash of the full file | | `downloadHashSha256` | SHA-256 | SHA-256 hash of the full file | | `downloadHashSha512` | SHA-512 | SHA-512 hash of the full file | | `downloadHashCrc32` | CRC-32 | CRC-32 checksum of the full file | | `downloadHashSha256Split4MB` | SHA-256 (split) | SHA-256 hashes of 4MB chunks, concatenated | | `downloadHashSha256First16MB` | SHA-256 (first 16MB) | SHA-256 of only the first 16MB of the file | | `downloadHashFileAttributes` | File attributes | JSON string of `{ fileSize, modified }`, not a cryptographic hash | ## `assetHashAlgorithm` in capabilities [#assethashalgorithm-in-capabilities] Declare which algorithm your integration uses in the `info` response: ```ts capabilities: { category: 'DAM', assetHashAlgorithm: 'Sha256', } ``` Valid values: `'Md5'`, `'Sha1'`, `'Sha256Split4MB'`, `'Sha256First16MB'`, `'Sha256'`, `'Sha512'`, `'FileAttributes'`, `'Crc32'` This tells CI HUB which hash to compute locally when comparing placed assets. It must match the hash field you return on assets. ## Returning hashes on assets [#returning-hashes-on-assets] Add the hash field directly on the asset object: ```ts const asset = { id: item.id, name: item.name, downloadUrl: item.downloadUrl, downloadHashSha256: item.sha256Checksum, } ``` ## `downloadHashFileAttributes` [#downloadhashfileattributes] A non-cryptographic approach. Instead of hashing file content, store the file size and modification timestamp as a JSON string. Useful when your platform doesn't expose content hashes but does track file metadata: ```ts const asset = { id: item.id, name: item.name, downloadHashFileAttributes: JSON.stringify({ fileSize: item.size, modified: new Date(item.lastModifiedDateTime).getTime(), }), } ``` CI HUB compares these attributes to detect changes. Less reliable than cryptographic hashes (a file could be modified without changing size) but requires no server-side hashing. Do not use this algorithm unless your platform doesn't expose content hashes. ## `searchByHash` [#searchbyhash] If your platform's API supports looking up assets by their content hash, set `searchByHash` in the `assetSearch` configuration to the algorithm name: ```ts capabilities: { assetSearch: { searchByHash: 'Sha256', }, assetHashAlgorithm: 'Sha256', } ``` CI HUB uses this for relink operations. When a placed asset's link is broken, the client can search by hash to find the matching asset on the remote system. # Metadata Values (/integration/advanced/metadata-values) The `values` array on an asset displays metadata in the CI HUB asset detail panel. Each entry is a key-value row. Grouping, nesting, and rich content are controlled by conventions in the `name` and `type` fields. ## Value structure [#value-structure] Each entry in the `values` array: ```ts { id: string, // unique identifier name: string, // display label type: 'TEXT' | 'ASSET' | 'DRAFT_JS' | 'DATE' | 'DATETIME' | 'TIME', value: string | number | object // depends on type } ``` ## Value types [#value-types] | Type | `value` field | UI display | | ---------- | ------------------ | -------------------------------------------------------- | | `TEXT` | `string \| number` | Plain text row | | `DATE` | `string` | Formatted date | | `DATETIME` | `string` | Formatted date + time | | `TIME` | `string` | Formatted time | | `DRAFT_JS` | `string` | Rich text (Draft.js serialized content) | | `ASSET` | mini-asset object | Embedded asset with thumbnail, download, and conversions | ### `TEXT`: the most common type [#text-the-most-common-type] Most metadata entries use `TEXT`. The `value` can be a string or number: ```ts values: [ { id: 'description', name: 'Description', type: 'TEXT', value: item.description }, { id: 'pageCount', name: 'Page Count', type: 'TEXT', value: item.pageCount }, { id: 'duration', name: 'Duration', type: 'TEXT', value: item.duration }, ] ``` ### `ASSET`: nested mini-assets [#asset-nested-mini-assets] Used on `PRODUCT`-type assets to embed downloadable files inside metadata. The `value` is a mini-asset object: ```ts { id: 'linkedFile', name: 'Linked File', type: 'ASSET', value: { id: file.id, name: file.name, version: 1, mimeType: file.mimeType, thumbnailUrl: file.thumbnailUrl, downloadUrl: file.downloadUrl, conversions: file.conversions, capabilities: defaultAssetCapabilities, } } ``` This renders the mini-asset with its own thumbnail, download button, and conversion options inside the parent asset's detail panel. ## Grouping with `\u2003` (em space) [#grouping-with-u2003-em-space] CI HUB uses the em space character (`\u2003`) as an indent prefix in the `name` field to create visual grouping. The pattern: 1. **Header row**: no `\u2003` prefix, empty or no `value`. Acts as a group label 2. **Child rows**: `name` prefixed with `\u2003`. Displayed indented under the header ```ts // Header row (no value, no indent) { id: 'copyright', name: 'copyright', type: 'TEXT' }, // Child rows (indented with \u2003) { id: 'notice', name: '\u2003Notice', value: item.copyright.notice, type: 'TEXT' }, { id: 'copyrightStatus', name: '\u2003Status', value: item.copyright.status, type: 'TEXT' }, ``` This renders as: ``` copyright Notice: MIT License Status: Active ``` ### Filtering out empty groups [#filtering-out-empty-groups] Header rows with no children are noise. Filter them out: ```ts const values = [ ...parseCustomMetadata(item.customMetadata || []), ...item.copyright.status || item.copyright.notice ? [{ id: 'copyright', name: 'copyright', type: 'TEXT' }, { id: 'notice', name: '\u2003Notice', value: item.copyright.notice, type: 'TEXT' }, { id: 'copyrightStatus', name: '\u2003Status', value: item.copyright.status, type: 'TEXT' }] : [] ].filter(metadate => metadate.value || ['copyright'].includes(metadate.id)) ``` ## Real integration patterns [#real-integration-patterns] ### Example - `createValue` helper [#example---createvalue-helper] some integrations uses a `createValue` helper that conditionally adds the `\u2003` prefix: ```ts const createValue = (id, name, value = '', indent) => ({ id, name: `${indent ? '\u2003' : ''}${name}`, type: 'TEXT', value, }) ``` Metadata templates produce grouped values: a header row for the template name, then indented child rows for each field: ```ts if (metadata && (showHidden || !templateHidden)) { const prefix = `${scope}#${templateKey}` acc.push(createValue(prefix, templateName)) acc.push(...(template.fields || []). filter(field => field && (showHidden || !field.hidden) && isValue(metadata[field.key])). map(field => createValue( `${prefix}#${field.key}`, field.displayName, getValue(metadata[field.key], field.type), true ))) } ``` ### Example - grouped custom fields [#example---grouped-custom-fields] some integrations groups custom fields by field set. A new header is added when the field set name changes: ```ts if (useGroupAndSort && fieldSetName && (!lastFieldSetName || fieldSetName !== lastFieldSetName)) { lastFieldSetName = fieldSetName customFieldsToAdd.push({ id: `group-${fieldSetId}`, name: fieldSetName, type: 'TEXT' }) } customFieldsToAdd.push({ id: fieldId, name: `${fieldSetName ? '\u2003' : ''}${getCustomFieldName(customFieldsMapping, fieldId, uiLocale)}`, value, type: 'TEXT', }) ``` ### Example - layer-based metadata [#example---layer-based-metadata] some integrations iterates metadata layers and nests properties under each layer name: ```ts Object.keys(item.metadata). filter(entry => !['xmpMetadata', 'exifMetadata', 'autoTagging'].includes(entry)). forEach(metadataId => { let groupHeaderAdded = false Object.entries(item.metadata[metadataId]).forEach(([key, value]) => { if (key !== '_displayValues' && isValidPropertyValue(value)) { if (!groupHeaderAdded) { values.push({ id: `${metadataId}`, name: `${getLayerName(layerSchemaData, metadataId)}`, type: 'TEXT', value: `` }) groupHeaderAdded = true } values.push({ id: `${metadataId}:${key}`, name: `\u2003${getLayerPropertyName(layerSchemaData, metadataId, key)}`, type: 'TEXT', value: getPropertyValueAsString(value) }) } }) }) ``` ### Example - multi-level nesting [#example---multi-level-nesting] some integrations nest up to three levels deep using multiple `\u2003` characters: ```ts // Level 0: item name (header) values.push({ id: item.reference, name: item.name, type: 'TEXT', value: '' }) // Level 1: property key Object.entries(item || {}).forEach(([key, value]) => { if (Array.isArray(value)) { values.push({ id: `item.reference#${key}`, name: `\u2003${key}`, type: 'TEXT', value: '' }) // Level 2: array entry name value?.forEach?.(option => { values.push({ id: `item.reference#${key}#type_name`, name: `\u2003\u2003${option.type_name}`, type: 'TEXT', value: '' }) // Level 3: nested properties Object.entries(option || {}).forEach(([innerKey, innerValue]) => { if (!['type_name'].includes(innerKey) && innerKey.indexOf('reference') === -1) { values.push({ id: `item.reference#${key}#${innerKey}`, name: `\u2003\u2003\u2003${innerKey}`, type: 'TEXT', value: innerValue }) } }) }) } else { values.push({ id: `item.reference#${key}`, name: `\u2003${key}`, type: 'TEXT', value }) } }) ``` This renders as: ``` Brochure A4 options Lamination Matte price: 0.05 EUR weight: 2g Binding Stapled price: 0.02 EUR quantity 500 ``` ## Best practices for IDs [#best-practices-for-ids] * Use unique, stable IDs. The `id` field drives change detection and filtering * Prefix group IDs to avoid collisions: `group-${setId}`, `${scope}#${templateKey}` * For nested values, use compound IDs: `${parentId}#${childKey}` * Keep IDs valid as HTML id attributes: no spaces, no special characters beyond `#`, `-`, `_` See [Search Schema](/integration/schemas/assets/search) | [Custom Metadata](/integration/advanced/custom-metadata) # Tips and Tricks (/integration/advanced/tips-and-tricks) Patterns and pitfalls collected from real integration implementations. **Validate all config keys at startup.** Use the `configKeys.filter(key => !config.has(key))` pattern at module level, before `defineIntegration`. A misconfigured deployment should fail loudly at startup, not silently on the first user request. **Centralize type configs in `integration-types.ts`.** Pass the same type alias to `defineIntegration`, auth helpers, and DAH separately. The SDK does not infer types across files. See [Typed Integrations](/integration/advanced/typed-integrations). **Use `config.has()` before `config.get()` for optional keys.** `config.get()` throws if the key doesn't exist. For optional features, always guard with `has()`: ```ts const uploadLimit = config.has('myIntegration.uploadLimitMB') ? config.get('myIntegration.uploadLimitMB') : 500 ``` **Read from the correct source.** Each handler has typed `requestData`. The SDK knows whether a field comes from `query`, `body`, or `params`. Read from the source that matches the handler's contract. ```ts search: async (locals, requestData) => { const query = requestData.query.query || '' const page = parseInt(requestData.query.more || '1', 10) // ... }, deleteAsset: async (locals, requestData) => { const { assetId } = requestData.params // ... }, ``` The only exception is `createAsset`/`updateAsset` where metadata may arrive in `query` when the body carries a binary buffer. **Always run user-provided server URLs through `ensureHttps()`.** Users copy URLs from browser address bars or documentation, so they might include `http://`, a trailing slash, or a path. Normalize before storing: ```ts import { ensureHttps } from '@ci-hub/integration-sdk' const normalizedUrl = ensureHttps(userProvidedUrl, true, true) ``` **Strip trailing slashes from your base URL** to avoid double-slash issues when building paths: ```ts const base = resourceEndpoint.replace(/\/$/, '') const url = `${base}/api/assets/${assetId}` ``` **`checkToken` is on the critical path of every request.** It's called before every handler. Use the fastest, cheapest endpoint your API has, such as a profile or status endpoint that returns a small payload. Avoid fetching collections or asset lists here. **In `refreshToken`, `locals.authPayload` is the refresh token.** The SDK swaps the access and refresh tokens before calling the handler. Don't try to swap them yourself. **Keep `adapterData` small.** It's encrypted and stored per session, but it's not a general-purpose cache. Store only what you need on every request: the resource endpoint URL, org/tenant ID, and any similar session-identifying data. **Set `supportsNewLoginUrl: true` (recommended; SDK default is `false`).** Whitelist `locals.endpointUrl` at the DAM for OAuth `redirect_uri`, and allow CI HUB panel origins for CORS during login. See [Login Flow](/integration/building-an-integration/login-flow#supportsnewloginurl) and [Direct Access Helper CORS](/integration/building-an-integration/direct-access-helper#cors). **Handle `canceled` and auth errors at the top of `login`.** Before any rendering or redirect logic, check for these conditions and return early. The recommended order is: ```ts login: async (locals, requestData) => { const authError = requestData.query.error_description || requestData.query.error if (authError) return sendAccessToken(authError) if (requestData.body.canceled || requestData.query.canceled) { return sendAccessToken() } // ... phase logic follows }, ``` **`state` is the correlation key.** It ties all redirect hops together. Mint it once with `getStateCodeAsync()`, pass it through every redirect, and use `setStateAdapterDataAsync`/`getStateAdapterDataAsync` to carry data between phases. **State is server-side only.** Use `setStateAdapterDataAsync` to carry tokens and credentials between redirect phases. Never put sensitive data in the URL. **Cap `size` at a safe maximum.** Clients can request arbitrarily large pages, so protect your API: ```ts const size = Math.min(parseInt(requestData.query.size || '25', 10), 100) ``` **Use `undefined` for `more` on the last page, not `null`.** Returning `null` signals to CI HUB that more results exist and shows the "Load more" button. Use `undefined` to end pagination: ```ts more: data.hasNextPage ? page + 1 : undefined // ✅ more: data.hasNextPage ? page + 1 : null // ❌ shows "Load more" on last page ``` **Wrap each item in list-mapping code inside `try/catch`.** One malformed asset from your API shouldn't fail the entire search response: ```ts const assets = rawItems.map(item => { try { return mapToAsset(item) } catch { return undefined } }).filter((a): a is MappedAsset => a !== undefined) ``` **CI HUB expects flat arrays** for assets and folders. Flatten nested structures inside your integration. Don't pass nested objects. **Include the original error in every `sendError` message.** It appears in the CI HUB error UI and gives users enough context to file a useful bug report: ```ts } catch (error) { return sendError(`Error uploading asset: ${error}`, 400) } ``` **Return `sendError` from all `catch` blocks. Never `throw`.** If a handler throws, the request ends in an unhandled error. Your `catch` block is the last line of defense. **Set `maxContentLength: Infinity` and `maxBodyLength: Infinity` on upload requests.** Axios has conservative default limits that will reject large files: ```ts await axios.put(uploadUrl, buffer, { headers: { 'Content-Type': mimeType }, maxContentLength: Infinity, maxBodyLength: Infinity, }) ``` **Request a fresh pre-signed URL on every upload attempt.** Pre-signed URLs expire (typically in minutes). Never cache them across requests. **Generate download URLs on demand.** If your download URLs expire, return a fresh one from the `download` handler rather than storing it at search time. The user might open the download hours after the search, by which point stored URLs will have expired. **Use clear sentinels to distinguish phases.** Test for the presence of `state`, `code`, and org/tenant IDs in that logical order. Make each `if` block mutually exclusive: ```ts if (authError) { /* surface error */ } else if (canceled) { /* abort */ } else if (!state && !serverUrl) { /* Phase 1 */ } else if (serverUrl && !state) { /* Phase 2 */ } else if (code && state && !orgId) { /* Phase 3 */ } else if (orgId && state) { /* Phase 4 */ } else { return sendAccessToken('Unexpected login state. Please try again.') } ``` # Typed Integrations (/integration/advanced/typed-integrations) This guide explains how to use the generic type parameter on `defineIntegration` so your integration handlers get accurate TypeScript types for `locals.adapterData`, per-handler `requestData`, and optional per-handler `locals` fields. ## Overview [#overview] When you call `defineIntegration`, you can pass a **type configuration** as the generic argument: ```typescript import { defineIntegration } from '@ci-hub/integration-sdk' defineIntegration<{ adapterData: { brandId: string } login: { requestData: { query: { brandId?: string; code?: string } body: { brandId?: string } } } }>({ name: 'My Integration', version: '1.0.0', // ... handlers }) ``` Inside each handler, TypeScript uses that configuration to type: * **`locals`**, including `locals.adapterData` merged with your custom fields * **`requestData`**: `query`, `body`, and `params` merged with the SDK's base types for that handler (e.g. `LoginRequest` for `login`) This is **compile-time only**. Runtime behavior (headers, JSON parsing, Zod validation) is unchanged. You are responsible for actually setting `adapterData` and request fields your types describe. The same config type can be passed manually to **`sendAccessToken`**, **`getStateAdapterDataAsync`**, and **`setStateAdapterDataAsync`** (see [Auth helpers](#auth-helpers)). DAH uses a separate [`DahTypeConfig`](#direct-access-helper-dah) for `adapterData` and `data`. Generic types are optional but helpful. They replace manual `as` casts with accurate compile-time checking. You can add them at any point during development. ## Type configuration shape [#type-configuration-shape] The generic argument must match `IntegrationTypeConfig`: | Key | Purpose | | --------------------------------- | ---------------------------------------------------------------------------------------- | | `adapterData` | Fields stored on the connection and passed in `locals.adapterData` for **every** handler | | `login`, `search`, `getFolder`, … | Per-handler extensions (see [Supported handler keys](#supported-handler-keys)) | Each handler key is optional and may include: ```typescript { locals?: Record // extra fields on locals for this handler only oauthState?: Record // login OAuth temp state (see Auth helpers) requestData?: { query?: Record // merged into the handler's default query type body?: Record // merged into the handler's default body type params?: Record // merged into the handler's default params type } } ``` Only use **handler names** and `adapterData` at the top level. Do not put `name`, `version`, or `capabilities` in the generic config. Those belong in the implementation object. ### How merging works [#how-merging-works] * **`adapterData`**: `locals.adapterData` becomes the SDK base (`resourceEndpoint` plus loose keys) **intersected** with your declared fields. * **`requestData`**: Each part you declare is **intersected** with the SDK default for that handler. For example, `login` always includes base `LoginRequest` fields (`endpointUrl`, optional `state`, etc.); your `query` / `body` extensions add fields like `brandId` or `code`. * **`locals` (per handler)**: If you set `login.locals`, only the `login` handler's `locals` parameter includes those extra fields (plus global `adapterData`). Other handlers use the global shape unless you configure them too. Invalid handler names in the generic (typos like `loginn`) produce a TypeScript error. ## Supported handler keys [#supported-handler-keys] You may configure any of these keys under the generic (same names as on `defineIntegration`): `info`, `login`, `logout`, `checkToken`, `refreshToken`, `search`, `getFolder`, `createFolder`, `createAsset`, `updateAsset`, `lockAsset`, `renameAsset`, `moveAsset`, `deleteAsset`, `renameFolder`, `moveFolder`, `deleteFolder`, `getAssetVersions`, `download`, `getBrandConfig`, `getBrandAssets`, `searchTasks`, `getTask`, `getTaskAssets`, `addTaskComment`, `addTaskAsset`, `updateCustomTaskState`, `deleteTaskAsset`, `addAssetToTask`, `updateTaskState` Handlers that only receive `locals` (no `requestData`): `info`, `checkToken`, `refreshToken`. ## Custom methods [#custom-methods] Any key on `defineIntegration` that is **not** in the standard handler list above is treated as a custom method, a server-side function callable via `/api/v1/system/providerInternal/:methodName`. Custom method keys use `CustomMethodTypeExtension` in the generic config, which supports `locals`, `requestData`, and `returnType`: ```typescript title="src/integration-types.ts" { locals?: Record requestData?: { query?: Record body?: Record params?: Record } returnType?: Record } ``` Example with a `sign` method: ```typescript title="src/integration-types.ts" type MyIntegrationConfig = { adapterData: { secretKey: string } sign: { // [!code ++:6] requestData: { body: { uploadParams: Record } } returnType: { signature: string; timestamp: number } } } ``` ```typescript title="src/index.ts" defineIntegration({ sign: async (locals, requestData) => { locals.adapterData.secretKey // string requestData.body.uploadParams // Record return send({ signature: '...', timestamp: Date.now() }) } }) ``` `returnType` is informational. It types the argument passed to `send()` inside the handler. Custom methods are not validated against Zod response schemas at runtime. See [Custom Methods](/integration/building-an-integration/custom-methods) for the full guide including how to call custom methods from the DAH. ## Examples [#examples] ### Global `adapterData` only [#global-adapterdata-only] Use this when every handler reads the same connection-specific data (brand ID, tenant URL, etc.): ```typescript title="src/index.ts" defineIntegration<{ adapterData: { brandId: string resourceEndpoint: string } }>({ name: 'My DAM', version: '1.0.0', info: async locals => { const { brandId } = locals.adapterData // string // ... }, search: async (locals, requestData) => { const { brandId } = locals.adapterData // string, same in all handlers // requestData uses default SearchQuery / SearchBody types } }) ``` Set `adapterData` when the user connects, typically in `login` or `refreshToken`: ```typescript title="src/index.ts" return sendAccessToken(null, accessToken, expiresIn, refreshToken, undefined, { resourceEndpoint: serverUrl, brandId: selectedBrandId }) ``` ### Per-handler `requestData` (login) [#per-handler-requestdata-login] OAuth and custom login flows often need extra query/body fields beyond `LoginRequest`: ```typescript title="src/index.ts" defineIntegration<{ adapterData: { brandId: string; serverUrl?: string } login: { requestData: { query: { brandId?: string serverUrl?: string code?: string error?: string error_description?: string canceled?: boolean state?: string } body: { brandId?: string serverUrl?: string canceled?: boolean state?: string } } } }>({ login: async (locals, requestData) => { const code = requestData.query.code const brandId = requestData.body.brandId || requestData.query.brandId || '' const serverUrl = requestData.body.serverUrl || requestData.query.serverUrl || '' // endpointUrl still required on base LoginRequest where applicable } }) ``` ### Per-handler `locals` [#per-handler-locals] Rarely needed if `adapterData` covers your case. Use when a single handler needs extra `locals` fields that other handlers should not see in the type system: ```typescript title="src/index.ts" defineIntegration<{ adapterData: { brandId: string } search: { locals: { debugSessionId?: string } } }>({ search: async locals => { locals.adapterData.brandId // string locals.debugSessionId // string | undefined, only on search } }) ``` You must populate any custom `locals` fields yourself if you rely on them; the SDK only supplies the standard `Locals` shape from headers. ### Reusing a config type [#reusing-a-config-type] Define a shared type alias and pass it to every API that accepts the same config: ```typescript title="src/integration-types.ts" export type MyIntegrationConfig = { adapterData: { brandId: string } login: { oauthState: { serverUrl?: string; verifier?: string } requestData: { query: { code?: string } body: { brandId?: string } } } } ``` ```typescript title="src/index.ts" defineIntegration({ /* ... */ }) ``` ## Auth helpers [#auth-helpers] Pass the **same** `MyIntegrationConfig` type to: | Function | Typed usage | | ------------------------------------------------ | ----------------------------------------------- | | `sendAccessToken(..., adapterData?)` | Last argument: `AdapterDataFromConfig` | | `getStateAdapterDataAsync(state)` | Returns `OAuthStateFromConfig \| null` | | `setStateAdapterDataAsync(state, data)` | `data`: `OAuthStateFromConfig` | `OAuthStateFromConfig` is read from **`login.oauthState`** (temporary OAuth flow data, not connection `adapterData`). ```typescript title="src/index.ts" const stored = await getStateAdapterDataAsync(state) await setStateAdapterDataAsync(state, { serverUrl, verifier: '...' }) return sendAccessToken(null, token, expiresIn, refresh, undefined, { resourceEndpoint: serverUrl, brandId: '...' }) ``` ## Direct Access Helper (DAH) [#direct-access-helper-dah] DAH runs in a **separate bundled file**. Use `DahTypeConfig` and pass it to `DahFunction` / `DirectAccessHelper`: ```typescript title="src/dah.ts" export type MyDahConfig = { adapterData: { resourceEndpoint: string } } const upload: DahFunction = async (axios, _p, _s, data, onProgress, adapterData, _t, helpers) => { adapterData.resourceEndpoint data.file helpers.getAdapterData().resourceEndpoint return { id: '...', name: 'file' } } export default { createAsset: upload } satisfies DirectAccessHelper ``` Share `adapterData` field types via the same `integration-types.ts` file as your integration config. ## Exported types [#exported-types] Import these from `@ci-hub/integration-sdk` when building helpers or wrapping handlers: | Type | Description | | ----------------------------------- | ---------------------------------------------------------------------- | | `IntegrationTypeConfig` | Shape of the generic argument | | `IntegrationDefinition` | Full integration object type for a given config | | `Integration` | Alias of `IntegrationDefinition` (default `TConfig` is empty) | | `IntegrationLocals` | `Locals` with typed `adapterData` | | `HandlerLocals` | Locals for one handler including optional per-handler `locals` | | `MergeRequestData` | How `requestData` is computed for a handler | | `HandlerRequestDefaults` | Map of default `TypedRequestData` per handler name | | `IntegrationHandlerName` | Union of valid handler keys | | `HandlerTypeExtension` | `{ locals?, oauthState?, requestData? }` for one handler entry | | `CustomMethodTypeExtension` | `{ locals?, requestData?, returnType? }` for a custom method entry | | `AdapterDataFromConfig` | `adapterData` shape for `sendAccessToken` and merged locals | | `OAuthStateFromConfig` | `login.oauthState` shape for state helpers | | `DahTypeConfig` | Generic config for DAH (`adapterData`, `data`) | | `DahFunction` | Typed DAH handler (`adapterData` + `data` params) | | `DahHelpers` | Typed helpers including `getAdapterData()` | | `DahAdapterDataFromConfig` | Adapter slice for DAH | | `DahDataFromConfig` | `DahData` merged with config `data` | | `DirectAccessHelper` | Object exported from `dah.ts` | ## What is not typed yet [#what-is-not-typed-yet] * **Cross-file inference**: you must pass the same config type alias to `defineIntegration`, auth helpers, and DAH separately (recommended: one `integration-types.ts` file) ## Tips and limitations [#tips-and-limitations] 1. **Declare fields you actually use.** Types do not validate runtime JSON; wrong or missing `adapterData` still fails at runtime. 2. **Optional vs required.** Use optional properties (`brandId?: string`) for values that appear only in some login steps; use required (`brandId: string`) when every authenticated handler expects them after login. 3. **Base request types still apply.** Extensions add fields; they do not remove SDK-required fields on `LoginRequest`, `SearchQuery`, etc. # URL Suffixes (/integration/advanced/url-suffixes) URL suffixes are special tokens appended to `downloadUrl` and `thumbnailUrl` that tell the CI HUB client how to handle authentication and caching when fetching the file. The client strips the suffix before making the actual HTTP request. ## Reference [#reference] | Suffix | Client behavior | | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `$AUTH_SESSION_ID$` | Appends the server session ID to the URL. Used by server-side integrations where downloads are proxied through the CI HUB backend | | `$FORCE_DOWNLOAD$` | Forces the client to download the file (not display inline). Sets the `Content-Disposition: attachment` behavior | | `$REQUEST_HEADERS$` | Reads custom headers from a `headers` query parameter on the URL (JSON-encoded). Supports `type=merge` (default), `type=replace`, or `type=overwrite` to control how custom headers combine with existing headers | | `$NO_AUTH$` | Signals that the URL is publicly accessible, so no auth headers are sent. The client downloads directly without proxying | | `$AUTH_PAYLOAD$` | Replaces the suffix with the URL-encoded access token as a query parameter value | | `$AUTH_PAYLOAD_BEARER$` | Replaces the suffix with URL-encoded `Bearer {token}` as a query parameter value | | `$AUTH_HEADER_PAYLOAD_BEARER$` | Strips the suffix and adds an `Authorization: Bearer {token}` header | | `$AUTH_HEADER_PAYLOAD_APITOKEN$` | Strips the suffix and adds an `Authorization: apiToken {token}` header | | `$NO_CACHE$` | Strips the suffix and adds a `Cache-Control: no-cache` header | ## Common patterns [#common-patterns] ### Public URLs [#public-urls] When your platform returns pre-signed or publicly accessible download URLs, append `$NO_AUTH$` so CI HUB downloads directly: ```ts const downloadUrl = `${asset.publicUrl}$NO_AUTH$` ``` ### Bearer token in header [#bearer-token-in-header] When the download endpoint requires the same OAuth token your integration uses, append `$AUTH_HEADER_PAYLOAD_BEARER$`. The client adds the `Authorization: Bearer` header automatically: ```ts const downloadUrl = `https://api.example.com/assets/${asset.id}/download$AUTH_HEADER_PAYLOAD_BEARER$` ``` ### Token as query parameter [#token-as-query-parameter] Some APIs expect the token in the URL itself. Use `$AUTH_PAYLOAD$` inside a query parameter: ```ts const downloadUrl = `https://api.example.com/assets/${asset.id}/content?token=$AUTH_PAYLOAD$` ``` ### Custom headers via `$REQUEST_HEADERS$` [#custom-headers-via-request_headers] For APIs that need non-standard headers (e.g. API keys, custom auth schemes), encode headers as JSON in a `headers` query parameter: ```ts const customHeaders = encodeURIComponent(JSON.stringify({ 'X-Api-Key': apiKey, 'X-Custom-Auth': customToken, })) const downloadUrl = `https://api.example.com/assets/${asset.id}/download?headers=${customHeaders}$REQUEST_HEADERS$` ``` The `type` parameter controls header merging: * `merge` (default): merges custom headers with existing ones, custom headers win on conflict * `replace`: uses only the custom headers, discards existing ones * `overwrite`: existing headers win on conflict ### Force download [#force-download] Append `$FORCE_DOWNLOAD$` when the URL would otherwise render inline (e.g., images, PDFs) and you want to ensure a file download: ```ts const downloadUrl = `${asset.viewUrl}$FORCE_DOWNLOAD$` ``` ### Disable caching [#disable-caching] Append `$NO_CACHE$` for URLs that return different content each time (e.g., latest version redirects): ```ts const thumbnailUrl = `${asset.previewUrl}$NO_CACHE$` ``` ## How the client processes suffixes [#how-the-client-processes-suffixes] The client runs `parseUrl()` which processes suffixes in this order: 1. `$AUTH_SESSION_ID$`: stripped (SDK integrations don't use server sessions) 2. `$FORCE_DOWNLOAD$`: stripped, flags the download as forced 3. `$HEADER_VALUE_STATIC_ENCODED_*`: static header extraction (internal) 4. `$NO_CACHE$`: stripped, adds `Cache-Control: no-cache` 5. Auth suffixes (mutually exclusive, only the first match applies): * `$REQUEST_HEADERS$` * `$NO_AUTH$` * `$AUTH_PAYLOAD$` * `$AUTH_PAYLOAD_BEARER$` * `$AUTH_HEADER_PAYLOAD_BEARER$` * `$AUTH_HEADER_PAYLOAD_APITOKEN$` Auth suffixes are mutually exclusive. Use only one per URL. Non-auth suffixes (`$FORCE_DOWNLOAD$`, `$NO_CACHE$`) can be combined with any auth suffix. # Advanced Handlers (/integration/building-an-integration/advanced-handlers) Handlers for rendition management, asset relationship tracking, and file transformations. These extend the upload pipeline and enable platform-specific features like linked-asset detection and format conversion. ## Upload Pipeline with Renditions [#upload-pipeline-with-renditions] When an asset is uploaded, CI HUB can trigger additional processing steps. The flow: ## getAdditionalRenditionsNeeded [#getadditionalrenditionsneeded] Called after an asset upload to determine if additional files need to be uploaded alongside the main asset. Typically used for InDesign, Illustrator, and Photoshop files that have linked assets. ### Inputs [#inputs] | Field | Description | | --------------------------- | ------------------------------ | | `requestData.query.assetId` | ID of the just-uploaded asset | | `requestData.query.name` | Filename of the uploaded asset | ### Response [#response] Return an array of rendition descriptors. Each has a `type` and a `url` that CI HUB will POST the rendition data to: ```ts return send([ { type: 'DocumentSummary', url: `${locals.endpointUrl}/saveAssetRelations?type=${fileExtension}&assetId=${encodeURIComponent(assetId)}` } ]) ``` Return `undefined` or an empty array if no additional renditions are needed. ### Patterns [#patterns] **Example** - Triggers for InDesign, Illustrator, and Photoshop files: ```ts const createAdditionalRenditions = (locals, name, assetId) => { const renditions = [] const fileExtension = path.extname(name).toLowerCase(). replace('.', '') if ([ 'ai', 'indd', 'psd' ].includes(fileExtension)) { renditions.push({ type: 'DocumentSummary', url: `${locals.endpointUrl}/saveAssetRelations?type=${fileExtension}&assetId=${encodeURIComponent(assetId)}` }) return renditions } } getAdditionalRenditionsNeeded: async (locals, requestData) => { try { const { assetId, name } = requestData.query return send(createAdditionalRenditions(locals, name, assetId)) } catch (error) { return sendError(error, 400) } }, ``` **Example** - Always returns a `DocumentSummary` rendition for every file type: ```ts const createAdditionalRenditions = (locals, name, assetId) => { const result = [] const fileExtension = path.extname(name).toLowerCase(). replace('.', '') result.push({ type: 'DocumentSummary', url: `${locals.endpointUrl}/saveAssetRelations?type=${fileExtension}&assetId=${encodeURIComponent(assetId)}` }) return result } getAdditionalRenditionsNeeded: async (locals, requestData) => { try { const { assetId, name } = requestData.query return send(createAdditionalRenditions(locals, name, assetId)) } catch (error) { return sendError(error, 400) } }, ``` *** ## additionalRendition [#additionalrendition] Receives and uploads one additional rendition file (e.g., a preview image, a linked asset). CI HUB calls this for each rendition returned by `getAdditionalRenditionsNeeded`. ### Inputs [#inputs-1] | Field | Description | | ------------------------------- | ---------------------------- | | `requestData.body.assetId` | Parent asset ID | | `requestData.body.quality` | Rendition quality identifier | | `requestData.body.name` | Rendition filename | | `requestData.getFileAsBuffer()` | Binary file data | ### Response [#response-1] ```ts return sendResult() ``` ### Patterns [#patterns-1] **Example** - Uploads rendition as multipart form data: ```ts additionalRendition: async (locals, requestData) => { const quality = requestData.body.quality const asset_id = requestData.body.assetId const name = requestData.body.name const dataBuffer = requestData.getFileAsBuffer() const formData = new FormDataNode() try { formData.append('file', dataBuffer, name || '') await callApi(locals, 'POST', '/cihub/updateAssetMedia', { asset_id, quality }, formData, formData.getHeaders()) return sendResult() } catch (err) { return sendError(err, 400) } }, ``` *** ## saveAssetRelations [#saveassetrelations] Called after CI HUB extracts the document structure from InDesign, Illustrator, or Photoshop files. Receives the document model with linked assets and creates relationship records in the DAM. ### Inputs [#inputs-2] | Field | Description | | ----------------------------------------------------------- | ----------------------------------------------------- | | `requestData.query.type` | File type: `'indd'`, `'ai'`, or `'psd'` | | `requestData.query.assetId` | Parent asset ID | | `requestData.body.document` or `requestData.query.document` | Document structure with spreads, artboards, and links | The `document` object structure varies by type: * **InDesign (`indd`)**: `document.spreads[].pages[].links[]` with master spread inheritance * **Illustrator (`ai`)**: `document.artBoards[].links[]` * **Photoshop (`psd`)**: `document.links[]` Each `link` contains `linkData` with `providerId`, `remoteSystemPrefix`, and `id` identifying the linked asset. ### Response [#response-2] ```ts return sendStatus(200) ``` ### Patterns [#patterns-2] **Example** - Extracts links from all document types and creates asset relations via REST API: ```ts saveAssetRelations: async (locals, requestData) => { const { type, assetId, name } = requestData.query const document = requestData.body.document || requestData.query.document try { if (type && !name && [ 'indd', 'ai', 'psd' ].includes(type)) { const systemPrefix = remoteSystemPrefix(locals) let links = [] if (type === 'indd') { const recursiveGetLinksFromMaster = (masterSpreadId, side) => { const masterSpread = masterSpreadId && (document?.masterSpreads || []).find(entry => entry.id === masterSpreadId) const page = masterSpread?.pages?.length && masterSpread.pages[masterSpread.pages.length > 1 && side === 'RIGHT_HAND' ? 1 : 0] return (page?.links && [ ...page.links, ...recursiveGetLinksFromMaster(page.masterSpreadId, side) ]) || [] } (document?.spreads || []).forEach(spread => (spread?.pages || []).forEach(page => { links = links.concat(page.links, recursiveGetLinksFromMaster(page.masterSpreadId, page.side)) })) } else if (type === 'ai') { (document?.artBoards || []).forEach(artBoard => { links = links.concat(artBoard.links || []) }) } else if (type === 'psd') { links = document?.links || [] } const children = links.map(link => { const linkData = link && link.linkData if (linkData && linkData.providerId === 'INTEGRATION_NAME' && linkData.remoteSystemPrefix === systemPrefix) { return { href: new URL(`api/entities/${linkData.id}`, locals.adapterData.systemUrl).toString() } } return undefined }).filter(item => item) if (children.length) { await callApi(locals, 'PUT', `/api/entities/${assetId}/relations/AssetToLinkedAsset`, null, { children, self: { href: new URL(`api/entities/${assetId}/relations/AssetToLinkedAsset`, locals.adapterData.systemUrl) } }) } } return sendStatus(200) } catch (err) { return sendError(`saveAssetRelations failed: ${err}`, 400) } }, ``` **Example** - Extracts links and creates bidirectional asset associations: ```ts saveAssetRelations: async (locals, requestData) => { const { type, assetId } = requestData.query const document = requestData.body.document || requestData.query.document try { if (type && [ 'indd', 'ai', 'psd' ].includes(type)) { let links = [] if (type === 'indd') { const recursiveGetLinksFromMaster = (masterSpreadId, side) => { const masterSpread = masterSpreadId && (document?.masterSpreads || []).find(entry => entry.id === masterSpreadId) const page = masterSpread?.pages?.length && masterSpread.pages[masterSpread.pages.length > 1 && side === 'RIGHT_HAND' ? 1 : 0] return (page?.links && [ ...page.links, ...recursiveGetLinksFromMaster(page.masterSpreadId, side) ]) || [] } (document?.spreads || []).forEach(spread => (spread?.pages || []).forEach(page => { links = links.concat(page.links, recursiveGetLinksFromMaster(page.masterSpreadId, page.side)) })) } else if (type === 'ai') { (document?.artBoards || []).forEach(artBoard => { links = links.concat(artBoard.links || []) }) } else if (type === 'psd') { links = document?.links || [] } let relations = [] links.forEach(link => { const linkData = link && link.linkData if (linkData && linkData.id && !relations.includes(linkData.id)) { relations.push(linkData.id) } }) if (relations.length) { relations = relations.map(relation => [ assetId, relation ]) relations.forEach(async relation => { await callApi(locals, 'POST', '/assets/associate', null, { assetIds: relation }) }) } } return sendStatus(200) } catch (err) { return sendError(`saveAssetRelations failed: ${err}`, 400) } }, ``` The InDesign link extraction is recursive. Master spreads can reference other master spreads, so `recursiveGetLinksFromMaster` traverses the chain. *** ## getAvailableTransformations [#getavailabletransformations] Returns the list of transformations the user can apply to assets (e.g., named presets, format conversions). CI HUB displays these as options in the transformation UI. ### Response [#response-3] Return an array of transformation descriptors: ```ts return send([ { id: 'named:my-preset', name: 'my-preset', details: { ... } }, { id: 'format:png', name: 'PNG', extension: 'png' }, { id: 'format:jpg', name: 'JPEG', extension: 'jpg' } ]) ``` ### Patterns [#patterns-3] **Example** - Fetches named transformations from the platform API and adds format conversions: ```ts getAvailableTransformations: async (locals, requestData) => { const client = getClient(locals) const result = [] try { const transformationList = await client.api.transformations({ named: 'true' }) for (const transformation of transformationList.transformations) { const transformationId = `${transformation.name.startsWith('t_') ? transformation.name.substring(2) : transformation.name}` const transformationDetails = await client.api.transformation(transformationId) const listItem = { id: `named:${transformationId}`, name: transformationId, details: transformationDetails.info } result.push(listItem) } result.push(...formatConversions) return send(result) } catch (err) { console.error(err) return sendError(err, 400) } }, ``` *** ## doTransformation [#dotransformation] Applies a transformation to an asset and returns the transformed file as a stream. CI HUB calls this when the user selects a transformation and confirms. ### Inputs [#inputs-3] | Field | Description | | -------------------------------------------------------------- | ------------------------------------------------------ | | `requestData.query.transformationId` | Transformation ID (from `getAvailableTransformations`) | | `requestData.body.dataBuffer` or `requestData.body.dataBase64` | Source file data | | `requestData.body.name` | Source filename | ### Response [#response-4] Return the transformed file as a stream: ```ts const { data } = await axios.get(downloadUrl, { responseType: 'stream', headers: { Accept: 'application/octet-stream' } }) return send(data) ``` ### Patterns [#patterns-4] **Example** - Uploads source file, applies named transformation or format conversion, pipes result: ```ts doTransformation: async (locals, requestData) => { const { transformationId } = requestData.query const { dataBuffer, dataBase64, name } = requestData.body const client = getClient(locals) const [ transformationType, transformationData ] = transformationId.split(':') try { const nativeAssetId = await uploadAsset(locals, dataBuffer, dataBase64, name, undefined, undefined, false, true) const { publicId, version, resourceType, uploadType } = splitAssetId(nativeAssetId) let transformationParams if (transformationType === 'format') { transformationParams = { format: transformationData } } else { transformationParams = { transformation: transformationData } } const downloadUrl = getTransformedImageUrl(client, publicId, version, resourceType, uploadType, transformationParams) const { data } = await axios.get(downloadUrl, { responseType: 'stream', headers: { Accept: 'application/octet-stream' } }) return send(data) } catch (err) { if (err && err.error && err.error.message) { return sendError(err.error.message, 400) } else { return sendError(err, 400) } } }, ``` The `transformationId` format uses a prefix to distinguish types: `named:preset-name` for named transformations, `format:png` for format conversions. Split on `:` to extract the type and value. [Create Asset Schema](/integration/schemas/assets/create-asset) # Asset Operations (/integration/building-an-integration/asset-operations) Handlers for modifying assets after they exist: delete, version history, lock/unlock, rename, and move. Each requires a capability flag to appear in the plugin UI. ## Capability Flags [#capability-flags] Enable each operation in your integration's `capabilities` object: ```ts capabilities: { canDeleteAsset: true, canLockAsset: true, canRenameAsset: true, canMoveAsset: true } ``` `getAssetVersions` has no capability flag. It's always available when implemented. ## deleteAsset [#deleteasset] Permanently removes an asset from the platform. CI HUB calls this when the user clicks **Delete** on an asset in the plugin UI. ### Inputs [#inputs] | Field | Description | | ----------------------------------------------------------- | ----------------------------------------------------------------------------------- | | `requestData.params.assetId` | Asset ID to delete | | `requestData.query.parentId` or `requestData.body.parentId` | Parent folder ID (some platforms need this to distinguish collections from folders) | ### Response [#response] ```ts return sendResult(null) // or return sendStatus(200) ``` ### Patterns [#patterns] **Example** - REST API, strips version suffix from compound IDs: ```ts deleteAsset: async (locals, requestData) => { const assetId = requestData.params.assetId.split('::')[0] try { await callApi(locals, 'DELETE', `/api/v4/media/${assetId}/`, {}) return sendResult(null) } catch (err) { return sendError(`Could not delete asset ${assetId} (${err})`, 403) } }, ``` **Example** - DAM that handles collection vs folder context: ```ts deleteAsset: async (locals, requestData) => { try { const { assetId } = requestData.params const parentFolderId = requestData.query.parentId || requestData.body.parentId || '' if (parentFolderId.startsWith('collection:')) { const collectionId = parentFolderId.replace('collection:', '') await callApi(locals, { query: queries.removeCollectionAssetsMutation, variables: { input: { collectionId, assetIds: [ assetId ] } } }) } else { await callApi(locals, { query: queries.deleteAssetMutation, variables: { input: { id: assetId } } }) } return sendStatus(200) } catch (error) { return sendError(error, 400) } }, ``` ### UI Behavior [#ui-behavior] On success, the asset disappears from the current folder/search results. On error, the plugin UI shows the error message. [Delete Asset Schema](/integration/schemas/assets/delete-asset) *** ## getAssetVersions [#getassetversions] Returns version history for an asset. CI HUB calls this when the user opens the version panel for an asset. ### Inputs [#inputs-1] | Field | Description | | ----------------------------------------------------------- | ---------------------------------------------- | | `requestData.query.assetId` | Single asset ID | | `requestData.query.assetIds` or `requestData.body.assetIds` | Array of asset IDs (batch mode) | | `requestData.query.withMaster` | `"true"` to include the current/master version | ### Response [#response-1] Return an object with `id`, `name`, and `versions` array. Each version uses the same shape as `extractAssetsData` output plus `masterId`: ```ts return send({ id: assetId, name: 'filename.jpg', versions: [ { ...assetData, // standard asset fields (thumbnailUrl, fileSize, etc.) masterId: assetId, // always the root asset ID id: 'asset123::2', // version-specific ID version: 2, } ] }) ``` ### Patterns [#patterns-1] **Example** - DAM that iterates `mediaItems` for version history: ```ts const getAssetVersions = async (locals, requestData, assetId) => { const withMaster = requestData.query.withMaster === 'true' try { const asset = await callApi(locals, 'GET', `/api/v4/media/${assetId}`, { versions: true }) const assetInfo = extractAssetData(locals, asset) const result = { id: assetId, name: '', versions: [] } result.versions = asset.mediaItems. filter(item => item.type === 'original'). sort((itemA, itemB) => itemB.version - itemA.version). map((item, idx) => { const versionId = `${assetId}::${item.version}` const version = Object.assign({}, assetInfo, { masterId: assetId, id: versionId, version: item.version, fileSize: item.size, xSizePx: item.width, ySizePx: item.height, thumbnailUrl: item.thumbnails.thul && `${item.thumbnails.thul}$NO_AUTH$`, downloadUrl: getDownloadUrl(locals, versionId), lowresUrl: getDownloadUrl(locals, versionId, '?lowres=1') }) if (idx) { version.created = new Date(item.dateCreated).getTime() version.modified = new Date(item.dateCreated).getTime() version.downloadHashFileAttributes = JSON.stringify({ fileSize: version.fileSize, modified: version.modified }) } return version }) if (!withMaster) { result.versions.shift() } return result } catch (err) { throw new Error(`Could not get asset versions for ${assetId} (${err})`) } } ``` **Example** - DAM that returns single version when platform doesn't support version history: ```ts getAssetVersions: async (locals, requestData) => { const { assetId } = requestData.query const withMaster = requestData.query.withMaster === 'true' const result = { id: assetId, name: undefined, versions: [] } if (!withMaster) { return sendError('DAM doesn\'t support versioning', 400) } try { const asset = await callApi(locals, { query: queries.getAssetByIdQuery, variables: { assetId } }) result.versions = asset.data.asset && extractAssetsData(locals, [ asset.data.asset ]).map(assetData => ({ ...assetData, masterId: assetId })) result.name = result.versions[0]?.name return send(result) } catch (error) { return sendError(error, 400) } }, ``` ### UI Behavior [#ui-behavior-1] The version panel lists all returned versions with thumbnails, dates, and file sizes. Users can download or place any version. The `masterId` links versions back to the root asset. [Asset Versions Schema](/integration/schemas/assets/get-asset-versions) *** ## lockAsset [#lockasset] Locks (checks out) or unlocks (checks in) an asset. Prevents concurrent edits on platforms that support exclusive checkout. ### Inputs [#inputs-2] | Field | Description | | ---------------------------- | --------------------------------- | | `requestData.params.assetId` | Asset ID | | `requestData.body.locked` | `true` to lock, `false` to unlock | ### Response [#response-2] ```ts return send({ id: assetId, lockedBy: 'username' }) // locked return send({ id: assetId, lockedBy: null }) // unlocked ``` ### Patterns [#patterns-2] **Example** - DAM with checkout/checkin endpoint, polls for lock confirmation: ```ts lockAsset: async (locals, requestData) => { const assetId = requestData.params.assetId const locked = requestData.body.locked const action = locked ? 'checkout' : 'checkin' try { await callApi(locals, 'POST', `content/dam/${assetId}.checkout.json`, { action }) let retries = maxRetries let lockedBy if (locked) { while (!lockedBy && retries) { if (retries !== maxRetries) { await promisify(setTimeout)(1000) } lockedBy = (await callApi(locals, 'GET', `/platform/content/dam/${assetId};resource=metadata`))?.['aem:checkedOutBy'] retries -= 1 } if (retries === 0) { throw new Error(`${locked ? 'Lock (checkout)' : 'Unlock (checkin)'} operation failed after a ${maxRetries} second(s) waiting period.`) } } return send({ id: assetId, lockedBy }) } catch (err) { return sendResult(err) } }, ``` **Example** - DAM that supports separate lock/unlock endpoints: ```ts lockAsset: async (locals, requestData) => { const assetId = requestData.params.assetId const locked = requestData.body.locked const result = { id: null, lockedBy: null } try { const currentUser = (await callApi(locals, 'GET', '/users/current')).payload if (locked) { const lockResponse = await callApi(locals, 'POST', `/assets/${assetId}/checkOut`) if (lockResponse.errors && lockResponse.errors.length) { return sendError(lockResponse.errors.join(', '), 400) } result.id = assetId result.lockedBy = `You (${currentUser.userName})` } else { const unlockResponse = await callApi(locals, 'PATCH', `/assets/${assetId}`, null, [{ op: 'remove', path: '/checkedOutBy' }]) if (unlockResponse.errors && unlockResponse.errors.length) { return sendError(unlockResponse.errors.join(', '), 400) } result.id = assetId } } catch (err) { return sendError(err, 400) } return send(result) }, ``` ### UI Behavior [#ui-behavior-2] When locked, the plugin UI shows a lock icon on the asset and displays `lockedBy`. Only the lock owner (or an admin, depending on platform) can unlock. The lock prevents other users from uploading new versions. [Lock Asset Schema](/integration/schemas/assets/lock-asset) *** ## renameAsset [#renameasset] Changes an asset's display name or filename. ### Inputs [#inputs-3] | Field | Description | | ---------------------------- | ----------- | | `requestData.params.assetId` | Asset ID | | `requestData.body.name` | New name | ### Response [#response-3] ```ts return send({ id: assetId, name: newName }) ``` ### Patterns [#patterns-3] **Example** - DAM that distinguishes filename vs title based on extension: ```ts renameAsset: async (locals, requestData) => { try { const { name } = requestData.body const { assetId } = requestData.params const hasExtension = Boolean(mime.lookup(name)) const asset = await callApi(locals, { query: queries.updateAssetMutation, variables: { input: { id: assetId, data: hasExtension ? { filename: name } : { title: name } } } }) const updatedAsset = asset.data.updateAsset.asset return send({ id: updatedAsset.id.toString(), name: hasExtension ? updatedAsset.filename : updatedAsset.title }) } catch (error) { return sendError(error, 400) } }, ``` **Example** - REST API, straightforward PUT: ```ts renameAsset: async (locals, requestData) => { try { const { name } = requestData.body const { assetId } = requestData.params const { id } = getAssetIdInfo(assetId) await callApi(locals, 'PUT', `/files/${id}`, null, { name }) return send({ id: assetId, name }) } catch (error) { return sendError(error, 400) } }, ``` ### UI Behavior [#ui-behavior-3] On success, the asset's name updates immediately in the plugin UI (folder view and detail panel). [Rename Asset Schema](/integration/schemas/assets/rename-asset) *** ## moveAsset [#moveasset] Moves an asset from one folder to another. ### Inputs [#inputs-4] | Field | Description | | ---------------------------------- | --------------------- | | `requestData.body.assetId` | Asset ID | | `requestData.body.targetParentId` | Destination folder ID | | `requestData.body.currentParentId` | Source folder ID | ### Response [#response-4] ```ts return send({ id: assetId, folderId: targetParentId }) ``` ### Patterns [#patterns-4] **Example** - DAM that replaces old category with new one: ```ts moveAsset: async (locals, requestData) => { try { const { assetId, targetParentId: folderId, currentParentId } = requestData.body if (typeof folderId !== 'string' || !folderId || folderId.startsWith('lightbox') || [ 'root', 'categories', 'lightboxes', 'home', 'mostViewed', 'recentlyUploaded' ].includes(folderId)) { return sendError('Invalid folder ID', 400) } const assetCategories = ((await callApi(locals, 'GET', `/assets/${assetId}/versions/basic`))?.payload?.[0]?.categoryIds || []).filter(category => category !== currentParentId?.toString()).concat(folderId.toString()) await callApi(locals, 'PUT', `/assets/${assetId}/categories`, null, assetCategories) return send({ id: assetId, folderId }) } catch (err) { return sendError(err, 400) } }, ``` Validate `targetParentId` before making API calls. Some virtual folder IDs (`root`, `lightbox:*`) are not valid move targets. ### UI Behavior [#ui-behavior-4] On success, the asset disappears from the current folder view and appears in the target folder. [Move Asset Schema](/integration/schemas/assets/move-asset) # Auth Handlers (/integration/building-an-integration/auth-handlers) Three handlers that complete the auth lifecycle after login: `checkToken`, `refreshToken`, and `logout`. ## checkToken [#checktoken] Called before every session resume. CI HUB verifies the stored access token is still valid. Make an API call to the platform's "current user" endpoint. On success, return user info via `send()`. On failure, return `sendError()` to force re-login. ### Inputs [#inputs] | Field | Description | | -------------------- | ---------------------------------------------- | | `locals.authPayload` | Stored access token (string or object) | | `locals.adapterData` | Integration-specific data persisted from login | Type `locals.adapterData` fields with a shared config on `defineIntegration` instead of casting manually. See [Typed Integrations](/integration/advanced/typed-integrations). ### Response [#response] ```ts // Success: session resumes, plugin UI shows user display name return send({ adapter: 'INTEGRATION_NAME', source: 'hostname-or-label', user: 'displayName' }) // Failure: forces re-login return sendError(err, 400) ``` The `source` field appears in the plugin UI connection list. Typically derived from the server URL hostname. ### Patterns [#patterns] **Example** - OAuth integration, validates token via REST call: ```ts checkToken: async (locals) => { try { const data = await callApi(locals, 'GET', '/api/v4/currentUser/', {}) return send({ adapter: 'INTEGRATION_NAME', source: remoteSystemPrefix(locals), user: data.username }) } catch (err) { return sendError(err, 400) } }, ``` **Example** - OAuth integration, validates via SDK client: ```ts checkToken: async (locals) => { const accessToken = locals.authPayload sstk.setAccessToken(accessToken) try { const usersApi = new sstk.UsersApi() const user = await usersApi.getUser() return send({ adapter: 'INTEGRATION_NAME', source: remoteSystemPrefix, user: user.username }) } catch (err) { return sendError(err, 400) } }, ``` **Example** - Credential-based integration (API key/secret), no API call needed: ```ts checkToken: async (locals) => { try { const cloudName = locals.authPayload.cloudName return send({ adapter: 'INTEGRATION_NAME', source: remoteSystemPrefix, user: cloudName }) } catch (err) { return sendError(err, 400) } }, ``` For credential-based integrations where the token is an object (not an OAuth access token), extract the display name directly. No API validation is needed. ### UI Behavior [#ui-behavior] On success, the plugin UI restores the previous session and shows the `user` value in the connection header. On failure, CI HUB drops the session and shows the login screen. *** ## refreshToken [#refreshtoken] Called when `checkToken` fails and a stored refresh token exists. Exchange the refresh token for a new access token. Return the new token via `sendAccessToken()`. Return `sendError()` to abandon refresh and force re-login. ### Inputs [#inputs-1] | Field | Description | | -------------------- | ---------------------------------------------- | | `locals.authPayload` | Stored refresh token | | `locals.adapterData` | Integration-specific data persisted from login | ### Response [#response-1] ```ts // Success: new access token stored, session resumes return sendAccessToken(null, accessToken, expiresIn, refreshToken, refreshExpiresIn, adapterData) // Failure: forces re-login return sendError(err, 400) ``` Parameter order for `sendAccessToken`: error, token, expiresIn, refreshToken, refreshExpiresIn, adapterData. ### Patterns [#patterns-1] **Example** - Standard OAuth refresh with adapterData preservation: ```ts refreshToken: async (locals) => { const adapterData = locals.adapterData if (!adapterData.resourceEndpoint) { return sendError('Could not refresh token, please re-add the connection.', 400) } try { const oauth = getAuthClient(adapterData.resourceEndpoint) const accessToken = oauth.createToken({ refresh_token: locals.authPayload }) const { token } = await accessToken.refresh() if (!token || !token.access_token) { throw new Error('No access_token found') } return sendAccessToken(null, token.access_token, token.expires_in, undefined, undefined, adapterData) } catch (err) { return sendError(err, 400) } }, ``` Validate `adapterData` before attempting refresh. Stale sessions missing required fields should error immediately with a clear message. **Example** - OAuth refresh with client credentials: ```ts refreshToken: async (locals) => { const clientKey = config.get('IntegrationName.clientKey') const clientSecret = config.get('IntegrationName.clientSecret') const refreshToken = locals.authPayload const oauth = getAuthClient() const token = oauth.createToken({ refresh_token: refreshToken }) try { const newToken = (await token.refresh({ client_id: clientKey, client_secret: clientSecret })).token const accessToken = newToken.access_token const tokenExpiresIn = newToken.expires_in return sendAccessToken(null, accessToken, tokenExpiresIn) } catch (err) { return sendAccessToken(err) } }, ``` **Example** - Credential-based integration, no actual refresh: ```ts refreshToken: async (locals) => { try { const token = locals.authPayload const adapterData = locals.adapterData return sendAccessToken(null, token, null, null, null, adapterData) } catch (err) { return sendError(err, 400) } }, ``` Credential-based integrations (API key + secret) have no expiring OAuth token. Re-send the same token and adapterData to keep the session alive. ### UI Behavior [#ui-behavior-1] On success, the session resumes transparently. The user never sees a login screen. On failure, CI HUB falls back to the login flow. *** ## logout [#logout] Called when the user disconnects from the integration in the plugin UI. Revoke tokens if the platform supports it, then return `sendStatus(200)`. CI HUB deletes all stored tokens regardless of the handler's response. ### Inputs [#inputs-2] | Field | Description | | -------------------------------- | ----------------------------------- | | `locals.authPayload` | Stored access token | | `requestData.body.refresh_token` | Stored refresh token (if available) | ### Response [#response-2] ```ts // Always return 200 return sendStatus(200) ``` ### Patterns [#patterns-2] **Example** - Revokes refresh token via OAuth client: ```ts logout: async (locals, requestData) => { const access_token = locals.authPayload const { refresh_token } = requestData.body try { const oauth = getAuthClient() const token = oauth.createToken({ access_token, refresh_token }) await token.revoke('refresh_token') return sendStatus(200) } catch (err) { return sendError(err, 400) } }, ``` **Example** - No revocation endpoint, return immediately: ```ts logout: async (locals, requestData) => { return sendStatus(200) }, ``` **Example** - No revocation, wrapped in try/catch: ```ts logout: async (locals, requestData) => { try { return sendStatus(200) } catch (err) { return sendError(err, 400) } }, ``` If the platform has no token revocation endpoint, `sendStatus(200)` is sufficient. CI HUB cleans up stored tokens on its side. ### UI Behavior [#ui-behavior-2] After logout completes, the plugin UI removes the connection and returns to the integration selection or login screen. *** ## Auth Flow Sequence [#auth-flow-sequence] *** [Check Token Schema](/integration/schemas/auth/check-token) | [Refresh Token Schema](/integration/schemas/auth/refresh-token) | [Logout Schema](/integration/schemas/auth/logout) # Custom Methods (/integration/building-an-integration/custom-methods) Custom methods let you expose server-side functions from your integration that the Direct Access Helper (or any browser code) can call via the CI HUB server. Because they run on the server, they can reach provider APIs that don't support CORS and can use credentials you never want to expose to the browser. This is an advanced escape hatch. Most integrations don't need it. It becomes relevant when your DAH needs to perform a step that the browser cannot do directly, such as generating a signed upload URL using a secret key or calling an internal API that restricts the allowed origins. ## How it works [#how-it-works] You add extra keys to the `defineIntegration` object alongside your standard handlers. Each key becomes a callable method name. When the CI HUB server receives a request at: ``` GET /api/v1/system/providerInternal/:methodName POST /api/v1/system/providerInternal/:methodName ``` it routes the call to the matching function in your integration. The function receives the same `locals` as every other handler (including `locals.adapterData`) and a `requestData` object containing whatever `query`, `body`, and `params` the caller sent. ```typescript title="src/index.ts" import { defineIntegration, send, sendError } from '@ci-hub/integration-sdk' defineIntegration({ name: 'My DAM', version: '1.0.0', capabilities: { category: 'DAM' }, // Standard handlers login: async (locals, requestData) => { /* ... */ }, search: async (locals, requestData) => { /* ... */ }, // Custom method sign: async (locals, requestData) => { try { const { uploadParams } = requestData.body const result = await generateSignature(uploadParams, locals.adapterData.secretKey) return send(result) } catch (err) { return sendError(err?.message ?? err, 400) } } }) ``` ## Calling from the DAH [#calling-from-the-dah] Use the standard integration request headers. The `Authorization` header carries the CI HUB platform token and `Provider-Authorization` carries the provider token. Both are available from the `helpers` object passed to your DAH function. ```typescript title="src/dah.ts" import type { DahFunction } from '@ci-hub/integration-sdk' const createAsset: DahFunction = async (axios, _payload, _sessionId, data, onProgress, _adapterData, _providerToken, helpers) => { // Call the custom method before uploading const { data: signatureData } = await axios.post( `${process.env.SERVER_BASE_URL}/api/v1/system/providerInternal/sign`, // [!code highlight] { uploadParams: { fileName: data.name, parentId: data.parentId } }, { headers: { 'Authorization': 'Bearer '.concat(helpers.getAccessToken()), 'Provider-Authorization': 'Bearer '.concat(helpers.getProviderAccessToken() || helpers.getPayload()) } } ) // Use signatureData.signature, signatureData.timestamp, etc. await axios.put(signatureData.uploadUrl, data.file, { headers: { 'Content-Type': 'application/octet-stream' }, maxContentLength: Infinity, onUploadProgress: (e) => onProgress(e.loaded / data.file.size) }) return { id: signatureData.assetId, name: data.name } } export default { createAsset } satisfies import('@ci-hub/integration-sdk').DirectAccessHelper ``` Inject `SERVER_BASE_URL` at build time via `buildDAH`'s second argument: ```typescript title="src/index.ts" const dahString = await buildDAH( path.join(import.meta.dirname, 'dah.ts'), { 'process.env.SERVER_BASE_URL': JSON.stringify(config.get('serverBaseUrl')) // [!code ++] } ) ``` Custom methods can also be called from any other server-side or browser-side context that can send the required headers. They are not exclusive to the DAH. ## Request and response [#request-and-response] There is no enforced request schema. The integration receives whatever the caller sends: | Source | Available as | | ------------------- | -------------------- | | URL query string | `requestData.query` | | Request body (JSON) | `requestData.body` | | URL path params | `requestData.params` | | Connection data | `locals.adapterData` | Return a response using `send(value)` or signal an error with `sendError(message, statusCode)`. Custom methods are **not** validated against Zod response schemas at runtime. The caller receives whatever JSON your function passes to `send`. ## Typing [#typing] Custom method keys use `CustomMethodTypeExtension` in the generic type config. The shape differs from standard handler keys: it supports `locals`, `requestData`, and `returnType` (but not `oauthState`). ```typescript title="src/integration-types.ts" import type { IntegrationTypeConfig } from '@ci-hub/integration-sdk' export type MyIntegrationConfig = { adapterData: { secretKey: string } sign: { // [!code ++:6] requestData: { body: { uploadParams: Record } } returnType: { signature: string; timestamp: number; uploadUrl: string } } } type _Assert = MyIntegrationConfig extends IntegrationTypeConfig ? true : never ``` ```typescript title="src/index.ts" defineIntegration({ sign: async (locals, requestData) => { locals.adapterData.secretKey // string requestData.body.uploadParams // Record return send({ signature: '...', timestamp: Date.now(), uploadUrl: '...' }) } }) ``` See [Typed Integrations: Custom methods](/integration/advanced/typed-integrations#custom-methods) for the full type reference. ## Reserved names [#reserved-names] Do not use these as custom method names. They conflict with standard integration keys: **Metadata:** see [Metadata](/integration/advanced/metadata) **Standard handlers:** see [Standard handlers](/integration/building-an-integration/standard-handlers) Any other key name is valid. # Direct Access Helper (/integration/building-an-integration/direct-access-helper) A Direct Access Helper (DAH) is a browser-side upload module that lets CI HUB clients upload files **directly to the provider API**, bypassing the CI HUB server proxy. Without a DAH, every file upload flows through the CI HUB server (`Browser → CI HUB Server → Provider API`). With a DAH, the browser talks to the provider directly (`Browser → Provider API`). This eliminates the server as a bottleneck for large files: no double transfer, no server memory pressure, no request timeouts on multi-GB uploads. A DAH can implement `createAsset` (new file upload), `updateAsset` (new version of existing file), or both. It runs inside the end-user's browser, receives an `axios` instance and auth credentials, and makes HTTP calls to the provider on its own. ## When you need one [#when-you-need-one] A DAH is **required for all new integrations**. Submissions without one will be rejected unless you can demonstrate that your provider's API cannot support browser-to-API uploads. Beyond the submission requirement, a DAH is especially valuable when: * Your provider supports direct browser-to-API uploads (pre-signed URLs, chunked uploads, multipart, etc.) * File sizes may exceed what the CI HUB server proxy can comfortably handle (typically >100 MB) * You want to show real upload progress to the user (the DAH receives an `onProgress` callback) * You want to reduce upload latency by cutting the server hop ## How it works [#how-it-works] 1. You write a TypeScript file (e.g. `src/dah.ts`) that **default-exports** a `DirectAccessHelper` object with `createAsset` and/or `updateAsset`. 2. In your integration entry file, call `buildDAH(path.join(import.meta.dirname, 'dah.ts'))`. It uses Vite internally to bundle your file into a self-contained IIFE string. Any packages or helper functions you import in your DAH file get bundled automatically. 3. Pass the result to `capabilities.directAccessHelper` in your integration definition. 4. The [SDK Workbench](/integration/getting-started/workbench) evaluates the string in the browser and shows a **"Direct Access"** button next to the normal **"Create Asset"** / **"Update Asset"** buttons. ## Building your DAH [#building-your-dah] Call `buildDAH` in your integration entry file. It takes the path to your DAH source file and an optional `define` map for build-time config injection: ```ts import path from 'node:path' import { defineIntegration, buildDAH } from '@ci-hub/integration-sdk' import * as queries from './queries.js' const dahString = await buildDAH(path.join(import.meta.dirname, 'dah.ts'), { 'process.env.GRAPH_BASE_ENDPOINT': JSON.stringify(config.get('myProvider.graphBaseEndpoint')), 'process.env.UPLOAD_FILE_MUTATION': JSON.stringify(queries.uploadFileMutation), 'process.env.REGION_API_URLS': { 'qa-us': config.get('myProvider.regions.qa-us.apiUrl'), 'prod-us': config.get('myProvider.regions.prod-us.apiUrl'), 'prod-eu': config.get('myProvider.regions.prod-eu.apiUrl') } }) defineIntegration({ name: 'my-integration', version: '1.0.0', capabilities: { category: 'DAM', directAccessHelper: dahString, // ... }, // ... handlers }) ``` `buildDAH` takes your source file, bundles it with Vite into a browser-ready IIFE expression, and returns the string. You can: * **Import packages**: any `import` in your DAH file gets bundled (e.g. a provider SDK, a hashing library). * **Use TypeScript**: full type checking with the exported `DahFunction`, `DahHelpers`, `DahData`, `DirectAccessHelper` types. Pass a `DahTypeConfig` generic for typed `adapterData` and `data` parameters. See [DAH typing](/integration/advanced/typed-integrations#direct-access-helper-dah). * **Inject config values at build time**: pass replacements via the second argument; references like `process.env.GRAPH_BASE_ENDPOINT` in your DAH source get inlined. Values are passed to Vite's `define` option, which does **textual substitution**. Always wrap string values in `JSON.stringify(...)`. Otherwise multi-line strings (e.g. GraphQL queries) and special characters will produce `Invalid define value (must be an entity name or JS literal)` build errors. ## Entry file requirements [#entry-file-requirements] The DAH entry file (`dah.ts`) must be a **plain ES module that default-exports the helper object**. No top-level IIFE wrapping, no top-level side effects. ```ts import type { DirectAccessHelper, DahFunction } from '@ci-hub/integration-sdk' const createUpdateAsset: DahFunction = async (axios, payload, _sessionId, data, onProgress, _adapterData, _accessToken, helpers) => { // ... } export default { createAsset: createUpdateAsset, updateAsset: createUpdateAsset } satisfies DirectAccessHelper ``` Do **not** wrap the entry in an IIFE: ```ts // WRONG: top-level IIFE produces a "double-wrapped" bundle whose value is undefined when eval'd (function () { const createUpdateAsset = async (...) => {...} return { createAsset: createUpdateAsset, updateAsset: createUpdateAsset } })() ``` Vite needs real ES exports to know what to surface from the bundled IIFE. Without `export default`, you'll either get an "empty chunk" warning, or a bundle that returns `undefined` from `eval`, and the host will silently fall back to the non-DAH upload path. ## Function signature [#function-signature] ```ts import type { DahFunction } from '@ci-hub/integration-sdk' const createAsset: DahFunction = async ( axios, // axios 0.19.2 instance payload, // the raw access token (provider credentials) sessionId, // CI HUB session ID (empty string in SDK test mode) data, // { parentId, name, file, comment, createAssetOptions, ... } onProgress, // callback: pass a fraction 0..1 (e.g. 0.5 = 50%) adapterData, // adapter-specific data from login (e.g. { resourceEndpoint }) providerAccessToken, // JWT string wrapping payload + adapterData helpers // utility functions (hashing, token getters, etc.) ) => { // ... upload logic ... return { id: 'new-asset-id', name: 'filename.png' } } ``` All eight parameters are always provided. You only use the ones your provider needs. ## Input types [#input-types] ### `data` (`DahData`) [#data-dahdata] | Field | Type | When present | | -------------------- | ------------------------ | -------------------------------- | | `parentId` | `string` | createAsset: target folder ID | | `assetId` | `string` | updateAsset: asset to update | | `name` | `string` | filename | | `comment` | `string` | optional version comment | | `file` | `File \| Blob` | the raw file bytes (not base64) | | `createAssetOptions` | `Record` | provider-specific create options | | `updateAssetOptions` | `Record` | provider-specific update options | | `statusInfoPrefix` | `string` | optional progress label prefix | ### `helpers` (`DahHelpers`) [#helpers-dahhelpers] | Helper | Returns | Notes | | -------------------------- | ------------------------- | --------------------------------------------------------------------------------- | | `calcMd5Hash(blob)` | `Promise` | MD5 hex, **not available in SDK test mode** (Web Crypto limitation), returns `''` | | `calcSha1Hash(blob)` | `Promise` | SHA-1 base64 | | `calcSha256Hash(blob)` | `Promise` | SHA-256 hex | | `getPayload()` | `unknown` | the raw provider access token | | `getAdapterData()` | `Record` | adapter data from login | | `getAccessToken()` | `string` | CI HUB platform access token | | `getProviderAccessToken()` | `string` | JWT wrapping payload + adapterData | | `getSessionId()` | `string` | CI HUB session ID | | `getRequestHeaders()` | `Record` | extra headers from provider info | | `getBase64FromString(str)` | `string` | base64-encode a UTF-8 string | ### `axios` [#axios] The DAH receives `axios@0.19.2` (not the latest). This is intentional. The host depends on the 0.19.x API shape. See the [axios 0.19.x documentation](https://github.com/axios/axios/tree/v0.x) for the API of that version. ## Output type [#output-type] ### `DahResult` [#dahresult] ```ts type DahResult = { id: string name: string sessionId?: string userMsg?: string data?: { id: string; name: string } } ``` | Field | Required | Description | | ----------- | -------- | -------------------------------------------------------------- | | `id` | yes | the created/updated asset ID | | `name` | yes | the asset filename | | `sessionId` | no | updated session ID (if the provider rotates sessions) | | `userMsg` | no | message to display to the user | | `data` | no | alternative nesting, `{ id, name }` is unwrapped automatically | Both flat (`{ id, name }`) and nested (`{ data: { id, name } }`) return shapes are accepted. The SDK normalizes them. ## Full example [#full-example] **`src/dah.ts`**: the DAH entry file: ```ts import type { DahFunction, DirectAccessHelper } from '@ci-hub/integration-sdk' const createUpdateAsset: DahFunction = async ( axios, payload, _sessionId, data, onProgress, _adapterData, _providerAccessToken, helpers ) => { const file = data.file! const fileSize = file.size const isUpdate = !!data.assetId const { data: uploadInfo } = await axios.post( 'https://api.my-provider.com/uploads/init', { fileName: data.name, parentId: data.parentId, assetId: data.assetId, contentHash: await helpers.calcSha256Hash(file) }, { headers: { Authorization: `Bearer ${payload}` } } ) await axios.put(uploadInfo.uploadUrl, file, { headers: { 'Content-Type': 'application/octet-stream' }, maxBodyLength: Infinity, onUploadProgress: (event) => { onProgress(event.loaded / fileSize) } }) const { data: asset } = await axios.post( 'https://api.my-provider.com/uploads/confirm', { uploadId: uploadInfo.id }, { headers: { Authorization: `Bearer ${payload}` } } ) return { id: asset.id, name: asset.name } } export default { createAsset: createUpdateAsset, updateAsset: createUpdateAsset } satisfies DirectAccessHelper ``` **`src/index.ts`**: wiring the DAH into your integration: ```ts import path from 'node:path' import { defineIntegration, buildDAH } from '@ci-hub/integration-sdk' const dahString = await buildDAH(path.join(import.meta.dirname, 'dah.ts')) defineIntegration({ name: 'my-provider', version: '1.0.0', capabilities: { category: 'DAM', directAccessHelper: dahString, }, // ... handlers }) ``` ## Limitations [#limitations] The DAH runs as a self-contained IIFE inside the end-user's browser. That shapes everything below. ### Runtime environment [#runtime-environment] * **Browser-only, not Node.** No `fs`, `path`, Node `crypto`, `Buffer`, or `process` (except keys you inject via `define`). Don't import Node-only packages (e.g. `mime-types`, `fs-extra`). Use Web platform APIs instead: `fetch`, `crypto.subtle`, `URL`, `Blob`, `File`, `btoa`, `atob`, `TextEncoder`, etc. * **Strict mode is always on.** Vite wraps the IIFE body with `"use strict"`. Implicit globals, `with`, octal literals produce errors. * **No top-level `await`.** The IIFE is synchronous. Keep `await` inside `createUpdateAsset`. (`async function` itself is fine.) * **No dynamic `import()` or `require()`.** The bundle has to be fully self-contained. Anything you need must be imported statically and bundled in. * **No CSS / asset imports.** Don't `import './style.css'` or `import logo from './logo.png'`. These produce extra chunks that don't fit the single-string eval model. * **No `import.meta.url` / `import.meta.dirname`.** Module URLs don't exist inside an `eval`'d IIFE. ### CORS [#cors] The provider's API must allow cross-origin requests from every host that runs the CI HUB panel. If the provider doesn't support CORS at all, a DAH won't work. Allowed origins your provider needs to whitelist: ``` https://app-aagcgsdkbdg.canva-apps.com https://app-aagppabnsou.canva-apps.com https://live.ci-hub.com https://stage.ci-hub.com https://dev.ci-hub.com https://ci-hub.azurewebsites.net https://ci-hub-test.azurewebsites.net https://ci-hub-beta.azurewebsites.net http://localhost:8080 https://localhost:8080 ``` ### Fixed function signature [#fixed-function-signature] You cannot change the parameter list. The host always calls: ```ts directAccessHelper[action]( axios, // pre-configured axios@0.19.2 instance, use THIS, do not import your own payload, // provider access token (string) sessionId, // string data, // { parentId?, assetId?, name, comment?, file, createAssetOptions?, updateAssetOptions? } onProgress, // (fraction: number) => void adapterData, // opaque provider state from login providerToken, // JWT wrapping payload + adapterData helpers // see "helpers" table above ) ``` * **Only `createAsset` and `updateAsset` are callable.** Anything else on the default export is ignored by current consumers. * **Use the passed-in `axios`.** It has the right interceptors / headers / `requestHeaders` injection. Importing your own bloats the bundle and defeats the integration. * **`axios` version is 0.19.2**, not the latest. Don't rely on features added after 0.19.x (`signal`, `AbortController` integration, native ESM exports). See the [axios 0.19.x README](https://github.com/axios/axios/tree/v0.x) for the API of that version. ### Bundle output contract [#bundle-output-contract] `buildDAH` produces a single IIFE **expression** that, when `eval`'d, returns the helper object. For this to work: * The entry file must `export default { createAsset, updateAsset }` (see [Entry file requirements](#entry-file-requirements)). * The default export must be a plain object literal, not the result of a function call, factory, or dynamic computation. Anything you put at the top level runs **once at eval time**, not on every `createAsset` invocation. * Unused imports and dead code are tree-shaken away. Don't reference helpers via dynamic string keys (`obj['my' + 'Helper']()`); the bundler may not see the reference and remove it. ### `define` / `process.env` [#define--processenv] * Only the keys you pass to `buildDAH`'s second argument exist at runtime. Referencing a `process.env.X` that wasn't injected throws `ReferenceError` when the DAH runs. * `define` is a **textual** replacement. Always `JSON.stringify` string values. Objects/arrays passed inline are auto-stringified by Vite, but anything you compute manually must be valid JSON. ### Bundle size [#bundle-size] Everything you import is **inlined** into the IIFE string, then shipped over the wire as part of `capabilities.directAccessHelper`, parsed, and `eval`'d in the browser. Large provider SDKs can blow up the auth/providers payload and slow the panel cold-start. * Prefer tiny, focused utility libs (sub-1 KB). * Hand-roll helpers when feasible (the SDK's `helpers.calcSha1Hash` / `calcSha256Hash` / `getBase64FromString` already cover common cases). * Don't accidentally drag your main `index.ts` into the DAH. See [Best practices](#best-practices) below. ### Host helpers vary between consumers [#host-helpers-vary-between-consumers] The `helpers` object is provided by whoever evaluates the DAH. There are two consumers today: | Consumer | MD5 | `getAccessToken` | `getSessionId` | | ------------------------- | ------------------------------------ | ---------------------- | --------------- | | Production CI HUB Plugins | real (CryptoJS) | CI HUB platform token | real session ID | | SDK Workbench | returns `''` (Web Crypto has no MD5) | same as `getPayload()` | returns `''` | If your DAH genuinely needs MD5 or a separate platform access token, the [SDK Workbench](/integration/getting-started/workbench) will not match production behavior exactly. ## Best practices [#best-practices] ### Architecture [#architecture] 1. **Split shared logic into a small dedicated file.** If your `createAsset` / `updateAsset` share helpers (e.g. an upload helper, a folder-ID normalizer), put them in a small file like `src/dah-utils.ts` that **both** the DAH and your main `index.ts` import. Don't import from `index.ts` itself. Vite will follow the import graph and pull half your integration into the DAH bundle. ``` src/ index.ts ← integration entry (Node-side) dah.ts ← imports only from dah-utils.ts dah-utils.ts ← tiny, browser-safe, shared queries.ts ← GraphQL strings, importable from both ``` 2. **One function for both create and update.** If your create and update logic is similar, write a single `createUpdateAsset` and export it as both. Branch on `data.assetId` (truthy = update). 3. **Export only one if that's all you support.** If your provider only supports direct upload for create, just export `createAsset`. The workbench disables the unsupported direct-access button and surfaces a Problems-panel hint. ### Configuration [#configuration] 4. **Inject server-side config via `define`.** Pass values to `buildDAH`'s second argument and read them as `process.env.X` inside the DAH: ```ts const dahString = await buildDAH(path.join(import.meta.dirname, 'dah.ts'), { 'process.env.REGION_API_URLS': { 'qa-us': REGIONS['qa-us'].apiUrl, 'prod-us': REGIONS['prod-us'].apiUrl, 'prod-eu': config.get('myIntegration.regions.prod-eu.apiUrl') }, 'process.env.GRAPH_BASE_ENDPOINT': JSON.stringify(config.get('myIntegration.graphBaseEndpoint')) }) ``` 5. **Wrap every string value in `JSON.stringify`.** GraphQL queries, URLs, IDs, anything that's a plain string at build time. Objects passed inline don't need this. 6. **Use `helpers.getAdapterData()` for per-connection data.** Values returned by your `login` handler in `adapterData` (per-tenant endpoints, region selection, etc.) are runtime. Read them via `helpers.getAdapterData()` instead of `define`. ### Runtime [#runtime] 7. **Use `payload` as the bearer token.** The 2nd argument is the raw provider access token from your `login` handler. Most providers just need `Authorization: Bearer ${payload}`. 8. **Set `maxContentLength: Infinity`** on axios calls that upload file data. Axios 0.19 rejects large payloads otherwise. 9. **Report progress for large uploads.** Call `onProgress(loaded / total)` inside axios's `onUploadProgress` callback. The UI shows a progress bar **only** when you report it. 10. **Test with real files.** The SDK Workbench passes a real `File` / `Blob` to your DAH, not a base64 string. Use `data.file.size`, `data.file.name`, and `data.file.type` as needed. 11. **Don't rely on MD5 in the workbench.** If you need MD5 for testing, run against the production Vue client instead, or temporarily substitute SHA-1/SHA-256 in your DAH to verify the upload flow end-to-end. ### Common pitfalls [#common-pitfalls] * Wrapping the entry file in `(function() { ... return {...} })()`. Use `export default { ... }` instead. * Passing un-stringified strings to `define`: produces an "Invalid define value" build error. * Importing `axios` directly inside `dah.ts`: causes bundle bloat and wrong interceptors. Use the injected `axios` parameter. * Importing from `index.ts` or any Node-only file: either a Vite build error, or a giant bundle. * Top-level side effects like fetching config, creating clients, etc. They run once at eval time, not per call. Move them inside the handler. *** See [Upload](/integration/building-an-integration/upload) | [Capabilities Reference](/integration/advanced/capabilities-reference) | [CLI Config](/integration/reference/cli#directaccesshelper) | [Bynder Example](/integration/examples/bynder/overview#upload-with-directaccesshelper) # Download (/integration/building-an-integration/download) Most integrations don't need a `download` handler. CI HUB fetches assets directly from the `downloadUrl` returned in asset data. Implement `download` only when the URL requires server-side resolution: signed/temporary URLs, proxy downloads, or protected content that needs a fresh token exchange. CI HUB calls this handler when the plugin needs to download an asset and the integration has registered a download handler. ## Inputs [#inputs] | Field | Description | | ------------------------------ | ------------------------------------------------ | | `requestData.query.assetId` | Asset to download | | `requestData.query.lowres` | `"1"` for low-resolution preview | | `requestData.query.noRedirect` | `"true"` to return JSON instead of HTTP redirect | | `requestData.query.localId` | Optional rendition/conversion ID | You can add additional query parameters when constructing the download URL. ## Response [#response] Two modes based on `noRedirect`: ```ts title="src/index.ts" // Default: redirect the client to the download URL return sendRedirectUri(downloadUrl) // noRedirect=true: return JSON with the URL return sendResult(null, { downloadUrl: `${freshUrl}$NO_AUTH$` }) // [!code highlight] ``` Append `$NO_AUTH$` to the URL when it's pre-signed or publicly accessible. This tells CI HUB not to inject auth headers when fetching. ## Patterns [#patterns] **Example** - DAM with versioned assets, parses compound `assetId::version` format: ```ts title="src/index.ts" download: async (locals, requestData) => { const id = requestData.query.assetId const parts = id.split('::') const assetId = parts[0] const version = parts.length === 2 ? parts[1] : -1 const lowres = requestData.query.lowres === '1' const noRedirect = requestData.query.noRedirect === 'true' try { const downloadUrl = await getDownloadLocation(locals, assetId, version, lowres) return noRedirect ? sendResult(null, { downloadUrl: downloadUrl && `${downloadUrl}$NO_AUTH$` }) : sendRedirectUri(downloadUrl) } catch (err) { return sendError(err, 404) } }, ``` **Example** - DAM with rendition-based downloads: ```ts title="src/index.ts" download: async (locals, requestData) => { const noRedirect = requestData.query.noRedirect === 'true' const assetId = requestData.query.assetId const localId = requestData.query.localId try { const downloadUrl = await getRenditionUrl(locals, assetId, localId) return noRedirect ? sendResult(null, { downloadUrl: downloadUrl && `${downloadUrl}$NO_AUTH$` }) : sendRedirectUri(downloadUrl) } catch (err) { return sendResult(err) } }, ``` **Example** - stock platform, checks availability before redirecting: ```ts title="src/index.ts" download: async (locals, requestData) => { const id = requestData.query.assetId const lowres = requestData.query.lowres === '1' const noRedirect = requestData.query.noRedirect === 'true' try { const downloadUrl = await getDownloadLocation(system, locals, id, lowres) if (!downloadUrl) { return sendError('Download not available', 404) } return noRedirect ? sendResult(null, { downloadUrl: downloadUrl && `${downloadUrl}$NO_AUTH$` }) : sendRedirectUri(downloadUrl) } catch (err) { const msg = (err || '').toString() || 'unexpected error' return sendError(msg, 400) } }, ``` ## URL Suffixes [#url-suffixes] Append suffixes to `thumbnailUrl` and `downloadUrl` in asset data to control how CI HUB authenticates and caches the request. These are processed by CI HUB's URL parser before fetching. | Suffix | Auth behavior | When to use | | -------------------------------- | ---------------------------------------------- | ---------------------------------------- | | `$NO_AUTH$` | No auth added, URL is used as-is | CDN thumbnails, pre-signed S3/Azure URLs | | `$AUTH_PAYLOAD$` | Token appended as query parameter | Legacy APIs with token-in-URL auth | | `$AUTH_PAYLOAD_BEARER$` | `Bearer {token}` as query parameter | Legacy Bearer-in-URL pattern | | `$AUTH_HEADER_PAYLOAD_BEARER$` | `Authorization: Bearer {token}` header | Google Drive, Box, Sitecore | | `$AUTH_HEADER_PAYLOAD_APITOKEN$` | `Authorization: apiToken {token}` header | Admiral Cloud, Picturepark | | `$AUTH_SESSION_ID$` | Session ID injected | Session-based auth | | `$FORCE_DOWNLOAD$` | Forces `Content-Disposition: attachment` | Thumbnail pipeline, forced save | | `$REQUEST_HEADERS$` | Custom headers from `info.requestHeaders` | Picturepark (complex auth headers) | | `$NO_CACHE$` | `Cache-Control: no-cache` header, skip caching | Volatile/expiring URLs | ### Suffix Examples in Asset Data [#suffix-examples-in-asset-data] ```ts title="src/index.ts" // Pre-signed URL, no auth needed thumbnailUrl: `https://cdn.example.com/thumb/abc123.jpg$NO_AUTH$` // [!code highlight] // Bearer token auth via header downloadUrl: `https://api.example.com/assets/123/download$AUTH_HEADER_PAYLOAD_BEARER$` // [!code highlight] // API token auth thumbnailUrl: `https://api.example.com/renditions/456$AUTH_HEADER_PAYLOAD_APITOKEN$` // No caching + no auth (expiring CDN URL) downloadUrl: `https://cdn.example.com/temp/signed-url$NO_AUTH$$NO_CACHE$` // Force download disposition thumbnailUrl: `https://api.example.com/preview/789$FORCE_DOWNLOAD$` ``` Suffixes can be combined. CI HUB strips them from the URL before making the request and applies the corresponding auth/cache behavior. ### How CI HUB Processes Suffixes [#how-ci-hub-processes-suffixes] The auth suffixes are mutually exclusive. CI HUB applies the first match: 1. `$REQUEST_HEADERS$`: parses custom headers from the URL's `headers` query param 2. `$NO_AUTH$`: strips suffix, sends request without auth 3. `$AUTH_PAYLOAD$`: replaces suffix with URL-encoded token 4. `$AUTH_PAYLOAD_BEARER$`: replaces suffix with URL-encoded `Bearer {token}` 5. `$AUTH_HEADER_PAYLOAD_BEARER$`: strips suffix, adds `Authorization: Bearer {token}` header 6. `$AUTH_HEADER_PAYLOAD_APITOKEN$`: strips suffix, adds `Authorization: apiToken {token}` header `$FORCE_DOWNLOAD$`, `$NO_CACHE$`, and `$AUTH_SESSION_ID$` are processed independently and can be combined with any auth suffix. ## UI Behavior [#ui-behavior] * User places/downloads an asset → CI HUB checks for `download` handler * If handler exists → calls it with `assetId`, uses response URL * If no handler → fetches directly from `downloadUrl` in asset data, applying URL suffix auth * `noRedirect=true` used internally for JSON-based URL resolution See [Download Schema](/integration/schemas/assets/download) # Filters (/integration/building-an-integration/filters) Filters let users narrow search and folder results in the plugin UI. They are returned in every `search` and `getFolder` response and **re-rendered after each call**. You rebuild the full filter list every time. ## How It Works [#how-it-works] 1. Your handler returns `result.filters`, an array of filter groups, each with `options`. 2. The UI renders them and sends back **only the IDs** of selected options in `requestData.query.filters[]`. 3. You parse those IDs, apply them to your API call, and return updated filters with `isActive` set correctly on every option. If you don't set `isActive`, the UI won't show what's selected after the next search. ## parseFilters Utility [#parsefilters-utility] The SDK exports `parseFilters` from `@ci-hub/integration-sdk`, a utility for single-select filters: ```ts import { parseFilters } from '@ci-hub/integration-sdk' parseFilters(['status:active', 'order:newest']) // → { status: 'active', order: 'newest' } ``` `parseFilters` splits each string on `:` and builds a `Record`. It works for single-select filters where each key has one value. If the same key appears multiple times, the last value wins. ### multi$ Prefix [#multi-prefix] For multi-select filters, prefix the filter key with `multi$` in the option ID. The SDK's built-in `parseFilters` does **not** handle `multi$`. Use the custom parser shown in the canonical example below. Strip `multi$` from the key and collect values into an array. ## Static Filters: Canonical Example [#static-filters-canonical-example] This is the standard pattern for filters with known, fixed options: ```ts const activeFilters: string[] = requestData.query.filters || [] const parseFilters = (filters: string[]) => filters.reduce((acc: Record, filter: string) => { const [key, value] = filter.split(':') if (key.startsWith('multi$')) { const multiKey = key.replace('multi$', '') acc[multiKey] = acc[multiKey] || [] ;(acc[multiKey] as string[]).push(value) } else { acc[key] = value } return acc }, {}) const parsedFilters = parseFilters(activeFilters) const buildStaticFilters = (parsedFilters: Record) => [ { id: 'status', name: 'Status', type: 'SELECT', options: [ { id: 'status:active', name: 'Active', isActive: parsedFilters.status === 'active' }, { id: 'status:archived', name: 'Archived', isActive: parsedFilters.status === 'archived' }, { id: 'status:draft', name: 'Draft', isActive: parsedFilters.status === 'draft' }, ], }, { id: 'mediaType', name: 'Media Type', type: 'SELECT', options: [ { id: 'multi$mediaType:image', name: 'Image', isActive: (parsedFilters.mediaType || []).includes('image') }, { id: 'multi$mediaType:video', name: 'Video', isActive: (parsedFilters.mediaType || []).includes('video') }, { id: 'multi$mediaType:document', name: 'Document', isActive: (parsedFilters.mediaType || []).includes('document') }, ], }, ] ``` Key points: * Single-select (`status`): option ID is `key:value`, compare with `===` * Multi-select (`mediaType`): option ID is `multi$key:value`, compare with `.includes()` * Every option has `isActive` set, even when `false` ## Dynamic Filters from API [#dynamic-filters-from-api] When filter options come from API responses (facets, categories, etc.), build the filter array dynamically. For example, this integration converts API facets into CI HUB filters: ```ts const encodeId = (str) => { if (!str) return '' const encoded = str.replace(/[^A-Za-z0-9\-_:.]/g, char => `_x${char.charCodeAt(0).toString(16).padStart(4, '0')}_` ) return `id_${encoded}` } const decodeId = (encodedStr) => { return encodedStr .replace(/^id_/, '') .replace(/_x([0-9a-f]{4})_/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)) ) } const getFiltersFromFacets = (activeFiltersJson = {}, facets = {}) => { const filters = [] Object.keys(facets) .filter(key => facets[key].buckets?.length > 0) .forEach(key => { filters.push({ id: encodeId(key), name: key, options: facets[key].buckets.filter(bucket => bucket.key).map(bucket => ({ id: `${encodeId(key)}:${encodeId(bucket.key)}`, name: bucket.key, count: bucket.doc_count, isActive: activeFiltersJson[encodeId(key)] === encodeId(bucket.key) })) }) }) return filters.filter(filter => filter.options.length > 0 && filter.id) } ``` This integration also converts selected filters back into API query terms: ```ts const filtersToTerms = (activeFiltersJson = {}) => { const terms = [] Object.keys(activeFiltersJson).forEach(key => { if (key.startsWith('id_')) { const filterKey = decodeId(key) const filterValue = decodeId(activeFiltersJson[key]) if (filterValue && filterKey) { terms.push(`(${filterKey}:"${filterValue}")`) } } }) return terms } ``` Notice the `encodeId`/`decodeId` pattern. Because the API returns facet names with spaces and special characters, the integration encodes them into safe HTML IDs and decodes them back when building API queries. ## Conditional Filters [#conditional-filters] This integration pre-defines all possible filters and uses guard functions to show/hide them based on context (search type, asset type, config flags): ```ts const allFilters = [ { ...assetTypeFilter, guard: (searchType) => searchType === 'text' || searchType === 'collection', singleOption: true }, { id: 'order', name: 'Sort Order', type: 'SELECT', options: [ { id: 'order:best_match', name: 'Best Match' }, { id: 'order:newest', name: 'Newest' }, { id: 'order:oldest', name: 'Oldest' }, ] }, // ... more filters ] // In search handler: const filters = allFilters.filter(filter => { if (filter.guard) return filter.guard(searchType, assetType) return true }) for (const filter of filters) { for (const option of filter.options) { const [key, value] = option.id.split(':') option.isActive = filterOptions[key] === value } } result.filters = filters ``` Some filter options are populated dynamically (from API artist/event facets) while the filter structure itself is predefined. ## ID Rules [#id-rules] All filter and option IDs must be **unique** and valid **HTML id attributes**. Avoid separator conflicts: if you use `:` as your ID separator (the standard pattern) but your API returns dynamic IDs containing `:`, your parsing will break. The `encodeId`/`decodeId` pattern from the dynamic filters example above solves this. ## Pre-search Filters [#pre-search-filters] Filters returned from the `info` handler are **pre-search filters**, set once when the integration initializes, not updatable during search. Use them only for filters that apply universally (e.g., a global content-type toggle). For anything that depends on search context, return filters from `search`/`getFolder` instead. ## Pagination and Subfolders [#pagination-and-subfolders] The `more` parameter in `search` and `getFolder` responses is for **assets only**. For subfolders, fetch all subfolders in a loop before returning. The UI does not paginate subfolders. *** [Search Schema](/integration/schemas/assets/search) | [Info Schema](/integration/schemas/assets/info) # Folder Navigation (/integration/building-an-integration/folder-navigation) `getFolder` returns the contents of a folder: subfolders, assets, filters, and a pagination cursor. CI HUB calls it when the user clicks a folder in the plugin UI, starting with `folderId = "root"` at the top level. ## Inputs [#inputs] | Field | Description | | ---------------------------- | ------------------------------------------------ | | `requestData.query.folderId` | Folder ID to open. `"root"` for top level | | `requestData.query.size` | Page size (max assets per page) | | `requestData.query.more` | Pagination cursor from previous response | | `requestData.query.filters` | Active filter selections (same format as search) | ## Response [#response] Same shape as search: ```ts { id: string, // echo back the folderId name: string, // display name folders: Folder[], // subfolders assets: Asset[], // assets in this folder filters: Filter[], // available filters for this folder more: number | string | undefined, // pagination cursor for next page, undefined = last page capabilities: FolderCapabilities, // what operations are allowed totalAssetsCount?: number } ``` `more` applies to **assets only**. Always return all subfolders in a single response (see [Subfolder Pagination](#subfolder-pagination)). ## Hardcoded Root Folders [#hardcoded-root-folders] Some integrations define virtual root folders that map to different API endpoints or content types. **Example** - boards, collections, and license categories: ```ts getFolder: async (locals, requestData) => { try { const folderNames = { 'all': 'All content', 'downloads': 'Downloaded content', 'boards': 'Boards', 'collections': 'Collections', 'licensed': 'Licensed Assets', 'videos:creative': 'Creative', 'videos:editorial': 'Editorial', 'images:creative': 'Creative', 'images:editorial': 'Editorial' } const folderId = requestData.query.folderId || 'root' const page = Number.parseInt(requestData.query.more || 0, 10) const size = Math.min(Number.parseInt(requestData.query.size || 50, 10), config.get('maxQuerySize')) let result = { folders: [], assets: [], more: undefined, capabilities: defaultFolderCapabilities } if (folderId === 'root') { result.folders = Object.keys(folderNames) .filter(folder => !['videos:creative', 'videos:editorial', 'images:creative', 'images:editorial'].includes(folder)) .map(folder => ({ id: folder, name: folderNames[folder], uploadUrl: '' })) } // ... handle each folder type } } ``` **Example** - DAM integration with collections, assets, work-in-progress, projects, and entities: ```ts getFolder: async (locals, requestData) => { try { let size = Math.min(parseInt(requestData.query.size || 50, 10), config.get('maxQuerySize')) const more = parseInt(requestData.query.more || 0, 10) || 0 const facetQuery = getFilterQuery(requestData.query) const folderCapabilities = await getFolderCapabilities(locals) const { canAddAsset, canAddFolder, canDeleteFolder } = folderCapabilities const result = { id: `${requestData.query.folderId}`, name: `${requestData.query.folderId}`, more: undefined, assets: [], folders: [], filters: [], capabilities: { ...defaultFolderCapabilities, canAddAsset }, totalAssetsCount: 0 } if (requestData.query.folderId === 'root') { result.folders = [ { id: 'collections', name: 'Collections' }, { id: 'assets', name: 'Assets' }, { id: 'wip', name: 'Work In Progress' }, { id: 'projects', name: 'Projects' }, { id: 'entities', name: 'Entities' } ] } // ... handle each folder type with different API calls and query configs } } ``` ## Folder ID Prefixing [#folder-id-prefixing] When an integration exposes multiple content types (libraries, collections, boards), use prefixed IDs to route to the correct API in subsequent `getFolder` calls. **Example** - DAM with libraries and collections: ```ts getFolder: async (locals, requestData) => { try { const folderId = (requestData.query.folderId as string).toString() const size = Math.min(parseInt((requestData.query.size as string) || '25', 10), config.get('maxQuerySize')) const more = parseInt((requestData.query.more as string) || '1', 10) const { brandId } = locals.adapterData const result: any = { id: folderId, assets: [], folders: [], filters: [], capabilities: { ...defaultFolderCapabilities, ...defaultAssetCapabilities }, more: undefined, totalAssetsCount: 0 } if (folderId === 'root') { const libraries = await callApi(locals, { query: queries.getGetBrandLibrariesQuery, variables: { brandId, page: more, limit: size } }) // Prefix library IDs so getFolder can route back to the library API result.folders = libraries.data.brand.libraries.items.map( (library: any) => ({ id: `library:${library.id}`, name: library.name }) ) result.more = libraries.data.brand.libraries.hasNextPage ? more + 1 : undefined } else if (folderId.startsWith('library:')) { const libraryId = folderId.replace('library:', '') const assetsRes = await callApi(locals, { query: queries.getGetLibraryAssetsQuery, variables: { libraryId, page: more, limit: size } }) const { library } = assetsRes.data const { browse, collections, currentUserPermissions } = library result.assets = extractAssetsData(locals, browse.assets.items) result.more = browse.assets.hasNextPage ? more + 1 : undefined result.folders = browse.folders.items?.map( (folder: any) => ({ id: `${folder.id}`, name: folder.name }) ) if (collections.total > 0) { result.folders.push({ id: `collections:${libraryId}`, name: 'Collections' }) } result.capabilities.canAddFolder = true result.capabilities.canAddAsset = currentUserPermissions.canCreateAssets } else if (folderId.startsWith('collections:')) { const libraryId = folderId.replace('collections:', '') const collections = await callApi(locals, { query: queries.getGetLibraryCollectionsQuery, variables: { libraryId } }) result.folders = collections.data.library.collections.items.map( (collection: any) => ({ id: `collection:${collection.id}`, name: collection.name }) ) } else if (folderId.startsWith('collection:')) { const collectionId = folderId.replace('collection:', '') const assets = await callApi(locals, { query: queries.getCollectionAssetsQuery, variables: { collectionId, page: more, limit: size } }) const canDeleteAsset = assets.data.node.currentUserPermissions.canRemoveAssets || false result.assets = extractAssetsData(locals, assets.data.node.assets.items, { canDeleteAsset }) result.more = assets.data.node.assets.hasNextPage ? more + 1 : undefined } // ... return send(result) } } ``` The prefix → API routing pattern: `library:abc` → Libraries API, `collection:xyz` → Collections API, `board:123` → Boards API. **Example** - uses the same approach for boards and collections: ```ts } else if (folderId === 'boards') { const boards = await getBoards(system, locals) for (const board of boards.boards) { result.folders.push({ id: `board:${board.id}`, name: board.name, uploadUrl: '' }) } } else if (folderId === 'collections') { const collections = await getCollections(system, locals) collections.collections.forEach(collection => { result.folders.push({ id: `collection:${collection.code};${collection.asset_family}`, name: collection.name, uploadUrl: '' }) }) } else if (folderId.startsWith('board:')) { const id = folderId.substring(6) const board = await getBoard(system, locals, id) if (board.ids.length > 0) { result = await getAssets(system, locals, board.ids, undefined, undefined, undefined, `/Boards/${board.name}`, page, size) } } else if (folderId.startsWith('collection:')) { const id = folderId.substring(11) result = await getAssets(system, locals, undefined, id, undefined, undefined, `/Collections/${id.split(';')[0]}`, page, size) } ``` ## Subfolder Pagination [#subfolder-pagination] `more` in the response only applies to assets. Always fetch **all** subfolders. Use a while-loop if the platform paginates folder listings: ```ts let allFolders = [] let folderPage = 1 let hasMore = true while (hasMore) { const res = await callApi(locals, { query: queries.getSubfolders, variables: { folderId, page: folderPage, limit: 100 } }) allFolders = allFolders.concat(res.data.folders.items) hasMore = res.data.folders.hasNextPage folderPage++ } result.folders = allFolders.map(f => ({ id: f.id, name: f.name })) result.more = assetsResponse.hasNextPage ? nextAssetCursor : undefined ``` If the API requests to get all subfolders are costly and slow, you can return all subfolders only in the first getFolder call. in the first `getFolder` call you will have `more = undefined`. example: ```ts getFolder: async (locals, requestData) => { try { const more = requestData.query.more if (!more) { // get all subfolders } return send(result) } } ``` This works because the CI HUB plugin will merge the results of the first `getFolder` call with the results of the subsequent `getFolder` calls. ## Per-Folder Capabilities [#per-folder-capabilities] Spread `defaultFolderCapabilities` and override per folder type. The defaults are all `false`: ```ts import { defaultFolderCapabilities, defaultAssetCapabilities } from '@ci-hub/integration-sdk' // defaultFolderCapabilities = { canDeleteFolder: false, canAddFolder: false, canAddAsset: false } // defaultAssetCapabilities = { canDeleteAsset: false, canUpdateAsset: false, canLockAsset: false, canUnlockAsset: false } ``` Override capabilities based on the folder type and user permissions: ```ts // Read-only folder (boards listing) result.capabilities = defaultFolderCapabilities // Writable folder with upload result.capabilities = { ...defaultFolderCapabilities, canAddFolder: true, canAddAsset: currentUserPermissions.canCreateAssets } // Full permissions subfolder result.capabilities = { ...defaultFolderCapabilities, canAddFolder: true, canAddAsset: true, canDeleteFolder: true, canDeleteAsset: true, canUpdateAsset: true } ``` ## UI Behavior [#ui-behavior] * `folderId = "root"` → CI HUB shows the top-level folder list after login * Clicking a folder → calls `getFolder` with that folder's `id` * `folders` array → rendered as clickable folder items * `assets` array → rendered as asset thumbnails/list items * `more` defined → "Load More" button appears, clicks send `more` value back * `capabilities.canAddAsset = true` → upload button appears in folder * `capabilities.canAddFolder = true` → "New Folder" option appears See [Get Folder Schema](/integration/schemas/folders/get-folder) | [Create Folder Schema](/integration/schemas/folders/create-folder) # Folder Operations (/integration/building-an-integration/folder-operations) Handlers for creating, deleting, renaming, and moving folders. Each requires a capability flag returned from `getFolder` in the folder's `capabilities` object. ## Capability Flags [#capability-flags] Return these per-folder in `getFolder` response: ```ts return send({ id: folderId, folders: [...], assets: [...], capabilities: { canCreateFolder: true, canDeleteFolder: true, canRenameFolder: true, canMoveFolder: true } }) ``` Capabilities are per-folder. Some folders (root, virtual containers) may disable operations that others allow. ## createFolder [#createfolder] Creates a new folder inside the specified parent. ### Inputs [#inputs] | Field | Description | | --------------------------- | ---------------- | | `requestData.body.name` | New folder name | | `requestData.body.parentId` | Parent folder ID | ### Response [#response] ```ts return send({ id: newFolderId, name: folderName }) ``` ### Patterns [#patterns] **Example** - DAM that supports both library folders and collections: ```ts createFolder: async (locals, requestData) => { try { const result = { id: '', name: '' } let { name, parentId } = requestData.body parentId = !folderIdStartsWith(parentId || '', [ 'root', 'collection:' ]) ? parentId : undefined if (!parentId) { throw new Error('You can not create a folder in this location') } if (parentId.startsWith('collections:')) { parentId = parentId.replace('collections:', '') const collection = await callApi(locals, { query: queries.createCollectionMutation, variables: { input: { name, parentId } } }) result.id = `collection:${collection.data.createCollection.collection.id}` result.name = collection.data.createCollection.collection.name } else { parentId = parentId.replace('library:', '') const folder = await callApi(locals, { query: queries.createFolderMutation, variables: { input: { name, parentId } } }) result.id = folder.data.createFolder.folder.id result.name = folder.data.createFolder.folder.name } return send(result) } catch (error) { return sendError(error, 400) } }, ``` **Example** - DAM that supports path-based folder creation: ```ts createFolder: async (locals, requestData) => { try { const { parentId, name } = requestData.body const parentPath = parentId === 'root' ? '' : (await callApi(locals, 'POST', '/files/get_metadata', null, { path: parentId })).path_lower const folderCreateResponse = await callApi(locals, 'POST', '/files/create_folder_v2', null, { path: `${parentPath}/${name}` }) return sendResult(null, { id: folderCreateResponse.metadata.id, name: folderCreateResponse.metadata.name }) } catch (err) { return sendError(err, 400) } }, ``` ### UI Behavior [#ui-behavior] On success, the new folder appears in the current folder view. The plugin UI uses the returned `id` and `name` for display. [Create Folder Schema](/integration/schemas/folders/create-folder) *** ## deleteFolder [#deletefolder] Permanently removes a folder. Some platforms recursively delete contents; others require the folder to be empty. ### Inputs [#inputs-1] | Field | Description | | ----------------------------- | ------------------- | | `requestData.params.folderId` | Folder ID to delete | ### Response [#response-1] ```ts return sendStatus(200) ``` ### Patterns [#patterns-1] **Example** - DAM that handles collection and folder types, blocks deletion of root-level folders: ```ts deleteFolder: async (locals, requestData) => { try { const { folderId } = requestData.params const id = folderIdStartsWith(folderId, [ 'root', 'collections', 'library' ]) ? undefined : folderId if (!id) { throw new Error('You can not delete this folder') } if (folderId.startsWith('collection:')) { const collectionId = folderId.replace('collection:', '') await callApi(locals, { query: queries.deleteCollectionMutation, variables: { input: { collectionId } } }) } else { await callApi(locals, { query: queries.deleteFolderMutation, variables: { input: { ids: [ id ] } } }) } return sendStatus(200) } catch (error) { return sendError(error, 400) } }, ``` **Example** - DAM that supports path-based deletion: ```ts deleteFolder: async (locals, requestData) => { try { const { folderId } = requestData.params await callApi(locals, 'POST', '/files/delete_v2', null, { path: folderId }) return sendResult(null) } catch (err) { return sendError(err, 400) } }, ``` Protect virtual/root folder IDs from deletion. Check the `folderId` against known non-deletable values before calling the platform API. ### UI Behavior [#ui-behavior-1] On success, the folder disappears from the parent folder view. [Delete Folder Schema](/integration/schemas/folders/delete-folder) *** ## renameFolder [#renamefolder] Changes a folder's display name. ### Inputs [#inputs-2] | Field | Description | | ----------------------------- | ----------- | | `requestData.params.folderId` | Folder ID | | `requestData.body.name` | New name | ### Response [#response-2] ```ts return send({ id: folderId, name: newName }) ``` ### Patterns [#patterns-2] **Example** - DAM that supports both collections and library folders: ```ts renameFolder: async (locals, requestData) => { try { const { name } = requestData.body const { folderId } = requestData.params const id = folderIdStartsWith(folderId, [ 'root', 'collections', 'library' ]) ? undefined : folderId if (!id) { throw new Error('You can not rename this folder') } const result = { id: '', name: '' } if (folderId.startsWith('collection:')) { const collectionId = folderId.replace('collection:', '') const collection = await callApi(locals, { query: queries.updateCollectionMutation, variables: { input: { id: collectionId, data: { name } } } }) result.id = collection.data.updateCollection.collection.id ? `collection:${collection.data.updateCollection.collection.id}` : folderId result.name = collection.data.updateCollection.collection.name || name } else { const folder = await callApi(locals, { query: queries.updateFolderMutation, variables: { input: { id, data: { name } } } }) result.id = folder.data.updateFolder.folder.id || folderId result.name = folder.data.updateFolder.folder.name || name } return send(result) } catch (error) { return sendError(error, 400) } }, ``` **Example** - DAM that supports JSON Patch: ```ts renameFolder: async (locals, requestData) => { const { folderId } = requestData.params const { name } = requestData.body try { await callApi(locals, 'PATCH', `/categories/${folderId}`, null, [{ op: 'replace', path: '/tree/name', value: name }]) return send({ id: folderId, name }) } catch (err) { return sendError(err, 400) } }, ``` ### UI Behavior [#ui-behavior-2] On success, the folder's name updates in the folder tree and breadcrumbs. [Rename Folder Schema](/integration/schemas/folders/rename-folder) *** ## moveFolder [#movefolder] Moves a folder to a different parent folder. ### Inputs [#inputs-3] | Field | Description | | --------------------------------- | ---------------------------- | | `requestData.body.folderId` | Folder ID to move | | `requestData.body.targetParentId` | Destination parent folder ID | ### Response [#response-3] ```ts return send({ id: folderId, targetParentId }) ``` ### Patterns [#patterns-3] **Example** - DAM that supports JSON Patch to update parent: ```ts moveFolder: async (locals, requestData) => { try { const { folderId, targetParentId } = requestData.body if (typeof targetParentId !== 'string' || !targetParentId || targetParentId.startsWith('lightbox') || [ 'root', 'categories', 'lightboxes', 'home', 'mostViewed', 'recentlyUploaded' ].includes(targetParentId)) { return sendError('Invalid folder ID', 400) } await callApi(locals, 'PATCH', `/categories/${folderId}`, null, [{ op: 'replace', path: '/parentId', value: targetParentId }]) return send({ id: folderId, targetParentId }) } catch (err) { return sendError(err, 400) } }, ``` Validate `targetParentId` before calling the API. Virtual folder IDs (`root`, `lightboxes`, etc.) are not valid move destinations. ### UI Behavior [#ui-behavior-3] On success, the folder disappears from its current location and appears under the target parent. Enable via `canMoveFolder: true` in the folder's capabilities. [Move Folder Schema](/integration/schemas/folders/move-folder) # Info Handler (/integration/building-an-integration/info-handler) Called after successful login. Returns integration metadata and optional pre-configuration that shapes the plugin UI for this connection. ```ts info?: (locals: Locals) => HandlerResult ``` CI HUB calls `info` once after a successful login (and after `checkToken` on reconnect). The response configures filters, locale pickers, upload options, and other UI elements for the duration of the session. ## Response [#response] Return via `sendResult`: ```ts return sendResult(null, { remoteSystemPrefix: 'dam.example.com', // all other fields optional }) ``` ### `remoteSystemPrefix` (required) [#remotesystemprefix-required] Base URL hostname of the remote system. CI HUB uses this to build "open in source system" links on assets. Typically derived from the user's connection endpoint: ```ts const remoteSystemPrefix = (locals: Locals) => new URL(locals.adapterData.resourceEndpoint).hostname ``` ### `filters` [#filters] Pre-search filters. Dropdown menus shown in the plugin UI **before** the user triggers a search. Set once at login, **not updatable during search**. Use only for always-applicable filters like "Library" or "Search Operation". Each filter has an `id`, `name`, and `options` array. Option IDs use the `filterId:value` convention: ```ts const filters = [ { id: 'library', name: 'Library', options: [ { id: 'library:all', name: 'All Libraries' }, { id: 'library:123', name: 'Brand Assets' }, { id: 'library:456', name: 'Marketing' }, ] } ] ``` Options support `default: true` to pre-select, `isDisabled` to gray out, and `isActive` for toggling. Supports `i18nName` for localized display names. These filters are static for the session. For filters that change based on search results (facets), use dynamic filters in the [search handler](/integration/building-an-integration/search). ### `dataLocales` [#datalocales] Locale picker options shown in the plugin UI. Each locale has an `id`, optional `name`/`displayName`, and an optional `default` flag: ```ts const dataLocales = [ { id: 'en', name: 'en', default: true }, { id: 'de', name: 'de' }, { id: 'fr', name: 'fr' }, ] ``` The selected locale is passed to subsequent handler calls (e.g. search) so the integration can return localized metadata. ### `createAssetOptions` / `updateAssetOptions` [#createassetoptions--updateassetoptions] Extra form fields shown in the plugin UI during upload (create) or re-upload (update). Each option defines an input with type `select`, `string`, or `date`: ```ts const createAssetOptions = [ { id: 'metadataTemplateId', name: 'Metadata Template', options: [ { id: 'metadataTemplateId:tmpl_1', name: 'Product Photography' }, { id: 'metadataTemplateId:tmpl_2', name: 'Marketing Campaign' }, ] }, { id: 'securityTemplateId', name: 'Security Template', options: [ { id: 'securityTemplateId:sec_1', name: 'Internal Only' }, { id: 'securityTemplateId:sec_2', name: 'Public' }, ] } ] ``` The user's selection is passed to the `createAsset`/`updateAsset` handler in `requestData.body`. ### `nativeFolderOrder` [#nativefolderorder] If `true`, CI HUB displays folders in the order returned by the provider API instead of sorting alphabetically. Use when the source system has meaningful ordering (custom sort, priority-based). ### `customMetadata` [#custommetadata] Metadata field definitions used for detail panels and filter configurations. Contains `groups` (grouping headers) and `fields` (individual metadata fields, optionally assigned to a group via `groupId`). See [Custom Metadata](/integration/advanced/custom-metadata) for full details. ### `searchConfigs` [#searchconfigs] Multiple search mode configurations. Adds configuration dropdowns to the search UI. `searchQueryRequired: true` prevents searching without a query string. ```ts const searchConfigs = { searchQueryRequired: false, configs: [ { id: 'single:searchMode', name: 'Search Mode', i18nName: { en: 'Search Mode' }, type: 'select', options: [ { id: 'all', name: 'All', isActive: false }, { id: 'any', name: 'Any', isActive: false }, { id: 'exact', name: 'Exact', isActive: false }, { id: 'default', name: 'Default', isActive: true }, ] } ] } ``` ### `requestHeaders` [#requestheaders] Custom HTTP headers the CI HUB client sends when making direct requests to asset URLs (thumbnails, downloads). Use when the provider requires authentication or cache-control headers on asset URLs: ```ts requestHeaders: { 'X-AdmiralCloud-ClientId': 'your-client-key', 'Cache-Control': 'no-cache' } ``` ### `transformation` [#transformation] Transformation config for integrations that support on-the-fly asset transformations (e.g. Cloudinary). Contains URLs for fetching available transformations and executing them: ```ts const transformation = { availableTransformationsUrl: `${adapterBaseUrl}/getAvailableTransformations`, actionUrl: `${adapterBaseUrl}/doTransformation` } ``` ### `showPdfPreviewOptions` [#showpdfpreviewoptions] If `true`, shows PDF preview options in the plugin UI. ### `assetSearchHelpUrl` [#assetsearchhelpurl] URL linking to external documentation about the provider's search syntax. Shown as a help link in the search UI. ## Patterns [#patterns] ### Example - Filters from API data [#example---filters-from-api-data] Fetches brand libraries from the API and builds a pre-search filter: ```ts info: async (locals) => { try { const { brandId } = locals.adapterData const libraries = await callApi(locals, { query: queries.getGetBrandLibrariesQuery, variables: { brandId, page: 1, limit: 100 } }) const libraryFilter = { id: 'library', name: 'Library', options: [{ id: 'library:all', name: 'All Libraries' }].concat(libraries.data.brand.libraries.items.map((library: any) => ({ id: `library:${library.id}`, name: library.name }))) } return sendResult(null, { remoteSystemPrefix: remoteSystemPrefix(locals), filters: [ libraryFilter ] }) } catch (error) { return sendError(`Error getting info: ${error}`, 400) } } ``` ### Example - createAssetOptions from metadata templates [#example---createassetoptions-from-metadata-templates] Fetches metadata and security templates from the API, builds upload form options dynamically: ```ts info: async (locals) => { try { const createAssetOptions = [] const filters = [ { id: 'searchOperation', name: 'Operation', options: [ { id: 'operation:AND', name: 'AND' }, { id: 'operation:OR', name: 'OR' } ] }, { id: 'searchField', name: 'Search Field', options: [ { id: 'keywordSearchField:all', name: 'Everything', default: true }, { id: 'keywordSearchField:filename', name: 'File Name' }, { id: 'keywordSearchField:assetId', name: 'Asset ID' }, { id: 'keywordSearchField:metadata', name: 'Metadata' }, { id: 'keywordSearchField:content', name: 'Content' } ] } ] const metadata = await callApi(locals, 'GET', '/v1/metadata/template') const security = await callApi(locals, 'GET', '/v1/security/template') const optionalMetadata = metadata.filter(templateTypeFilter).filter(nonRequired) if (optionalMetadata.length > 0) { createAssetOptions.push({ id: 'metadataTemplateId', name: 'Metadata Template', options: optionalMetadata.map(item => ({ id: `metadataTemplateId:${item.templateId}`, name: item.templateName })) }) } if (security?.length > 0) { createAssetOptions.push({ id: 'securityTemplateId', name: 'Security Template', options: security?.map(item => ({ id: `securityTemplateId:${item.templateId}`, name: item.templateName })) }) } return sendResult(null, { remoteSystemPrefix: remoteSystemPrefix(locals), filters, createAssetOptions }) } catch (error) { return sendError(error, 400) } } ``` ### Example - dataLocales and customMetadata [#example---datalocales-and-custommetadata] Fetches available locales from the API and builds custom metadata field definitions: ```ts info: async (locals) => { let customMetadata let dataLocales const availableLocales = await getAvailableLocales(locals, locals.authPayload) dataLocales = availableLocales.supportedLocals. split(','). map(locale => locale.trim()). map(locale => ({ id: locale, name: locale, default: locale === availableLocales.defaultLocale })) try { customMetadata = { fields: [], groups: [] } const uiLocale = await getUiLocale(locals, locals.authPayload) const customFieldClient = await createSoapClient(locals && locals.authPayload, 'apiCustomFieldService') const customFieldsMapping = await getCustomFieldMapping(customFieldClient) customMetadata.fields = [ { id: 'assetType', name: translate('File Category', uiLocale) }, { id: 'mediaTypeName', name: translate('Asset Type', uiLocale) }, { id: 'assetAvailability', name: translate('Asset Availability', uiLocale) } ] customFieldsMapping.forEach(customFieldMap => { const { id: groupId, name: groupName } = customFieldMap.attributes customMetadata.groups.push({ id: groupId, name: groupName }) customFieldMap.CustomField.forEach(customField => { const fieldId = customField.attributes.id const fieldName = getCustomFieldName(customFieldsMapping, fieldId, uiLocale) customMetadata.fields.push({ id: `${fieldId}`, name: fieldName, groupId }) }) }) } catch { // Suppress errors, custom metadata is optional } return sendResult(null, { remoteSystemPrefix: remoteSystemPrefix(locals.authPayload), showPdfPreviewOptions: true, dataLocales, customMetadata }) } ``` ## UI Behavior [#ui-behavior] | Field | Plugin UI Effect | | ----------------------- | -------------------------------------------------------- | | `remoteSystemPrefix` | "Open in source" links on assets | | `filters` | Dropdown menus above search results (static for session) | | `dataLocales` | Language picker in the plugin toolbar | | `createAssetOptions` | Extra form fields in the upload dialog | | `updateAssetOptions` | Extra form fields in the re-upload dialog | | `nativeFolderOrder` | Folders keep provider ordering instead of A–Z sort | | `customMetadata` | Metadata panels on asset details, filter options | | `searchConfigs` | Configuration dropdowns in the search bar | | `requestHeaders` | Sent with every direct asset URL request | | `transformation` | Enables transformation UI (Cloudinary) | | `showPdfPreviewOptions` | Shows PDF preview toggles | [Info Schema](/integration/schemas/assets/info) | [Custom Metadata](/integration/advanced/custom-metadata) # Login Flow (/integration/building-an-integration/login-flow) The `login` handler authenticates the user and returns tokens + adapterData to CI HUB. CI HUB calls it when the user clicks **Connect** in the plugin UI. ## `supportsNewLoginUrl` [#supportsnewloginurl] Declare whether CI HUB should use the unified login endpoint when starting a connection. Set this in your integration `capabilities` (returned from `info`). The SDK default is `false` when omitted. **Recommended:** set `supportsNewLoginUrl: true` for new integrations. | Value | CI HUB login URL | | ----------------- | ------------------------------ | | `true` | `/api/v1/auth/login` | | `false` (default) | `/api/v1/auth/login/:provider` | ```ts title="src/index.ts" capabilities: { category: CategoryEnum.DAM, supportsNewLoginUrl: true, // [!code ++] // ... } ``` ### CI HUB redirect URI allowlist [#ci-hub-redirect-uri-allowlist] Configure redirect URI allowlists at the DAM (or your identity provider) so these CI HUB origins are permitted. This is the same list used for [Direct Access Helper](/integration/building-an-integration/direct-access-helper#cors): ``` https://app-aagcgsdkbdg.canva-apps.com https://app-aagppabnsou.canva-apps.com https://live.ci-hub.com https://stage.ci-hub.com https://dev.ci-hub.com https://ci-hub.azurewebsites.net https://ci-hub-test.azurewebsites.net https://ci-hub-beta.azurewebsites.net http://localhost:8080 https://localhost:8080 ``` Include the full URL that matches the desired login URL, e.g. `http://localhost:8080/api/v1/auth/login` when `supportsNewLoginUrl` is `true`, or `http://localhost:8080/api/v1/auth/login/:INTEGRATION_NAME` when `supportsNewLoginUrl` is `false`. ## `sendAccessToken` [#sendaccesstoken] ```ts sendAccessToken(error?, accessToken?, expiresIn?, refreshToken?, refreshExpiresIn?, adapterData?) ``` | Parameter | Type | Description | | ------------------ | ------------------------- | ---------------------------------------------------------------------------------------------- | | `error` | `string \| null` | Error message. If set, login fails and the plugin UI shows the message | | `accessToken` | `string` | Token (or credential object) stored and passed to all future handlers via `locals.authPayload` | | `expiresIn` | `number` | Token lifetime in seconds | | `refreshToken` | `string` | Refresh token for `refreshToken` handler | | `refreshExpiresIn` | `number` | Refresh token lifetime in seconds | | `adapterData` | `Record` | Persisted object available in every future handler call via `locals.adapterData` | Pass the same type config as `defineIntegration` to type `adapterData` and OAuth state helpers instead of using manual casts. See [Auth helpers](/integration/advanced/typed-integrations#auth-helpers). ## adapterData [#adapterdata] The `adapterData` object is persisted across all future handler calls. Access it via `locals.adapterData`. Typical fields: `resourceEndpoint`, `orgId`, `brandId`, API base URLs, anything your handlers need that isn't the auth token itself. ## State Management [#state-management] OAuth flows require multiple redirects. State helpers persist data across them: ```ts title="src/index.ts" const state = await getStateCodeAsync() await setStateAdapterDataAsync(state, { serverUrl, verifier }) const { serverUrl } = await getStateAdapterDataAsync(state) ``` | Function | Description | | --------------------------------------- | --------------------------------------------------------- | | `getStateCodeAsync()` | Generates a random state code | | `setStateAdapterDataAsync(state, data)` | Persists data keyed to the state code, survives redirects | | `getStateAdapterDataAsync(state)` | Retrieves the persisted data | ## `render(template, data)` [#rendertemplate-data] Renders an ECT template to show login forms to the user. The first argument is the template path without `.ect` extension. See [Login Templates](/integration/templates/overview). ```ts title="src/index.ts" return render(path.join(import.meta.dirname, 'select-serverurl'), { title: 'Select Portal', action: urlObject.toString(), serverUrl: defaultUrl, logo, contact }) ``` ## `sendRedirectUri(url)` [#sendredirecturiurl] Redirects the user's browser to an external URL, typically an OAuth authorization endpoint. ```ts title="src/index.ts" return sendRedirectUri(authUrl) ``` ## Error Handling [#error-handling] Pass an error string as the first argument to `sendAccessToken`. The plugin UI displays it to the user. ```ts title="src/index.ts" return sendAccessToken('Invalid credentials') ``` ## Patterns [#patterns] ### OAuth + server URL form [#oauth--server-url-form] User selects a server URL via a rendered form, then is redirected to the OAuth provider. After authorization, the code is exchanged for tokens. Template (`select-serverurl.ect`): ```html title="src/select-serverurl.ect" <% extend 'login-template.ect' %>

Please enter the URL to your INTEGRATION_NAME portal.


``` Handler: ```ts title="src/index.ts" login: async (locals, requestData) => { const code = requestData.query.code const authError = requestData.query.error || requestData.query.error_description ? `${requestData.query.error_description || 'Auth error'} (${requestData.query.error || '???'})` : '' let serverUrl = ensureHttps(((requestData.body.serverUrl || requestData.query.serverUrl || '') as string).trim(), true, true) const canceled = requestData.body.canceled || requestData.query.canceled const state = requestData.body.state || requestData.query.state if (authError) { return sendAccessToken(authError) } if (canceled) { return sendAccessToken() } // First call: create state and redirect to re-invoke the login handler if (!state) { const urlObject = new URL(locals.endpointUrl) urlObject.searchParams.set('state', await getStateCodeAsync()) urlObject.searchParams.set('serverUrl', serverUrl) return sendRedirectUri(urlObject.toString()) } // No server URL yet, render the form const serverUrlError = serverUrl && !await checkIsPortal(serverUrl) if (!serverUrl && !code || serverUrlError) { const urlObject = new URL(locals.endpointUrl) urlObject.searchParams.set('state', state) return render(path.join(import.meta.dirname, 'select-serverurl'), { title: 'Select INTEGRATION_NAME Portal', action: urlObject.toString(), serverUrl: serverUrl || config.get('IntegrationName.defaultServerUrl'), logo, contact, error: serverUrlError ? 'Invalid Url (System is not a valid INTEGRATION_NAME system).' : undefined }) } // Retrieve serverUrl from state if (!serverUrl) { serverUrl = (await getStateAdapterDataAsync(state)).serverUrl } try { const oauth = getAuthClient(serverUrl) // No code yet, save serverUrl in state and redirect to OAuth provider if (!code) { await setStateAdapterDataAsync(state, { serverUrl }) const authUrl = oauth.authorizeURL({ redirect_uri: `${locals.endpointUrl}`, scope: SCOPES, state }) return sendRedirectUri(authUrl) } // Code received, exchange for tokens const { token } = await oauth.getToken({ code, redirect_uri: locals.endpointUrl }) return sendAccessToken(null, token.access_token, token.expires_in, token.refresh_token, undefined, { resourceEndpoint: serverUrl }) } catch (err) { return sendAccessToken(err) } }, ``` If your system does not send the `expires_in` for `access_token` and `refresh_expires_in` for `refresh_token`, you can hardcode them. It is not recommended but it is valid. ### API key / credentials [#api-key--credentials] User enters credentials via a rendered form. Credentials are validated against the platform API before completing login. The credential object itself is stored as the access token. Template (`login.ect`): ```html title="src/login.ect" <% extend 'login-template.ect' %>

Please enter your credentials.


``` Handler: ```ts title="src/index.ts" login: async (locals, requestData) => { const endpointUrlWithParam = param => { const urlObject = new URL(locals.endpointUrl) Object.entries(param).forEach(([ key, value ]) => { urlObject.searchParams.set(key, value) }) return urlObject.toString() } const { cloudName, apiKey, apiSecret } = requestData.body const token = { cloudName, apiKey, apiSecret } const adapterData = { resourceEndpoint: 'https://your-platform.example.com/api' } const state = requestData.body.state || requestData.query.state const canceled = (requestData.body.canceled || requestData.query.canceled) === 'true' try { // First call: create state if (!state) { return sendRedirectUri(endpointUrlWithParam({ state: await getStateCodeAsync() })) } // Render login form (reused for validation errors) const renderForm = error => render(path.join(import.meta.dirname, 'login'), Object.assign({ title: 'INTEGRATION_NAME Login', action: endpointUrlWithParam({ state }), logo, providerName: 'INTEGRATION_NAME', error }, token)) if (canceled) { return sendAccessToken('Login was cancelled') } // Incomplete credentials, show form if (!cloudName || !apiKey || !apiSecret) { return renderForm() } // Validate credentials against the platform API try { await DAMService.ping({ cloud_name: cloudName, api_key: apiKey, api_secret: apiSecret }) } catch (err) { if (err && err.error && err.error.message) { switch (err.error.message) { case 'cloud_name mismatch': return renderForm('INTEGRATION_NAME: Invalid Cloud Name') case 'unknown api_key': return renderForm('INTEGRATION_NAME: Invalid API-Key') case 'api_secret mismatch': return renderForm('INTEGRATION_NAME: Secret Mismatch') default: break } } return renderForm('INTEGRATION_NAME: Invalid Login Data') } // Credential object stored as the access token return sendAccessToken(null, token, null, null, null, adapterData) } catch (err) { return sendError(err, 400) } }, ``` ### OAuth PKCE + multi-step (server URL → OAuth → brand select) [#oauth-pkce--multi-step-server-url--oauth--brand-select] Multi-step flow: user enters a server URL, gets redirected for PKCE-based OAuth, then selects a brand. State helpers persist data across each redirect. ```ts title="src/index.ts" login: async (locals, requestData) => { const { code } = requestData.query const authError = requestData.query.error || requestData.query.error_description ? `${requestData.query.error_description || 'Auth error'} (${requestData.query.error || '???'})` : '' let serverUrl = ensureHttps(((requestData.body.serverUrl || requestData.query.serverUrl || '') as string).trim(), true, true) const canceled = requestData.body.canceled || requestData.query.canceled const state = requestData.body.state || requestData.query.state const brandId = requestData.body.brandId || requestData.query.brandId || '' if (authError) { return sendAccessToken(authError) } if (canceled) { return sendAccessToken() } // Step 1: create state and redirect if (!state) { const urlObject = new URL(locals.endpointUrl) urlObject.searchParams.set('state', await getStateCodeAsync()) urlObject.searchParams.set('serverUrl', serverUrl) return sendRedirectUri(urlObject.toString()) } // Step 2: no server URL yet, render the form if (!serverUrl && !code) { const urlObject = new URL(locals.endpointUrl) urlObject.searchParams.set('state', state as string) return render(path.join(import.meta.dirname, 'select-serverurl'), { title: 'Select INTEGRATION_NAME Portal', action: urlObject.toString(), serverUrl: serverUrl || config.get('IntegrationName.defaultServerUrl'), logo, contact }) } if (!serverUrl) { ({ serverUrl } = await getStateAdapterDataAsync(state as string) as { serverUrl: string }) } try { const oauth = getAuthClient(serverUrl) let tokenData = (await getStateAdapterDataAsync(state as string))?.tokenData as oauth2.Token // Step 3: no code yet, generate PKCE challenge and redirect to OAuth provider if (!code) { const verifier = createCodeVerifier() const challenge = createCodeChallenge(verifier) await setStateAdapterDataAsync(state as string, { serverUrl, verifier }) const authUrl = oauth.authorizeURL({ redirect_uri: `${locals.endpointUrl}`, code_challenge_method: 'S256', code_challenge: challenge, state: state as string, scope: SCOPES }) return sendRedirectUri(authUrl) } // Step 4: code received, exchange with PKCE verifier if (!tokenData) { const { verifier } = await getStateAdapterDataAsync(state as string) as { verifier: string } const { token } = await oauth.getToken({ code: code as string, client_id: 'your-client-id', redirect_uri: locals.endpointUrl, code_verifier: verifier }) tokenData = token } // Step 5: no brand selected yet, fetch brands and render selection form if (!brandId) { await setStateAdapterDataAsync(state as string, { tokenData, serverUrl }) const brands = await axios.post(`${serverUrl}/graphql`, { query: queries.getBrandsQuery }, { headers: { 'Authorization': `Bearer ${tokenData.access_token}`, 'Content-Type': 'application/json' } }) const urlObject = new URL(locals.endpointUrl) urlObject.searchParams.set('state', state as string) urlObject.searchParams.set('serverUrl', serverUrl) urlObject.searchParams.set('code', code as string) return render(path.join(import.meta.dirname, 'select-serverurl'), { title: 'Select Brand', brands: brands.data.data.brands, authMethod: 'brands', serverUrl, state, action: urlObject.toString(), logo, contact }) } // Step 6: complete, send tokens with brandId in adapterData return sendAccessToken(null, tokenData.access_token as string, tokenData.expires_in as number, tokenData.refresh_token as string, undefined, { resourceEndpoint: serverUrl, brandId }) } catch (error: any) { return sendAccessToken(`Error logging in: ${error.message}`) } }, ``` *** [Login Schema](/integration/schemas/auth/login) | [Login Templates](/integration/templates/overview) | [Capabilities Reference](/integration/advanced/capabilities-reference) # Search (/integration/building-an-integration/search) The search handler returns assets matching a text query. Called when the user types in the search bar in the CI HUB plugin UI. ## Inputs [#inputs] | Parameter | Type | Description | | ----------------------------- | ---------- | ------------------------------------------------------------ | | `requestData.query.query` | `string` | Search text entered by the user | | `requestData.query.page` | `string` | Current page number | | `requestData.query.size` | `string` | Requested page size | | `requestData.query.filters` | `string[]` | Selected filter option IDs | | `requestData.query.parentId` | `string` | Folder scope, limits search to a subfolder | | `requestData.body.dataBase64` | `string` | Base64-encoded image for similarity/visual search (optional) | ## Response [#response] ```ts return send({ assets, folders, filters, more }) ``` | Field | Type | Description | | --------- | --------------------- | ---------------------------------------------------------------------------- | | `assets` | `Asset[]` | Matching assets | | `folders` | `Folder[]` | Subfolders relevant to the query | | `filters` | `Filter[]` | Filter definitions with options and active state | | `more` | `number \| undefined` | Next page token. Present when more **assets** exist. `undefined` = last page | ## The `extractAssetsData` Pattern [#the-extractassetsdata-pattern] Every integration needs a function that maps remote API objects to the CI HUB `Asset` shape. By convention this function is called `extractAssetData` (single) or `extractAssetsData` (batch). It is **not** an SDK export. You write it in your integration. Both `search` and `getFolder` reuse it. ### Asset Object Fields [#asset-object-fields] Every field the mapping function should produce: | Field | Type | Purpose | | ---------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier from the remote system | | `name` | `string` | Display name. **Sanitize** with `.replace(/[/\\:*?"<>\|]/g, '_')`. Creative tools reject special characters in file names | | `downloadUrl` | `string \| null` | URL to fetch the file binary. Append [URL suffixes](#url-suffixes) as needed. `null` if download is not permitted | | `thumbnailUrl` | `string \| null` | Preview image URL. For InDesign/IDMS files, CI HUB can generate thumbnails server-side via `getThumbnailUrl()`. Pass the source system thumbnail or an empty string | | `mimeType` | `string` | Derived from file extension or the remote API. Fall back to `'application/octet-stream'` | | `xSizePx` / `ySizePx` | `number` | Pixel dimensions (width / height) | | `fileSize` | `number` | Size in bytes | | `created` / `modified` | `number` | Unix millisecond timestamps. Convert ISO date strings with `new Date(dateString).getTime()` | | `version` | `number` | Version number. Default to `1` when the platform doesn't support versioning | | `values` | `Array<{id, name, type, value}>` | Metadata entries shown in the asset detail panel. See [Custom Metadata](/integration/advanced/custom-metadata) | | `conversions` | `Array<{id, name, url, extension}>` | Available renditions/derivatives of the asset | | `capabilities` | `AssetCapabilities` | Per-asset permissions. Spread `defaultAssetCapabilities` and override what the platform supports | | `keywords` | `string[]` | Tags, displayed as chips in the plugin UI | | `states` | `string[]` | Workflow / lifecycle state labels | | `assetDetailsExternalUrl` | `string \| null` | "Open in source system" link | | `downloadHashFileAttributes` | `string` | `JSON.stringify({ fileSize, modified })`. Used by CI HUB for change detection | ### URL Suffixes [#url-suffixes] Append these to `downloadUrl` or `thumbnailUrl` to control how CI HUB fetches the file: * `$NO_AUTH$`: URL is publicly accessible, skip auth headers * `$AUTH_PAYLOAD_BEARER$`: attach the stored token as a Bearer header * `$FORCE_DOWNLOAD$`: force download instead of streaming Full list in the [Search Schema](/integration/schemas/assets/search). ## Pagination [#pagination] `more` controls asset pagination. Return a page token (typically `page + 1`) when more assets exist; return `undefined` on the last page. For **subfolders**: return all matching folders in a single response. Don't paginate folders. ## `canAddAsset` in Search [#canaddasset-in-search] If the platform allows uploading assets without a folder context (e.g. a flat asset library), set `canAddAsset: true` in the search result's `capabilities`: ```ts title="src/index.ts" capabilities: { canAddAsset: true } // [!code highlight] ``` This shows the upload button in the plugin UI even when not inside a folder. ## Patterns [#patterns] ### Example - `extractAssetData` [#example---extractassetdata] Maps a single remote API object to the CI HUB Asset shape. Derives the name, thumbnail, MIME type, conversions, states, and metadata values from the remote item. ```ts title="src/index.ts" const stateProps = [ { id: 'watermarked', name: 'Watermarked' }, { id: 'limited', name: 'Limited' }, { id: 'archive', name: 'Archived' }, { id: 'isPublic', name: 'Public' } ] const getValues = item => stateProps. filter(prop => item[prop.id]). map(prop => ({ id: prop.id, name: prop.name, type: 'TEXT', value: '✓' })). concat(Object.entries(item). filter(([ key, value ]) => key.startsWith('property_') && value). map(([ key, value ]) => ({ id: key, name: `${key[9].toUpperCase()}${key.substring(10)}`, type: 'TEXT', value: Array.isArray(value) ? value.join(', ') : value }))) const extractAssetData = (locals, item) => { let name = (item.name || '').replace(/[/\\:*?"<>|]/g, '_') const currentExtension = (path.extname(name) || '').toLowerCase().replace('.', '') if (item.extension && currentExtension !== `${item.extension}`.toLowerCase()) { name += `.${item.extension}` } const thumbnailVideoUrl = item && item.videoPreviewURLs && item.videoPreviewURLs.length && item.videoPreviewURLs[0] const downloadUrl = getDownloadUrl(locals, item.id) const thumbnailUrl = getThumbnailUrl(downloadUrl, name, [ 'indd', 'idms' ], item.thumbnails.thul && `${item.thumbnails.thul}$NO_AUTH$`) const fileSize = item.fileSize const modified = new Date(item.dateModified).getTime() return { id: item.id, name, parentPath: '/Assets', fileSize, xSizePx: item.width, ySizePx: item.height, created: new Date(item.dateCreated).getTime(), modified, mimeType: mime.lookup(name) || 'application/octet-stream', version: item.version || 1, caption: item.description && item.description.trim() || undefined, copyright: item.copyright && item.copyright.trim() || undefined, title: item.name, thumbnailUrl, // [!code highlight] thumbnailVideoUrl, downloadUrl, // [!code highlight] downloadHashFileAttributes: JSON.stringify({ fileSize, modified }), // [!code highlight] lowresUrl: !thumbnailVideoUrl ? getDownloadUrl(locals, item.id, '?lowres=1') : undefined, assetDetailsExternalUrl: getAssetDetailsExternalUrl(locals, item.id), conversions: getConversions(item), keywords: item.tags, states: stateProps.filter(entry => item[entry.id]).map(entry => entry.name), capabilities: defaultAssetCapabilities, values: getValues(item) } } ``` ### Example - `extractAssetsData` [#example---extractassetsdata] Batch variant that maps an array of remote items, merges per-asset permissions with `defaultAssetCapabilities`, and filters out broken items. ```ts title="src/index.ts" const extractAssetsData = (locals, items, overrideCapabilities = {}, useFileName = false) => items.map((item) => { const expired = item.expiresAt ? new Date(item.expiresAt).getTime() < Date.now() : false const [ key, fallback ] = useFileName ? [ 'title', 'filename' ] : [ 'filename', 'title' ] const assetName = item[key] || item[fallback] const downloadUrl = item.downloadUrl?.concat('$NO_AUTH$') ?? getDownloadUrl(locals) const thumbnailUrl = item.thumbnailUrl?.concat('$NO_AUTH$') const extension = item.extension || mimeTypes.extension(item.filename) const fileSize = item.size const modified = new Date(item.modifiedAt).getTime() const readableId = getHumanReadableId(item.id.toString()) const canDownload = !expired && (item.currentUserPermissions?.canDownload ?? true) const capabilities = { canUpdateAsset: !expired && (item.currentUserPermissions?.canEdit || false), canDeleteAsset: !expired && (item.currentUserPermissions?.canDelete || false) } try { const asset = { id: item.id.toString(), name: assetName, downloadUrl: canDownload ? downloadUrl : null, thumbnailUrl: thumbnailUrl, mimeType: mimeTypes.lookup(extension) || mimeTypes.lookup(assetName) || 'application/octet-stream', title: item.title, xSizePx: item.width, ySizePx: item.height, fileSize, created: new Date(item.createdAt).getTime(), modified, version: 1, values: getValues(item), conversions: expired ? [] : getConversions(item, extension, thumbnailUrl), keywords: item.tags?.map((tag) => tag.value).filter((tag) => tag), states: [ item.workflowTask?.status?.name, item.licenses?.map((license) => license.title), expired ? 'Expired' : '' ].flat().filter((state) => state), capabilities: { ...defaultAssetCapabilities, ...capabilities, ...overrideCapabilities }, // [!code highlight] downloadHashFileAttributes: JSON.stringify({ fileSize, modified }), assetDetailsExternalUrl: readableId ? new URL(`/screen/${readableId}`, locals.adapterData.resourceEndpoint).toString() : null } return asset } catch { return undefined } }).filter((item) => item) ``` ### Example - Search Handler [#example---search-handler] Parses query parameters, calls the remote API, maps results through `extractAssetData`, builds filters, and determines pagination. ```ts title="src/index.ts" search: async (locals, requestData) => { const query = requestData.query.query || '' const page = Number.parseInt(requestData.query.more || 0, 10) const size = Math.min(Number.parseInt(requestData.query.size || 50, 10), config.get('IntegrationName.maxQuerySize')) const activeFilters = requestData.query.filters || [] try { const result = await getAssets(locals, null, query, page, size, activeFilters) return sendResult(null, result) } catch (err) { return sendError(err, 400) } } // getAssets builds the full result object: const getAssets = async (locals, collection, search, page, size, activeFilters = []) => { const capabilities = Object.assign({}, defaultFolderCapabilities, { canAddAsset: true, canDeleteFolder: collection !== '' }) const result = { folders: [], assets: [], filters: [], capabilities, totalAssetsCount: 0 } const query = { limit: size, page: page + 1, count: true, total: true, orderBy: 'dateCreated desc' } const assets = await callApi(locals, 'GET', '/api/v4/media/', query) result.totalAssetsCount = assets.count.total // Pagination: check if more assets exist if (page * size + assets.media.length < result.totalAssetsCount) { // [!code highlight] result.more = page + 1 // [!code highlight] } // Map each remote item to CI HUB Asset for (const item of assets.media) { const asset = extractAssetData(locals, item) result.assets.push(asset) } return result } ``` ### Example - Search Handler [#example---search-handler-1] Integration with filter parsing, folder scoping, and two search paths (library search vs. brand-wide search). ```ts title="src/index.ts" search: async (locals, requestData) => { const { brandId } = locals.adapterData const isFileNameSearch = requestData.query.type === 'fileName' const query = (requestData.query.query || '').replace(isFileNameSearch ? /^"|"$/g : '', '') const activeFilters = requestData.query.filters || [] const activeFiltersJson = parseOptions(activeFilters) const rFolderId = (requestData.query.parentId || '').toString() const folderId = folderIdStartsWith(rFolderId) ? undefined : rFolderId const more = parseInt((requestData.query.more || '1'), 10) || 1 const size = Math.min(parseInt((requestData.query.size || '25'), 10), config.get('IntegrationName.maxQuerySize')) const result = { assets: [], folders: [], filters: [], more: undefined, capabilities: {}, totalAssetsCount: 0 } try { const searchQuery = { ...folderId ? { inFolder: { id: folderId } } : {}, search: query } const assets = await callApi(locals, { query: queries.getSearchAssetsQuery, variables: { libraryId, query: searchQuery, page: more, limit: size } }) result.assets = extractAssetsData(locals, assets.data.library.assets.items) result.more = assets.data.library.assets.hasNextPage ? more + 1 : undefined // [!code highlight] result.totalAssetsCount = assets.data.library.assets.total result.filters = getFilters(assets.data, activeFiltersJson) return send(result) } catch (error) { return sendError(`Error searching: ${error}`, 400) } } ``` *** [Search Schema](/integration/schemas/assets/search) | [Filters](/integration/building-an-integration/filters) | [Custom Metadata](/integration/advanced/custom-metadata) # Tasks (/integration/building-an-integration/tasks) Task handlers connect CI HUB's tasking UI to work management platforms. Users can search tasks, view task details, attach/remove assets, add comments, and update task states, all from inside the creative tool. ## Enabling Tasks [#enabling-tasks] Set `tasking: true` and configure `taskSearch` in capabilities: ```ts capabilities: { tasking: true, taskSearch: { help: { en: 'Search for tasks by typing a name', de: 'Suchen Sie nach Aufgaben indem Sie einen Namen eintippen' } } } ``` ## searchTasks [#searchtasks] Returns a filtered, paginated list of tasks. CI HUB calls this when the user types in the task search bar or applies filters. ### Inputs [#inputs] | Field | Description | | --------------------------- | -------------------------------------------------------------------- | | `requestData.query.query` | Search text | | `requestData.query.filters` | Applied filter option IDs (array of `"filterName:optionId"` strings) | | `requestData.query.more` | Pagination cursor from previous response | | `requestData.query.size` | Page size | ### Response [#response] ```ts return send({ tasks: [...], // array of task objects filters: [...], // filter definitions with selected state more: 'cursor-or-offset', // pagination cursor, undefined if no more totalTasksCount: 0 // total count (if known) }) ``` ### Patterns [#patterns] **Example** - Parses filters, supports workspace scoping and completion status: ```ts const performTaskSearch = async (locals, requestData) => { const query = requestData.query.query || '' const appliedFilters = requestData.query.filters || [] const more = requestData.query.more || undefined const size = Math.min(Number.parseInt(requestData.query.size || 50, 10), config.get('IntegrationName.maxQuerySize')) const parsedFilters = appliedFilters.reduce((acc, optionId) => { const [ filterName, optionName ] = optionId.split(':') acc[filterName] = optionName return acc }, {}) const result = { tasks: [], filters: [ getGlobalTaskListFilter(parsedFilters), getCompletedStatusFilter(parsedFilters) ], more: undefined, totalTasksCount: 0 } const workspaceId = parsedFilters.workspace || await getDefaultWorkspaceId(locals) const completed = [ undefined, 'completedAndIncomplete' ].includes(parsedFilters.completedStatusFilter) ? undefined : parsedFilters.completedStatusFilter === 'completed' const userID = parsedFilters.globalTaskListFilter === 'myTasks' ? await getUserId(locals) : undefined const data = (await callApi(locals, 'GET', `/workspaces/${workspaceId}/tasks/search`, { 'created_at.before': more, 'limit': size, 'text': query, 'opt_fields': optFieldsTask, 'sort_by': 'created_at', 'assignee.any': userID, completed })).data || [] result.tasks = await extractTasksData(locals, data) if (result.tasks.length && result.tasks.length === size) { result.more = new Date(result.tasks[result.tasks.length - 1].created || 0).toISOString() } return result } searchTasks: async (locals, requestData) => { try { const result = await performTaskSearch(locals, requestData) return send(result) } catch (err) { return sendError(err, 400) } }, ``` The handler delegates to `performTaskSearch` which is reused by both `searchTasks` and the `search` handler (when tasking is enabled in folder navigation). [Search Tasks Schema](/integration/schemas/tasks/search-tasks) *** ## getTask [#gettask] Returns full details for a single task. ### Inputs [#inputs-1] | Field | Description | | --------------------------- | ----------- | | `requestData.params.taskId` | Task ID | ### Response [#response-1] Return a single task object (same shape as items in `searchTasks`). ### Patterns [#patterns-1] **Example** - Returns full details for a single task: ```ts getTask: async (locals, requestData) => { try { const { taskId } = requestData.params const data = (await callApi(locals, 'GET', `/tasks/${taskId}`)).data const task = (await extractTasksData(locals, [ data ]))[0] if (!task) { return sendError('Error processing task', 400) } return send(task) } catch (err) { return sendError(err, 400) } }, ``` [Get Task Schema](/integration/schemas/tasks/get-task) *** ## getTaskAssets [#gettaskassets] Returns the assets (attachments) linked to a task. ### Inputs [#inputs-2] | Field | Description | | --------------------------- | ----------------- | | `requestData.params.taskId` | Task ID | | `requestData.query.size` | Page size | | `requestData.query.more` | Pagination cursor | ### Response [#response-2] ```ts return send({ assets: [...], more: 'next-offset', totalAssetsCount: 0 }) ``` ### Patterns [#patterns-2] **Example** - Returns the assets linked to a task: ```ts getTaskAssets: async (locals, requestData) => { try { const { taskId } = requestData.params const limit = Math.min(Number.parseInt(requestData.query.size || 50, 10), config.get('IntegrationName.maxQuerySize')) const result = { assets: [], more: undefined, totalAssetsCount: 0 } const taskAssets = await callApi(locals, 'GET', `/tasks/${taskId}/attachments`, { opt_fields: optFieldsAttachment, offset: (requestData.query.more !== '' && requestData.query.more) || undefined, limit }) || {} if (taskAssets.data && taskAssets.data.length) { result.assets = extractAssetData(locals, taskAssets.data).map(asset => ({ ...asset, capabilities: { ...asset.capabilities, canDeleteAsset: true } })) } if (taskAssets.next_page) { result.more = taskAssets.next_page.offset } return send(result) } catch (err) { return sendError(err, 400) } }, ``` Set `canDeleteAsset: true` on task assets to enable the remove button in the task assets panel. [Get Task Assets Schema](/integration/schemas/tasks/get-task-assets) *** ## addTaskComment [#addtaskcomment] Posts a text comment to a task. ### Inputs [#inputs-3] | Field | Description | | --------------------------- | ------------ | | `requestData.params.taskId` | Task ID | | `requestData.body.comment` | Comment text | ### Response [#response-3] ```ts return sendStatus(200) ``` ### Patterns [#patterns-3] **Example** - Adds a comment to a task: ```ts addTaskComment: async (locals, requestData) => { try { const { taskId } = requestData.params const { comment } = requestData.body const data = { data: { is_pinned: false, text: comment } } await callApi(locals, 'POST', `/tasks/${taskId}/stories`, null, data) return sendStatus(200) } catch (err) { return sendError(err, 400) } }, ``` [Add Task Comment Schema](/integration/schemas/tasks/add-task-comment) *** ## addTaskAsset [#addtaskasset] Attaches an asset to a task. The asset is linked as an external reference using CI HUB's view URL system. ### Inputs [#inputs-4] | Field | Description | | ------------------------------------- | ------------------------------------------------------------------------ | | `requestData.params.taskId` | Task ID | | `requestData.body.name` | Asset display name | | `requestData.body.providerId` | Source integration provider ID (in the login response, `adapter` field) | | `requestData.body.remoteSystemPrefix` | Source integration system prefix (in the login response, `source` field) | | `requestData.body.assetId` | Asset ID in the source system | | `requestData.body.viewUrl` | Base view URL for the asset | ### Response [#response-4] ```ts return sendStatus(200) ``` ### Patterns [#patterns-4] **Example** - Attaches as an external link using multipart form data: ```ts addTaskAsset: async (locals, requestData) => { try { const { taskId } = requestData.params const { name, providerId, remoteSystemPrefix: systemPrefix, assetId, viewUrl } = requestData.body if ([ taskId, name, providerId, systemPrefix, assetId, viewUrl ].every(val => ![ undefined, null ].includes(val))) { const assetViewUrl = createAssetViewUrl(viewUrl, providerId, systemPrefix, assetId) const fd = new FormDataNode() fd.append('parent', taskId) fd.append('name', name) fd.append('resource_subtype', 'external') fd.append('url', assetViewUrl) await callApi(locals, 'POST', '/attachments', null, fd, fd.getHeaders()) return sendStatus(200) } return sendError('Not implemented', 400) } catch (err) { return sendError(err, 400) } }, ``` `createAssetViewUrl()` generates a CI HUB view URL that links back to the asset in its source system. Use it to create cross-integration asset references. [Add Task Asset Schema](/integration/schemas/tasks/add-task-asset) *** ## deleteTaskAsset [#deletetaskasset] Removes an asset attachment from a task. ### Inputs [#inputs-5] | Field | Description | | ---------------------------- | ----------------------- | | `requestData.params.taskId` | Task ID | | `requestData.params.assetId` | Attachment ID to remove | ### Response [#response-5] ```ts return sendStatus(200) ``` ### Patterns [#patterns-5] **Example** - Removes an asset attachment from a task: ```ts deleteTaskAsset: async (locals, requestData) => { try { const { assetId } = requestData.params await callApi(locals, 'DELETE', `/attachments/${assetId}`) return sendStatus(200) } catch (err) { return sendError(err, 400) } }, ``` [Delete Task Asset Schema](/integration/schemas/tasks/delete-task-asset) *** ## updateCustomTaskState [#updatecustomtaskstate] Updates a task's status or custom field value. CI HUB calls this when the user changes a state dropdown in the task detail panel. ### Inputs [#inputs-6] | Field | Description | | ------------------------------------ | ---------------------- | | `requestData.params.taskId` | Task ID | | `requestData.query.stateId` | State field identifier | | `requestData.query.selectedOptionId` | New value/option ID | ### Response [#response-6] ```ts return sendStatus(200) ``` ### Patterns [#patterns-6] **Example** - Supports both built-in fields and custom fields (prefixed with `custom_userField_id:`): ```ts updateCustomTaskState: async (locals, requestData) => { try { const { taskId } = requestData.params const { stateId, selectedOptionId } = requestData.query let data if (stateId.startsWith('custom_userField_id:')) { const [ , fieldID ] = stateId.split(':') data = { data: { custom_fields: { [fieldID]: selectedOptionId } } } } else { data = { data: { [stateId]: selectedOptionId } } } await callApi(locals, 'PUT', `/tasks/${taskId}`, null, data) return sendStatus(200) } catch (err) { return sendError(err, 400) } }, ``` **Example** - Simpler API, maps directly to a status field: ```ts updateCustomTaskState: async (locals, requestData) => { try { const { taskId } = requestData.params const { selectedOptionId } = requestData.query await callApi(locals, 'PUT', '/task', { ID: taskId, updates: JSON.stringify({ status: selectedOptionId }) }) return sendStatus(200) } catch (err) { return sendError(err, 400) } }, ``` The `stateId` and `selectedOptionId` values come from the task's `states` array, which is populated in `extractTasksData`. Each state has `options` with selectable values. [Update Custom Task State Schema](/integration/schemas/tasks/update-custom-task-state) # Upload (/integration/building-an-integration/upload) `createAsset` uploads a new file into a folder. `updateAsset` replaces an existing asset's file. CI HUB calls these when the user uploads from the plugin UI. ## Enabling Upload in the UI [#enabling-upload-in-the-ui] Upload visibility is controlled by capabilities returned from `getFolder` and `info`: | Capability | Where | Effect | | ---------------------- | ---------------------- | -------------------------------------- | | `canAddAsset: true` | Folder capabilities | Upload button appears in that folder | | `canUpdateAsset: true` | Per-asset capabilities | "Update" option appears on right-click | ## Inputs [#inputs] ### createAsset [#createasset] | Field | Description | | ------------------------------------- | ---------------------------------------------------- | | `requestData.body.name` | Original filename | | `requestData.body.dataBase64` | File as base64 data URI (fallback) | | `requestData.body.dataBuffer` | File as Buffer (preferred) | | `requestData.body.parentId` | Target folder ID | | `requestData.body.createAssetOptions` | Filter-format options from `info.createAssetOptions` | ### updateAsset [#updateasset] | Field | Description | | ----------------------------- | ---------------------------------- | | `requestData.params.assetId` | ID of asset to update | | `requestData.body.name` | New filename | | `requestData.body.dataBase64` | File as base64 data URI (fallback) | | `requestData.body.dataBuffer` | File as Buffer (preferred) | ## Response [#response] ```ts title="src/index.ts" return send({ id: string, // new or updated asset ID name: string, // filename additionalRenditionsNeeded?: Array<{ // triggers linked-file upload flow // [!code ++:4] type: string, url: string }> }) ``` ## Patterns [#patterns] ### Standard Chunked Upload [#standard-chunked-upload] **Example**: init upload → PUT chunks to pre-signed URLs → complete: ```ts title="src/index.ts" createAsset: async (locals, requestData) => { try { const { name, dataBase64, dataBuffer, createAssetOptions } = requestData.body const buffer = dataBuffer || Buffer.from(dataBase64.split(',')[1], 'base64') const assetOptions = parseFilters(createAssetOptions || []) const { data } = await callApi(locals, 'post', 'v1/assets/asset', {}, { filename: name, metadataTemplateId: assetOptions.metadataTemplateId, securityTemplateIds: [assetOptions.securityTemplateId], metadata: [], filesize: buffer.length }) const { fileId, filename, originalFileId, uploadId } = data const urls = data.urls || [] const parts = [] if (data.url && urls.length === 0) { urls.push({ url: data.url, partNumber: 1 }) } await Promise.all( urls.map(async url => { const start = maxChunkSize * (url.partNumber - 1) const end = Math.min(maxChunkSize * url.partNumber, buffer.length) const chunk = buffer.subarray(start, end) const response = await axios.put(url.url, chunk, { headers: { 'Content-Type': 'application/octet-stream' } }) parts.push({ etag: response.headers.etag.replace(/"/g, ''), partNumber: url.partNumber }) }) ) await callApi(locals, 'post', '/v1/asset/complete', null, { fileId, filename, filesize: buffer.length, action: 'complete', originalFileId, uploadId, parts }) const additionalRenditionsNeeded = createAdditionalRenditions(locals, filename, fileId) return send({ id: fileId, name: filename, additionalRenditionsNeeded }) // [!code highlight] } catch (err) { return sendError(err) } }, ``` ### updateAsset: Same Flow with Existing Metadata [#updateasset-same-flow-with-existing-metadata] **Example** - fetches existing asset metadata, creates new version with same template/security settings: ```ts title="src/index.ts" updateAsset: async (locals, requestData) => { try { const { assetId } = requestData.params const { name, dataBase64, dataBuffer } = requestData.body const buffer = dataBuffer || Buffer.from(dataBase64.split(',')[1], 'base64') const asset = (await callApi(locals, 'GET', `/v1/assets/asset/${assetId}`)).data || {} const { data } = await callApi(locals, 'post', 'v1/assets/asset', {}, { filename: name, metadataTemplateId: asset.metadataTemplateId, securityTemplateIds: asset.securityTemplateIds, metadata: (asset.metadata || []).filter( metadata => !['System Process Source', 'System Layout Links'].includes(metadata.name) ), filesize: buffer.length, originalFileId: asset.originalFileId // [!code highlight] }) const { fileId, filename, originalFileId, uploadId } = data const urls = data.urls || [] const parts = [] if (data.url && urls.length === 0) { urls.push({ url: data.url, partNumber: 1 }) } await Promise.all( urls.map(async url => { const start = maxChunkSize * (url.partNumber - 1) const end = Math.min(maxChunkSize * url.partNumber, buffer.length) const chunk = buffer.subarray(start, end) const response = await axios.put(url.url, chunk, { headers: { 'Content-Type': 'application/octet-stream' } }) parts.push({ etag: response.headers.etag.replace(/"/g, ''), partNumber: url.partNumber }) }) ) await callApi(locals, 'post', '/v1/asset/complete', null, { fileId, filename, filesize: buffer.length, action: 'complete', originalFileId, uploadId, parts }) const additionalRenditionsNeeded = createAdditionalRenditions(locals, filename, fileId) return send({ id: fileId, name: filename, additionalRenditionsNeeded }) // [!code highlight] } catch (err) { return sendError(err) } }, ``` ### Simple FormData Upload [#simple-formdata-upload] **Example** - single POST with multipart form data: ```ts title="src/index.ts" const upload = async (locals, requestData) => { try { const { name, dataBase64, dataBuffer, parentId } = requestData.body const assetId = requestData.params?.assetId const buffer = dataBuffer || Buffer.from(dataBase64.split(',').pop(), 'base64') const fileSize = buffer.length const formData = new FormDataNode() let versionGroup formData.append('asset', buffer, name || '') if (assetId) { // [!code highlight] versionGroup = (await callApi(locals, 'GET', `/assets/${assetId}`)).asset.versionGroup // [!code highlight] } const id = (await callApi(locals, 'POST', '/assets/upload', { estimateTime: 1, size: fileSize, totalSize: fileSize, folderId: assetId ? null : parentId, versionGroup }, formData, formData.getHeaders()))[0].asset.id return send({ id, name, additionalRenditionsNeeded: createAdditionalRenditions(locals, name, id) }) } catch (err) { return sendError(err, 400) } } ``` This integration reuses the same function for both `createAsset` and `updateAsset`. When `assetId` is present, it fetches the version group to create a new version. ## Additional Renditions [#additional-renditions] When uploading InDesign, Illustrator, or Photoshop files, CI HUB can extract linked files and associate them with the uploaded asset. This is driven by `additionalRenditionsNeeded` in the upload response. ### Flow [#flow] ### Creating the Renditions List [#creating-the-renditions-list] Check the file extension. Return renditions only for supported creative formats: ```ts title="src/index.ts" const createAdditionalRenditions = (locals, fileName, assetId) => { const fileExtension = path.extname(fileName).toLowerCase().replace('.', '') if (['ai', 'indd', 'psd'].includes(fileExtension)) { // [!code highlight] return [{ type: 'DocumentSummary', url: `${locals.endpointUrl}/saveAssetRelations?type=${fileExtension}&assetId=${encodeURIComponent(assetId)}` }] } } ``` The `url` points to the integration's own `saveAssetRelations` handler, which receives the document structure from the plugin and creates asset relationships. ### getAdditionalRenditionsNeeded Handler [#getadditionalrenditionsneeded-handler] When using `directAccessHelper` (browser-side upload), the renditions list isn't computed server-side during upload. Instead, CI HUB calls this handler after upload completes: ```ts title="src/index.ts" getAdditionalRenditionsNeeded: async (locals, requestData) => { try { const { assetId, name } = requestData.query return send(createAdditionalRenditions(locals, name, assetId)) } catch (error) { return sendError(error, 400) } } ``` ### Direct Access Helper (browser-side upload) [#direct-access-helper-browser-side-upload] For large files, provide a Direct Access Helper (DAH), a bundled JavaScript function that uploads directly from the browser to the provider API, bypassing the CI HUB server. The DAH is **required for all new integrations** unless you can demonstrate it is not feasible. See [Direct Access Helper](/integration/building-an-integration/direct-access-helper) for the full guide: entry file structure, function signature, input/output types, limitations, and best practices. ## UI Behavior [#ui-behavior] * Folder with `canAddAsset: true` → upload button visible * User clicks upload → file picker → `createAsset` called with file buffer and `parentId` * Asset with `canUpdateAsset: true` → right-click shows "Update" option * User clicks Update → file picker → `updateAsset` called with `assetId` and new file buffer * Upload response with `additionalRenditionsNeeded` → plugin automatically posts document structure to each rendition URL See [Create Asset Schema](/integration/schemas/assets/create-asset) | [Update Asset Schema](/integration/schemas/assets/update-asset) # Worked Examples (/integration/examples) Full integration walkthroughs showing how real adapters were built. These are reference implementations. Read them alongside the [main guide](/integration) to understand how the patterns apply in production. New to the SDK? Start with the [main guide](/integration) first. Come back here once you understand the core concepts. ## Available examples [#available-examples] ## How to use these examples [#how-to-use-these-examples] Each example documents: * The **capabilities** the integration declares and why * The **auth flow** chosen and the decisions behind it * **Folder and asset mapping**: how the remote data model maps to the CI HUB schema * **API patterns** specific to that platform (GraphQL, REST, pagination) * **Upload flow**: server-side, client-side ([Direct Access Helper](/integration/building-an-integration/direct-access-helper)), or both * **Edge cases** and how they were handled Use them as a reference when building your own integration, not as a copy-paste starting point. Your platform's API will have different shapes, auth requirements, and data models. # Installation (/integration/getting-started/installation) ## Prerequisites [#prerequisites] * Node.js 20.19+ or 22.12+ * TypeScript 5 or later * An existing DAM or content platform with an API you can call ## Scaffold a new project (recommended) [#scaffold-a-new-project-recommended] The fastest way to get started is the `create` command. It scaffolds a ready-to-run TypeScript project with the SDK pre-configured: ```bash npm create @ci-hub/integration my-integration ``` ```bash pnpm create @ci-hub/integration my-integration ``` ```bash yarn create @ci-hub/integration my-integration ``` ```bash bun create @ci-hub/integration my-integration ``` ### CLI options [#cli-options] | Flag | Description | | -------------- | ---------------------------------------------------------------- | | `--overwrite` | Remove existing files in the target directory before scaffolding | | `--install` | Auto-install dependencies (default: interactive prompt) | | `--no-install` | Skip dependency installation | After scaffolding, start the development server: ```bash cd my-integration npm run dev ``` The SDK starts a local server and exposes your integration at `http://localhost:8080`. Opening that URL gives you the [SDK Workbench](/integration/getting-started/workbench), which calls your handlers the same way the CI HUB client does. You can also point a CI HUB development environment at this URL to test your integration end to end. ## Manual install [#manual-install] If you prefer to set up a project from scratch: ```bash npm install @ci-hub/integration-sdk ``` ```bash pnpm add @ci-hub/integration-sdk ``` ```bash yarn add @ci-hub/integration-sdk ``` ```bash bun add @ci-hub/integration-sdk ``` ## TypeScript configuration [#typescript-configuration] The scaffolded project includes a `tsconfig.json`. If you're setting up manually, your config should have at minimum: ```json title="tsconfig.json" { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "strict": true, "esModuleInterop": true }, "include": ["src/**/*"] } ``` The SDK ships with full type definitions. You get autocomplete and type checking for all handler signatures, `locals`, `requestData`, and response helpers. ## The full `defineIntegration` skeleton [#the-full-defineintegration-skeleton] Below is the complete list of handlers you can implement. Start with the ones your platform supports and add more over time. Handlers you don't implement are simply omitted. Every handler inside `defineIntegration` is fully typed. The SDK infers the correct `locals` and `requestData` types for each handler. For stricter compile-time types on `adapterData`, per-handler `requestData`, and OAuth state, pass a type config to `defineIntegration`. See [Typed Integrations](/integration/advanced/typed-integrations). ```ts title="src/index.ts" import { defineIntegration, send, sendResult, sendError, sendStatus, sendAccessToken, sendRedirectUri, defaultFolderCapabilities, defaultAssetCapabilities, config, fs, path, CategoryEnum, } from '@ci-hub/integration-sdk' const imageBase64 = (name: string) => `data:image/png;base64,${Buffer.from(fs.readFileSync(path.join(import.meta.dirname, name))).toString('base64')}` const logo = { data: imageBase64('logo.png'), width: 600, height: 134, backgroundColor: '#FFFFFF' } const glyph = { data: imageBase64('glyph.png'), width: 80, height: 80, backgroundColor: '#FFFFFF' } export default defineIntegration({ name: 'My DAM', version: '1.0.0', logo, glyph, contact: config.get('myIntegration.contact'), capabilities: { category: CategoryEnum.DAM, assetUploadLimitInMB: 500, directAssetDownload: true, assetSearch: { supportsParentId: true, }, description: { en: 'Connect to My DAM from CI HUB.', }, }, // ─── Auth (required) ───────────────────────────────────────────────────── login: async (locals, requestData) => { /* ... */ }, // [!code highlight] logout: async (locals, requestData) => { /* ... */ }, // [!code highlight] checkToken: async (locals) => { /* ... */ }, // [!code highlight] refreshToken: async (locals) => { /* ... */ }, // optional (OAuth only) // ─── Content (implement what your platform supports) ────────────────────── search: async (locals, requestData) => { /* ... */ }, getFolder: async (locals, requestData) => { /* ... */ }, download: async (locals, requestData) => { /* ... */ }, createAsset: async (locals, requestData) => { /* ... */ }, updateAsset: async (locals, requestData) => { /* ... */ }, deleteAsset: async (locals, requestData) => { /* ... */ }, // ─── Folders ───────────────────────────────────────────────────────────── createFolder: async (locals, requestData) => { /* ... */ }, renameFolder: async (locals, requestData) => { /* ... */ }, deleteFolder: async (locals, requestData) => { /* ... */ }, moveFolder: async (locals, requestData) => { /* ... */ }, // ─── Asset actions ─────────────────────────────────────────────────────── lockAsset: async (locals, requestData) => { /* ... */ }, renameAsset: async (locals, requestData) => { /* ... */ }, moveAsset: async (locals, requestData) => { /* ... */ }, getAssetVersions: async (locals, requestData) => { /* ... */ }, // ─── Tasks ─────────────────────────────────────────────────────────────── searchTasks: async (locals, requestData) => { /* ... */ }, getTask: async (locals, requestData) => { /* ... */ }, getTaskAssets: async (locals, requestData) => { /* ... */ }, addTaskComment: async (locals, requestData) => { /* ... */ }, addTaskAsset: async (locals, requestData) => { /* ... */ }, deleteTaskAsset: async (locals, requestData) => { /* ... */ }, updateCustomTaskState: async (locals, requestData) => { /* ... */ }, // ─── Brand Hub ─────────────────────────────────────────────────────────── getBrandConfig: async (locals, requestData) => { /* ... */ }, getBrandAssets: async (locals, requestData) => { /* ... */ }, // ─── Advanced ──────────────────────────────────────────────────────────── doTransformation: async (locals, requestData) => { /* ... */ }, additionalRendition: async (locals, requestData) => { /* ... */ }, saveAssetRelations: async (locals, requestData) => { /* ... */ }, }) ``` ## config.json [#configjson] The SDK reads configuration from `config.json` in your project root (or `src/config.json`). Structure it with a top-level `serverBaseUrl` and an integration-specific section keyed by your integration name: ```json title="config.json" { "serverBaseUrl": "http://localhost:8080", "myIntegration": { "contact": { "text": "If you experience any problems, please contact our support team.", "url": { "link": "https://your-platform.example.com/help", "email": "support@your-platform.example.com" } }, "authEndpoint": "https://your-platform.example.com/oauth/authorize", "tokenEndpoint": "https://your-platform.example.com/oauth/token", "clientId": "your-client-id", "clientSecret": "your-client-secret", "maxQuerySize": 100, "maxFileSizeInMB": 5242880 } } ``` Access values with `config.get()` and `config.has()` using dot-separated paths: ```ts title="src/index.ts" config.get('myIntegration.clientId') // returns the value or throws if missing config.get('myIntegration.maxQuerySize') // nested keys work the same way config.has('myIntegration.clientSecret') // returns boolean, never throws // [!code highlight] ``` `config.get()` throws if the key doesn't exist. Pass a default value as the second argument to avoid the throw: `config.get('myIntegration.timeout', 30000)`. ## Config validation [#config-validation] Validate required config keys at the top of your `index.ts`, before `defineIntegration`. This fails fast on startup instead of at runtime when a handler is called: ```ts title="src/index.ts" { const requiredKeys = ['myIntegration.clientId', 'myIntegration.contact', 'myIntegration.authEndpoint', 'myIntegration.tokenEndpoint'] const missing = requiredKeys.filter(k => !config.has(k)) if (missing.length) throw new Error(`Missing configuration: ${missing.join(', ')}`) // [!code highlight] } ``` The block scope `{}` keeps `requiredKeys` and `missing` out of module scope. ## Project structure [#project-structure] Keep all integration logic in `index.ts`. Split only for long static data: GraphQL query strings (`queries.ts`), static filter/rendition lists (`renditions.ts`), or `.ect` login templates. ## Available scripts [#available-scripts] The scaffolded project includes npm scripts that wrap the CLI: | Script | Command | Description | | ------ | ------------- | ---------------------------------- | | `dev` | `npm run dev` | Start the local development server | The CLI (`integration-cli`) ships inside `@ci-hub/integration-sdk` and is not installed as a global binary. The `dev` script runs it for you; for any other command, use your package manager: ```bash npx integration-cli dev npx integration-cli auth login npx integration-cli config --init npx integration-cli submit ``` ```bash pnpm exec integration-cli dev pnpm exec integration-cli auth login pnpm exec integration-cli config --init pnpm exec integration-cli submit ``` ```bash yarn integration-cli dev yarn integration-cli auth login yarn integration-cli config --init yarn integration-cli submit ``` ```bash bunx integration-cli dev bunx integration-cli auth login bunx integration-cli config --init bunx integration-cli submit ``` For the full command reference (`dev`, `auth`, `config`, `submit`), see the [CLI reference](/integration/reference/cli). # Partner Journey (/integration/getting-started/partner-journey) This page is for product, sales, and project leads. If you're deciding whether to build an integration, start here. Developers go straight to [Installation](/integration/getting-started/installation). ## What your customers get [#what-your-customers-get] Your platform shows up inside CI HUB's plugins (add-ons) for 30+ apps, such as Adobe InDesign, Photoshop, Microsoft 365, Figma, and Canva. That puts your content in front of CI HUB's 2,200+ corporate customers. Your customers log in with their account on your platform, then browse, search, and place their assets without leaving the app they work in. Your access rules and metadata carry through, so people only see what they're allowed to see. If your integration supports upload, they can also save files back to your platform. This works for any system that stores enterprise content: DAM, MAM, PIM, CRM, or cloud storage. More than 70 systems already use the SDK, including Sitecore, Adobe Experience Manager, Bynder, and Frontify. You don't host the integration. CI HUB runs it on its own servers. ## What you need on your side [#what-you-need-on-your-side] * A free **CI HUB Sales Club** membership. Apply with the [Sales Club Registration](https://ci-hub.com/sales-club-registration) form. * A **CI HUB Integration SDK license**. Write to [sales@ci-hub.com](mailto\:sales@ci-hub.com). * A developer who knows TypeScript or JavaScript and your platform's API. Your developers can install the SDK and build locally before the membership and license are in place. You need both before you submit. ## The journey at a glance [#the-journey-at-a-glance] **Stage** is CI HUB's test environment. **Production** is the live environment your customers use. ## Step by step [#step-by-step] ### Build locally [#build-locally] Your developers install the SDK and build the integration on their own machine. The [SDK Workbench](/integration/getting-started/workbench), a local test tool, lets them try every part the way the CI HUB plugins will use it. ### Submit [#submit] Your developers submit the integration with one command (see the [CLI reference](/integration/reference/cli)). The same tool shows the status and results of every version you've submitted. ### Review [#review] CI HUB reviews the submission and emails the result: approved, or rejected with feedback. After a rejection, your developers address the feedback and submit again. ### Test on stage [#test-on-stage] CI HUB deploys the approved integration to its stage server. You test it there before it reaches your customers. ### Go live [#go-live] Email [integration@ci-hub.com](mailto\:integration@ci-hub.com) to request the production release. CI HUB deploys the integration to production and lets you know when it's live. ## Updates [#updates] Every later version takes the same path: build, submit, review, test on stage, then request the production release. ## Common questions [#common-questions] The Sales Club membership is free. For the Integration SDK license, write to [sales@ci-hub.com](mailto\:sales@ci-hub.com) for a quote. A tiered partner program, by feature set and depth of integration. You can resell CI HUB to your own customers at a margin, and co-marketing, enablement, and technical support are included. Yes. Your developers can install the SDK and build locally without the Sales Club membership or the license. Both are needed before you submit. Not the integration. CI HUB runs it on its stage and production servers. It calls your platform's API, which you keep running as you do today. The same way as the first version. See [Updates](#updates). ## Next steps [#next-steps] # Project Structure (/integration/getting-started/project-structure) Running `npm create @ci-hub/integration my-integration` scaffolds: ## index.ts [#indexts] All integration logic lives in `index.ts`. The file contains `defineIntegration`, every handler, and all helper functions. Split only for long static data (see below). ## When to split [#when-to-split] You might need to split your code into multiple files if you have a lot of static data like GraphQL queries, predefined renditions, or predefined filters. | File | When to extract | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `integration-types.ts` | Shared type config for `defineIntegration`, auth helpers, and `dah.ts`. See [Typed Integrations](/integration/advanced/typed-integrations). | | `dah.ts` | Direct Access Helper for browser-side upload. See [Direct Access Helper](/integration/building-an-integration/direct-access-helper). | | `dah-utils.ts` | Shared helpers imported by both `dah.ts` and `index.ts` (browser-safe code only). | | `queries.ts` | Long GraphQL query strings. if your API uses GraphQL. | | `renditions.ts` | Static rendition/conversion lists (predefined sizes, aspect ratios). | | `*.ect` | Login screen templates (ECT format). See [Login Templates](/integration/templates/overview). | `queries.ts` and `renditions.ts` are just examples, if needed you can create any file you need to store your static data. ## cihub.config.jsonc [#cihubconfigjsonc] The CLI configuration file that controls how source files, templates, and assets are discovered and bundled. Run `integration-cli config --init` to generate a starter file (see [CLI reference](/integration/reference/cli#quick-start) for your package manager). See the [CLI reference](/integration/reference/cli#configuration-file) for all available fields and defaults. ## config.json [#configjson] Integration-specific configuration. Keys are accessed via `config.get('integrationName.key')`. ```json title="src/config.json" { "serverBaseUrl": "http://localhost:8080", "IntegrationName": { "contact": { "text": "Support description", "url": { "link": "https://your-platform.example.com/help", "email": "support@example.com" } }, "authEndpoint": "/api/oauth/authorize", "tokenEndpoint": "/api/oauth/accesstoken", "clientId": "your-client-id", "maxQuerySize": 100 } } ``` ```ts title="src/index.ts" import { config } from '@ci-hub/integration-sdk' const apiUrl = config.get('IntegrationName.apiUrl') const limit = config.has('IntegrationName.uploadLimitMB') // [!code highlight] ? config.get('IntegrationName.uploadLimitMB') // [!code highlight] : 500 // [!code highlight] ``` ## Logo and glyph [#logo-and-glyph] Images are inlined as base64 data URLs. Place `logo.png` (600×134) and `glyph.png` (80×80) next to the `index.ts` file. ```ts title="src/index.ts" import { fs, path } from '@ci-hub/integration-sdk' const imageBase64 = (name: string) => `data:image/png;base64,${Buffer.from( fs.readFileSync(path.join(import.meta.dirname, name)) ).toString('base64')}` const logo = { data: imageBase64('logo.png'), width: 600, height: 134, backgroundColor: '#FFFFFF' } const glyph = { data: imageBase64('glyph.png'), width: 80, height: 80, backgroundColor: '#FFFFFF' } ``` | Field | Description | | ------------------ | ---------------------------------------------------------- | | `data` | Base64-encoded PNG as a data URI | | `width` / `height` | Pixel dimensions of the source image | | `backgroundColor` | Hex color used when the image has a transparent background | Use PNG format. Keep logos under 100 KB. The `backgroundColor` field matters for dark mode rendering in CI HUB. # SDK Workbench (/integration/getting-started/workbench) The SDK Workbench is the local stand-in for the CI HUB client. `npm run dev` serves it at `http://localhost:8080` (see [CLI](/integration/reference/cli#integration-cli-dev)). The workbench talks to your integration over the same HTTP surface the client uses. Every control in it runs one of your handlers, with the same inputs the client would send. ## What the workbench tests [#what-the-workbench-tests] * **Your handlers, not mocks.** Nothing between the workbench and your code is faked. If a flow works here, it works in the client. * **Your response shape.** Every response is validated against the schema for that handler. Failures appear in the diagnostics panel, pointing at the field. * **What the client does with your response.** A valid response that hides a button or fetches an unexpected URL shows up as an insight, not just a pass. ## How a click reaches your code [#how-a-click-reaches-your-code] Take the Navigation module. Type a folder id, press **Load**, and your `getFolder` handler runs. Everything on screen arrives in that handler's request data: the folder id, the selected filters, the data locale. The second argument carries the session, which is the access token and the `adapterData` your `login` handler returned. Both are sent on every call after login. Two consequences: * Auth must succeed before anything else works. * A mistake in what `login` returns often surfaces later, when a handler reads an `adapterData` field that was never set. See [adapterData](/integration/building-an-integration/login-flow#adapterdata). If a control runs a handler you did not export, the server replies that the method is not implemented and the workbench shows that message. ## Where to start [#where-to-start] Work down the sidebar in order. Each module depends on the ones above it. **Details.** Reads your metadata and registers your handler list. **Auth.** Everything else needs the session it produces. **Info**, if you implement it. Search and Navigation build their filter bars from what it returns. **Search** or **Navigation**, whichever your platform leads with. Everything else, in any order. *** ## Details [#details] **Runs:** no handler. The server reads every non-function property of your `defineIntegration` call and returns it, plus the list of handler names you exported. **Tests:** that your metadata is well formed and that the handlers you think you exported are exported. The **Registered Handlers** badges are the literal list of functions the server found on your integration object. A handler missing here is missing everywhere, and every feature depending on it is disabled in every other module. The capability badges are what you declared in `capabilities`. The handler list and the capabilities together decide what the rest of the workbench lets you do, so read this view before concluding that something else is broken. Press **Refresh Details** in the sidebar after changing your integration. Adding a handler or a capability does not change the gating until this runs again. See [Integration Info](/integration/reference/integration-info) and [Capabilities Reference](/integration/advanced/capabilities-reference). *** ## Auth [#auth] **Runs:** [`login`](/integration/schemas/auth/login), then [`checkToken`](/integration/schemas/auth/check-token), [`refreshToken`](/integration/schemas/auth/refresh-token) and [`logout`](/integration/schemas/auth/logout). **Tests:** the whole OAuth round trip, as the client performs it. **Login** calls your `login` handler and expects a redirect to your provider in return. The workbench opens that URL in a popup. When your provider redirects back, `login` runs a second time with the authorization code and is expected to return the token payload. The workbench stores it and immediately calls `checkToken` with it. One **Login** press therefore exercises both halves of your login handler plus the token check. If the popup closes on an error page, your second call returned no access token. The remaining buttons appear once you are logged in: | Control | Effect | | ------------------- | ----------------------------------------------------------------------------------------------------------- | | **Check Token** | Calls `checkToken` with the current access token | | **Refresh Token** | Calls `refreshToken` and replaces the stored session with what you return | | **Logout** | Calls `logout` | | **View Token JSON** | Shows what the workbench is holding. Use it to confirm `adapterData` contains what your later handlers read | `capabilities.supportsNewLoginUrl` changes which login address the workbench uses, but both forms reach the same `login` handler. See [Login Flow](/integration/building-an-integration/login-flow) and [Auth Handlers](/integration/building-an-integration/auth-handlers). *** ## Info [#info] **Runs:** [`info`](/integration/schemas/assets/info). **Tests:** the per-user configuration your integration returns after authentication. The handler is optional, but much of the workbench is built from it: pre-search filters, data locales, search configs, the option inputs on the upload and update forms, and the request headers used to fetch thumbnails. Search and Navigation call `info` themselves when they need filters, so what is listed here is exactly what those modules offer. If a filter bar is missing from Search, this view tells you whether `info` returned it. See [Info Handler](/integration/building-an-integration/info-handler) and [Filters](/integration/building-an-integration/filters). *** ## Search [#search] **Runs:** [`search`](/integration/schemas/assets/search). **Tests:** everything the client's search bar does. * Typing a query and pressing **Search** calls `search` with that text. * Selecting a filter re-runs `search` with the selected filter ids, so you can check that your handler applies them and that the filters you return mark the right options as active. * **Load more** re-runs `search` with the `more` cursor you returned, which verifies your pagination. * **Parent ID** appears when you declare `capabilities.assetSearch.supportsParentId`, and scopes the search to a folder. * **Similarity Search** appears when you declare `capabilities.assetSearch.similarSearch`. It hands `search` a base64 image alongside the query, the only case where that handler receives a file. The two accordions at the bottom call [`createAsset`](/integration/schemas/assets/create-asset) and [`updateAsset`](/integration/schemas/assets/update-asset). Search results are not a folder, so the upload accordion asks for a target parent id. The client offers upload from search results only when you declare `capabilities.supportsAddAssetInSearch`, the same flag that gates the entry in the grid's background menu. Results render as a grid. Right-clicking an asset gives the actions the client offers, covered in [The grid and its context menus](#the-grid-and-its-context-menus). See [Search](/integration/building-an-integration/search) and [`canAddAsset` in Search](/integration/building-an-integration/search#canaddasset-in-search). *** ## Navigation [#navigation] **Runs:** [`getFolder`](/integration/schemas/folders/get-folder), plus most of your mutating handlers. **Tests:** folder browsing and the permission model around it. This is the widest module in the workbench. **Load** calls `getFolder` with the folder id, starting at `root`. Double-clicking a folder in the grid calls it again for that folder, which is how you walk your tree. This module is where **capabilities** get tested, in two layers. What you return in a folder's `capabilities` decides what the client offers inside it, and the workbench enforces the same rules: return `canAddAsset: false` and the upload form is refused, with the reason shown. Mismatches between what you intended and what you returned surface here. The accordions below the folder input call one handler each, so you can exercise a handler without hunting for the right tile: | Accordion | Your handler | | --------------------- | ------------------------------------------------------------ | | Create Folder | [`createFolder`](/integration/schemas/folders/create-folder) | | Create Asset (Upload) | [`createAsset`](/integration/schemas/assets/create-asset) | | Update Asset | [`updateAsset`](/integration/schemas/assets/update-asset) | | Rename Folder | [`renameFolder`](/integration/schemas/folders/rename-folder) | | Delete Folder | [`deleteFolder`](/integration/schemas/folders/delete-folder) | | Delete Asset | [`deleteAsset`](/integration/schemas/assets/delete-asset) | | Rename Asset | [`renameAsset`](/integration/schemas/assets/rename-asset) | | Lock / Unlock Asset | [`lockAsset`](/integration/schemas/assets/lock-asset) | | Download | [`download`](/integration/schemas/assets/download) | **Download** resolves the URL through your `download` handler and shows it without fetching the file, so you can check the URL before trusting it. See [Folder Navigation](/integration/building-an-integration/folder-navigation), [Per-Folder Capabilities](/integration/building-an-integration/folder-navigation#per-folder-capabilities), [Folder Operations](/integration/building-an-integration/folder-operations), [Upload](/integration/building-an-integration/upload), [Download](/integration/building-an-integration/download) and [Asset Operations](/integration/building-an-integration/asset-operations). *** ## Versions [#versions] **Runs:** [`getAssetVersions`](/integration/schemas/assets/get-asset-versions). **Tests:** the version history of one asset. Enter an asset id and press **Load**. The **With master** checkbox is passed to your handler, so you can exercise both paths through it. The grid renders each version with the size, modified date and version label you returned, laid out the way the client lays them out. Use it to check that your version ordering and labelling read correctly to a user. See [getAssetVersions](/integration/building-an-integration/asset-operations#getassetversions). *** ## Brand [#brand] **Runs:** [`getBrandConfig`](/integration/schemas/brand/get-brand-config), then [`getBrandAssets`](/integration/schemas/brand/get-brand-assets). **Tests:** the Brand Hub surface, which needs `capabilities.supportsBrandHub` declared plus both handlers exported. **Load Brand Config** calls `getBrandConfig`. Double-clicking a category in the grid calls `getBrandAssets` with that category's `folderId` and `categoryType`, the values you returned in the config. That makes it a real test of the two handlers agreeing with each other. **Load more** pages through a category using the `more` cursor you returned. See [Brand Hub](/integration/advanced/brand-hub). *** ## Tasks [#tasks] **Runs:** [`searchTasks`](/integration/schemas/tasks/search-tasks), [`getTask`](/integration/schemas/tasks/get-task), [`getTaskAssets`](/integration/schemas/tasks/get-task-assets), [`addTaskComment`](/integration/schemas/tasks/add-task-comment), `addAssetToTask`, [`addTaskAsset`](/integration/schemas/tasks/add-task-asset), `updateTaskState`, [`updateCustomTaskState`](/integration/schemas/tasks/update-custom-task-state), [`deleteTaskAsset`](/integration/schemas/tasks/delete-task-asset). **Tests:** task workflows, which need `capabilities.tasking` declared. Searching calls `searchTasks`. Clicking a result calls `getTask`. Everything in the task detail panel maps to one handler: | Control | Your handler | | ----------------------------------- | ----------------------- | | Get Assets | `getTaskAssets` | | Add Comment | `addTaskComment` | | Add Asset (id only) | `addAssetToTask` | | Add Task Asset (full form) | `addTaskAsset` | | A badge under "Transition to state" | `updateTaskState` | | Update Custom Task State | `updateCustomTaskState` | | Remove (Delete Task Asset) | `deleteTaskAsset` | The state badges come from the `availableStates` you returned on the task, so clicking one tests that your task response and your state handler agree. After a transition or an asset change the workbench re-reads the task, which shows whether the change took effect on your side. See [Tasks](/integration/building-an-integration/tasks). *** ## Reparent [#reparent] **Runs:** [`moveAsset`](/integration/schemas/assets/move-asset) or [`moveFolder`](/integration/schemas/folders/move-folder), depending on the type toggle. **Tests:** moving something to a new parent, including moving to `root`. The same form opens from the grid's **Move** entry with the source already filled in. *** ## The grid and its context menus [#the-grid-and-its-context-menus] Search, Navigation, Versions and Brand render their results as a grid of tiles. Right-clicking a tile gives the actions the client would offer for it, and each one opens the same form the accordions use, pre-filled and locked to that item. The menu runs the same handlers listed above. What it adds is the **gating**. Every entry is checked twice: once against your handler list and capabilities, and once against the capability flags on the item you clicked. An entry you cannot use stays visible and explains itself on hover. That message is the useful part, because it tells you why the client would not offer the action to a user. Folders are the exception worth understanding. A folder listed inside another folder usually arrives with nothing but an id and a name, so the workbench does not know what it permits and will not guess. **Load actions** in its menu calls your `getFolder` for that one folder to find out. If the actions stay disabled afterwards, your `getFolder` did not return capabilities for it. **Preview Details** runs no handler. It shows one asset or folder the way the client displays it after transforming your response: dates rewritten, capabilities resolved through their fallback chain, and the classification that decides which host actions appear. Use it to check whether a field you returned survives the client's transforms. See [Asset Object](/integration/schemas/assets/asset-object) and [Asset Types](/integration/advanced/asset-types). *** ## When something is disabled [#when-something-is-disabled] There are three reasons, and the diagnostics panel names which one applies. **The handler is not exported.** Diagnostics says `Missing handler(s): `. Add the function to your `defineIntegration` call and press **Refresh Details**. **The capability is not declared.** Diagnostics says `Capability not met: `, showing the exact flag it tested. Several features need both a handler and a flag: Brand needs `supportsBrandHub`, Tasks needs `tasking`, similarity search needs `assetSearch.similarSearch`, upload from search results needs `supportsAddAssetInSearch`. Add the flag to `capabilities` and press **Refresh Details**. See [Capabilities Reference](/integration/advanced/capabilities-reference). **The item said no.** The handler exists and the capability is declared, but the folder or asset you are acting on returned a flag that forbids it, such as `canAddAsset: false` or `canDeleteAsset: false`. Nothing is wrong with your configuration. This is your own response talking, and the fix is in whatever your handler computed for that item. On any module other than Details and Auth, the panel may simply be telling you to run Details or log in first. *** ## What the workbench cannot tell you [#what-the-workbench-cannot-tell-you] Worth knowing before you treat a green result as final: * **Direct Access Helper behavior is close, but not identical.** Your helper runs in a real browser here, but not the browser environment it gets in production. MD5 is the clearest example: the workbench cannot produce one and passes your helper an empty string, so a helper that depends on it passes here and fails for users. See [Limitations](/integration/building-an-integration/direct-access-helper#limitations) and [Download Hashes](/integration/advanced/download-hashes). * **The CORS check is unauthenticated.** A provider that allows the preflight but blocks credentialed requests still passes here and fails in production. * **Batch operations are not exercised.** `batchOperations.canDelete` and `canLock` change how the client calls `deleteAsset` and `lockAsset`. The workbench acts on one item at a time. * **Host-specific behavior is out of scope.** How your assets place into InDesign, Photoshop or Office is not something a browser can test. For the hosted end of the process, see [Partner Journey](/integration/getting-started/partner-journey). *** ## Handler lookup [#handler-lookup] Every handler the workbench can call, and where to trigger it. A handler you export that is not listed here is never reached by any control. | Handler | Where in the workbench | | ------------------------------------------------------------------------------ | ------------------------------------------------------------------ | | [`addAssetToTask`](/integration/building-an-integration/tasks) | Tasks, Add Asset | | [`addTaskAsset`](/integration/schemas/tasks/add-task-asset) | Tasks, Add Task Asset | | [`addTaskComment`](/integration/schemas/tasks/add-task-comment) | Tasks, Add Comment | | [`checkToken`](/integration/schemas/auth/check-token) | Auth, Check Token, and automatically after login | | [`createAsset`](/integration/schemas/assets/create-asset) | Navigation and Search accordions, folder and listing context menus | | [`createFolder`](/integration/schemas/folders/create-folder) | Navigation accordion, folder and listing context menus | | [`deleteAsset`](/integration/schemas/assets/delete-asset) | Navigation accordion, asset context menu | | [`deleteFolder`](/integration/schemas/folders/delete-folder) | Navigation accordion, folder context menu | | [`deleteTaskAsset`](/integration/schemas/tasks/delete-task-asset) | Tasks, Delete Task Asset | | [`download`](/integration/schemas/assets/download) | Navigation accordion, asset context menu | | [`getAssetVersions`](/integration/schemas/assets/get-asset-versions) | Versions, Load; asset context menu, View Versions | | [`getBrandAssets`](/integration/schemas/brand/get-brand-assets) | Brand, opening a category and Load more | | [`getBrandConfig`](/integration/schemas/brand/get-brand-config) | Brand, Load Brand Config | | [`getFolder`](/integration/schemas/folders/get-folder) | Navigation Load and folder drill-down; folder menu, Load actions | | [`getTask`](/integration/schemas/tasks/get-task) | Tasks, clicking a result | | [`getTaskAssets`](/integration/schemas/tasks/get-task-assets) | Tasks, Get Assets | | [`info`](/integration/schemas/assets/info) | Info, Load Provider Info; and on demand from Search and Navigation | | [`lockAsset`](/integration/schemas/assets/lock-asset) | Navigation accordion, asset context menu | | [`login`](/integration/schemas/auth/login) | Auth, Login. Runs twice: the redirect, then the callback | | [`logout`](/integration/schemas/auth/logout) | Auth, Logout | | [`moveAsset`](/integration/schemas/assets/move-asset) | Reparent with type Asset; asset context menu, Move | | [`moveFolder`](/integration/schemas/folders/move-folder) | Reparent with type Folder; folder context menu, Move | | [`refreshToken`](/integration/schemas/auth/refresh-token) | Auth, Refresh Token | | [`renameAsset`](/integration/schemas/assets/rename-asset) | Navigation accordion, asset context menu | | [`renameFolder`](/integration/schemas/folders/rename-folder) | Navigation accordion, folder context menu | | [`search`](/integration/schemas/assets/search) | Search, and every filter change and Load more | | [`searchTasks`](/integration/schemas/tasks/search-tasks) | Tasks, Search and Load more | | [`updateAsset`](/integration/schemas/assets/update-asset) | Navigation and Search accordions, asset context menu | | [`updateCustomTaskState`](/integration/schemas/tasks/update-custom-task-state) | Tasks, Update Custom Task State | | [`updateTaskState`](/integration/building-an-integration/tasks) | Tasks, clicking a state badge | ## Next steps [#next-steps] # CLI (/integration/reference/cli) The `integration-cli` ships with `@ci-hub/integration-sdk` and provides commands for developing, testing, and submitting your integration. See [Installation](/integration/getting-started/installation) for setup instructions. The CLI is not installed as a global binary. Run it through your package manager (`npx`, `pnpm exec`, `yarn`, or `bunx`), or use the npm scripts included in the scaffolded project (for example, `npm run dev`). ## Quick Start [#quick-start] ```bash npm install @ci-hub/integration-sdk npx integration-cli auth login npx integration-cli config --init npx integration-cli dev ``` ```bash pnpm add @ci-hub/integration-sdk pnpm exec integration-cli auth login pnpm exec integration-cli config --init pnpm exec integration-cli dev ``` ```bash yarn add @ci-hub/integration-sdk yarn integration-cli auth login yarn integration-cli config --init yarn integration-cli dev ``` ```bash bun add @ci-hub/integration-sdk bunx integration-cli auth login bunx integration-cli config --init bunx integration-cli dev ``` *** ## Commands [#commands] ### `integration-cli dev` [#integration-cli-dev] Start the local development server with the SDK Workbench. ```bash npx integration-cli dev [--open] ``` ```bash pnpm exec integration-cli dev [--open] ``` ```bash yarn integration-cli dev [--open] ``` ```bash bunx integration-cli dev [--open] ``` | Flag | Description | | -------- | --------------------------------------- | | `--open` | Open the browser automatically on start | The server runs at `http://localhost:8080` and watches your project for changes to `.ts`, `.js`, `.json`, and `.ect` files. When a change is detected the server restarts automatically. For the workbench modules and the map of which control calls which handler, see [SDK Workbench](/integration/getting-started/workbench). **Interactive shortcuts** (while the server is running): | Key | Action | | --- | --------------- | | `r` | Restart server | | `u` | Show server URL | | `o` | Open in browser | | `c` | Clear console | | `q` | Quit | | `h` | Show help | *** ### `integration-cli auth` [#integration-cli-auth] Manage authentication with CI HUB. These commands handle **developer** authentication, your personal CI HUB account used for submitting integrations. This is separate from the auth handlers (`login`, `checkToken`, `refreshToken`) that your **integration** implements for end-user login. See [Login Flow](/integration/building-an-integration/login-flow) for integration auth. #### `auth login` [#auth-login] ```bash npx integration-cli auth login ``` ```bash pnpm exec integration-cli auth login ``` ```bash yarn integration-cli auth login ``` ```bash bunx integration-cli auth login ``` Opens the browser for CI HUB login. The CLI waits up to 5 minutes for you to complete the sign-in flow, then stores the credentials locally. #### `auth check` [#auth-check] ```bash npx integration-cli auth check ``` ```bash pnpm exec integration-cli auth check ``` ```bash yarn integration-cli auth check ``` ```bash bunx integration-cli auth check ``` Verifies that the stored token is still valid. If the token has expired, it is refreshed automatically. If the refresh also fails, the token is cleared and you will need to log in again. #### `auth logout` [#auth-logout] ```bash npx integration-cli auth logout ``` ```bash pnpm exec integration-cli auth logout ``` ```bash yarn integration-cli auth logout ``` ```bash bunx integration-cli auth logout ``` Clears all stored credentials from the local machine. *** ### `integration-cli config` [#integration-cli-config] Create or validate the project configuration file. See [Project Structure](/integration/getting-started/project-structure) for where the config file sits in the scaffold. ```bash npx integration-cli config [--init] [--check] [--name ] ``` ```bash pnpm exec integration-cli config [--init] [--check] [--name ] ``` ```bash yarn integration-cli config [--init] [--check] [--name ] ``` ```bash bunx integration-cli config [--init] [--check] [--name ] ``` | Flag | Description | | ------------------- | --------------------------------------------------------------------------- | | `--init` | Scaffold a starter config file with commented-out defaults | | `--check` | Validate the existing config file against the schema | | `--name ` | Filename to use with `--init` (`cihub.config.jsonc` or `cihub.config.json`) | * Running `integration-cli config --init` without `--name` prompts you to pick a filename interactively. * Running `integration-cli config --check` reports whether the config is valid or lists the validation errors. *** ### `integration-cli submit` [#integration-cli-submit] Bundle and submit the integration to CI HUB for review. ```bash npx integration-cli submit [--dry] ``` ```bash pnpm exec integration-cli submit [--dry] ``` ```bash yarn integration-cli submit [--dry] ``` ```bash bunx integration-cli submit [--dry] ``` | Flag | Description | | ------- | ------------------------------------------------------- | | `--dry` | List all files and warnings without actually submitting | The command resolves the bundle from your config (source files, templates, assets, and direct-access helpers), checks for violations, and uploads everything to CI HUB. You must be logged in before submitting. **Bundle violations** are reported when a file is reachable from your entry file but is not matched by your `include` patterns or is explicitly excluded. Adjust `declaration.include` / `declaration.exclude` in your config and try again. The maximum bundle size is **50 MB**. *** ## Configuration File [#configuration-file] The CLI looks for `cihub.config.jsonc` or `cihub.config.json` in the project root. All fields are optional and fall back to the defaults shown below. Run `integration-cli config --init` to generate a starter file (see [Quick Start](#quick-start) for your package manager). ### `declaration` [#declaration] Controls how the integration's TypeScript source is discovered. | Field | Default | Description | | ------------------------ | ------------------- | ---------------------------------------------------------------- | | `entryFile` | `./src/index.ts` | Path to the entry file that exports the integration's public API | | `config` | `./src/config.json` | Path to the integration's runtime JSON config | | `include` | `["src/**/*"]` | Glob patterns for files to include | | `exclude` | `[]` | Glob patterns for files to exclude | | `respectTsconfigInclude` | `true` | Merge patterns from `tsconfig.json` `include` | | `respectTsconfigExclude` | `true` | Merge patterns from `tsconfig.json` `exclude` | | `respectGitignore` | `true` | Treat `.gitignore` entries as additional excludes | ### `templates` [#templates] Controls how [ECT template](/integration/templates/overview) files are discovered. | Field | Default | Description | | ------------------------ | ------------------ | ------------------------------------------------- | | `include` | `["src/**/*.ect"]` | Glob patterns for template files to include | | `exclude` | `[]` | Glob patterns for template files to exclude | | `respectTsconfigExclude` | `true` | Merge patterns from `tsconfig.json` `exclude` | | `respectGitignore` | `true` | Treat `.gitignore` entries as additional excludes | ### `assets` [#assets] Paths to the same [logo and glyph](/integration/getting-started/project-structure#logo-and-glyph) images you pass to `defineIntegration`. The CLI reads them from disk so they can be included in the submission bundle. | Field | Default | Description | | ------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `logo` | `./src/logo.png` | Full-size logo (600×134) shown in listings and detail views. See [Integration Info → logo](/integration/reference/integration-info#logo) | | `glyph` | `./src/glyph.png` | Compact icon (80×80) used in menus and inline references. See [Integration Info → glyph](/integration/reference/integration-info#glyph) | ### `directAccessHelper` [#directaccesshelper] Paths to optional helper modules that let consumer applications call your integration's API directly, bypassing the standard handler flow. | Field | Default | Description | | ---------------- | -------------- | --------------------------------------------- | | `javascriptPath` | `./src/dah.ts` | TypeScript helper, used by all CI HUB plugins | | `pythonPath` | `./src/dah.py` | Python helper, used by CI HUB Drive | See [Direct Access Helper](/integration/building-an-integration/direct-access-helper) for how to write and build the helper module. ### `integration` [#integration] Metadata included in the submission bundle. These fields map to the [Integration Info](/integration/reference/integration-info) object that CI HUB stores for your integration. | Field | Default | Description | | --------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `my-integration` | Must match the `name` you pass to [`defineIntegration`](/integration/reference/sdk-packages#defineintegrationconfig) (lowercase, hyphenated) | | `version` | `1.0.0` | The version you are submitting. Increment this for each new submission | | `message` | `""` | Optional message for the review team | *** ## Authentication Flow [#authentication-flow] The CLI uses browser-based OAuth for authentication. When you run `integration-cli auth login`, a browser window opens where you sign in with your CI HUB account. Once the sign-in is complete, the CLI receives the tokens and stores them in an encrypted local file (`cihub.enc`). Tokens are refreshed automatically when they expire. Run `integration-cli auth logout` to clear stored credentials at any time. # Integration Info (/integration/reference/integration-info) ## Fields [#fields] ### logo [#logo] Logo image displayed in the integration list ### glyph [#glyph] Small icon displayed next to the connection name ### contact [#contact] Support contact information for this integration ### capabilities [#capabilities] Static feature flags and configuration for this integration ### capabilities.assetSearch [#capabilitiesassetsearch] When search is enabled, set `assetSearch` to an object with these fields. Set `assetSearch: false` to disable search entirely. # SDK Packages & Exports (/integration/reference/sdk-packages) Everything you need is available from `@ci-hub/integration-sdk`. You don't need to install Node.js built-ins or most third-party libraries separately. For the CLI commands that use this package (`dev`, `config`, `submit`), see the [CLI reference](/integration/reference/cli). ```ts import { // Integration defineIntegration, // Response helpers send, sendResult, sendError, sendStatus, sendAccessToken, sendRedirectUri, // Auth state helpers getStateCodeAsync, getStateAdapterDataAsync, setStateAdapterDataAsync, // Rendering render, ensureHttps, // Capabilities defaultFolderCapabilities, defaultAssetCapabilities, // Enums CategoryEnum, HashAlgorithmEnum, FieldTypeEnum, // Node.js built-ins fs, path, crypto, // Third-party axios, config, mimeTypes, oauth2, } from '@ci-hub/integration-sdk' ``` Import only what you use. *** ## Integration [#integration] ### `defineIntegration(config)` [#defineintegrationtconfigconfig] The entry point for every integration. Accepts a configuration object with metadata and all handler functions. Returns the integration definition. All handler signatures are fully typed. The SDK infers the correct `locals` and `requestData` types for each handler. Pass an optional generic `TConfig` to type `locals.adapterData`, per-handler `requestData`, and OAuth state fields instead of using manual casts. See [Typed Integrations](/integration/advanced/typed-integrations) for the full guide. ```ts export default defineIntegration({ name: 'My DAM', version: '1.0.0', logo, glyph, contact, capabilities: { /* ... */ }, login: async (locals, requestData) => { /* ... */ }, // ... other handlers }) ``` With a type config: ```ts export default defineIntegration({ name: 'My DAM', // ... handlers. locals.adapterData and requestData are typed from MyIntegrationConfig }) ``` *** ## Response helpers [#response-helpers] ### `send(data)` [#senddata] Successful response with a payload. Use for all content handlers that return data. ```ts return send({ assets: [], folders: [], filters: [], more: undefined }) ``` ### `sendResult(error, data)` [#sendresulterror-data] Explicit null-error form of `send`. Pass `null` as the first argument on success. ```ts return sendResult(null, { filters: [] }) ``` ### `sendError(message, statusCode)` [#senderrormessage-statuscode] Handler failed. The message is shown to the user in the CI HUB UI. ```ts return sendError(`Error searching assets: ${error}`, 400) ``` ### `sendStatus(code)` [#sendstatuscode] Success with no response body. Use for `deleteAsset`, `deleteFolder`, `logout`. ```ts return sendStatus(200) ``` ### `sendAccessToken(error?, token?, expiresIn?, refreshToken?, refreshExpiresIn?, adapterData?)` [#sendaccesstokentconfigerror-token-expiresin-refreshtoken-refreshexpiresin-adapterdata] Auth handlers only. Stores the session or reports an auth error. Pass the same type config as `defineIntegration` to type the `adapterData` argument. See [Auth helpers](/integration/advanced/typed-integrations#auth-helpers). ```ts // Success return sendAccessToken(null, accessToken, expiresIn, refreshToken, undefined, { resourceEndpoint: serverUrl, orgId: selectedOrg, }) // Failure return sendAccessToken('Invalid credentials. Please try again.') // Clean abort (user canceled) return sendAccessToken() ``` ### `sendRedirectUri(url)` [#sendredirecturiurl] Redirects the user to a URL. Used during OAuth flows to redirect to the authorization endpoint, or to redirect back to the integration endpoint to initialize state. ```ts return sendRedirectUri(authorizationUrl) ``` *** ## Auth state helpers [#auth-state-helpers] These persist data between redirect steps in multi-phase login flows. Data is stored server-side only. ### `getStateCodeAsync()` [#getstatecodeasync] Generates an opaque, cryptographically random state token. ```ts const state = await getStateCodeAsync() ``` ### `setStateAdapterDataAsync(state, data)` [#setstateadapterdataasynctconfigstate-data] Stores arbitrary data against a state token. Pass the same type config as `defineIntegration` to type `data` from `login.oauthState`. See [Auth helpers](/integration/advanced/typed-integrations#auth-helpers). ```ts await setStateAdapterDataAsync(state, { serverUrl, verifier }) ``` ### `getStateAdapterDataAsync(state)` [#getstateadapterdataasynctconfigstate] Retrieves data stored for a state token. Pass the same type config as `defineIntegration` to type the return value. See [Auth helpers](/integration/advanced/typed-integrations#auth-helpers). ```ts const { serverUrl, verifier } = await getStateAdapterDataAsync(state) ``` *** ## Rendering [#rendering] ### `render(templatePath, data)` [#rendertemplatepath-data] Renders an `.ect` HTML template with the provided data. Returns the rendered HTML as a response. The `.ect` extension is added automatically. ```ts return render(path.join(import.meta.dirname, 'login'), { action: locals.endpointUrl, logo, contact: config.get('myIntegration.contact'), }) ``` ### `ensureHttps(serverUrl, originOnly, dontExcept)` [#ensurehttpsserverurl-originonly-dontexcept] Normalizes a URL to HTTPS. Use on all user-provided server URLs before storing or calling them. | Parameter | Type | Description | | ------------ | --------- | ----------------------------------------------------------------------------------- | | `serverUrl` | `string` | The URL to normalize | | `originOnly` | `boolean` | If `true`, returns only the origin (protocol + hostname), stripping path/query/hash | | `dontExcept` | `boolean` | If `true`, returns empty string on invalid URL instead of throwing | ```ts const normalized = ensureHttps(userUrl, true, true) // 'https://example.com' (origin only, no throw on bad input) ``` *** ## Capabilities [#capabilities] ### `defaultFolderCapabilities` [#defaultfoldercapabilities] Default capability object for folders. All destructive flags default to `false`. Spread this first, then override: ```ts const caps = { ...defaultFolderCapabilities, canAddAsset: true, canAddFolder: true } ``` ### `defaultAssetCapabilities` [#defaultassetcapabilities] Default capability object for assets. Spread this first, then override with values derived from your system's permission data: ```ts const caps = { ...defaultAssetCapabilities, canUpdateAsset: item.permissions.canEdit } ``` *** ## Types [#types] For stricter compile-time types on `adapterData`, `requestData`, and auth state, pass a type config to `defineIntegration` and related helpers. See [Typed Integrations](/integration/advanced/typed-integrations) for the full guide, examples, and exported type reference. ### `Locals` [#locals] Type for the first argument of every handler. Inferred automatically inside `defineIntegration`. Import it only when you need to type a helper function outside the integration definition: ```ts import type { Locals } from '@ci-hub/integration-sdk' async function callApi(locals: Locals, endpoint: string) { /* ... */ } ``` ### `TypedRequestData` [#typedrequestdataq-b-p] Generic type for the second argument of handlers. Each handler inside `defineIntegration` gets a specialized version automatically (e.g., `TypedRequestData` for `search`). Import this when you need to type a helper that receives request data: ```ts import type { TypedRequestData, SearchQuery, SearchBody } from '@ci-hub/integration-sdk' function parseSearchParams(requestData: TypedRequestData) { const query = requestData.query.query || '' // ... } ``` ### `IntegrationInfo` [#integrationinfo] Type for the return value of the `info` handler. ### Type configuration exports [#type-configuration-exports] These types support the generic on `defineIntegration`, auth helpers, and DAH: | Type | Description | | -------------------------------- | ----------------------------------------------------------- | | `IntegrationTypeConfig` | Shape of the generic argument | | `IntegrationDefinition` | Full integration object type for a given config | | `AdapterDataFromConfig` | `adapterData` shape for `sendAccessToken` and merged locals | | `OAuthStateFromConfig` | `login.oauthState` shape for state helpers | | `DahTypeConfig` | Generic config for DAH (`adapterData`, `data`) | | `DahFunction` | Typed DAH handler | | `DirectAccessHelper` | Object exported from `dah.ts` | See [Exported types](/integration/advanced/typed-integrations#exported-types) for the complete list. *** ## Enums [#enums] ### `CategoryEnum` [#categoryenum] Integration category. Use in `capabilities.category`: ```ts capabilities: { category: CategoryEnum.DAM } ``` ### `HashAlgorithmEnum` [#hashalgorithmenum] Asset deduplication strategy. Use in `capabilities.assetHashAlgorithm`: ```ts capabilities: { assetHashAlgorithm: HashAlgorithmEnum.FILE_ATTRIBUTES } ``` ### `FieldTypeEnum` [#fieldtypeenum] Custom metadata field types. Use in `checkToken` values and custom metadata declarations: ```ts values: [{ id: 'email', name: 'Email', value: user.email, type: FieldTypeEnum.TEXT }] ``` *** ## Node.js built-ins [#nodejs-built-ins] | Export | Module | Common use | | -------- | ------------- | ---------------------------------------------------------- | | `fs` | `node:fs` | `fs.readFileSync`, loading logo/glyph images | | `path` | `node:path` | `path.join(import.meta.dirname, 'logo.png')` | | `crypto` | `node:crypto` | `crypto.randomBytes`, `crypto.createHash` for PKCE helpers | *** ## Third-party libraries [#third-party-libraries] ### `axios` [#axios] Pre-configured Axios instance for HTTP requests. ```ts const { data } = await axios.get(url, { headers, params }) const { data } = await axios.post(url, body, { headers }) await axios.put(uploadUrl, buffer, { headers: { 'Content-Type': mimeType }, maxContentLength: Infinity, maxBodyLength: Infinity, }) ``` ### `config` [#config] Typed config reader backed by [node-config](https://github.com/node-config/node-config). ```ts config.has('myIntegration.clientId') // boolean, always check optional keys config.get('myIntegration.clientId') // string | number | object, throws if missing config.get('myIntegration.limit') // typed get ``` ### `mimeTypes` [#mimetypes] MIME type lookup from [`mime-types`](https://github.com/jshttp/mime-types). ```ts mimeTypes.lookup('photo.jpg') // → 'image/jpeg' mimeTypes.extension('image/jpeg') // → 'jpeg' mimeTypes.lookup(filename) || 'application/octet-stream' // safe fallback ``` ### `oauth2` [#oauth2] OAuth 2.0 client from [`simple-oauth2`](https://github.com/lelylan/simple-oauth2). Used to implement authorization code + PKCE flows. ```ts const client = new oauth2.AuthorizationCode({ client: { id: 'clientId', secret: '' }, auth: { tokenHost, tokenPath, authorizePath, revokePath }, options: { bodyFormat: 'form' }, }) const authUrl = client.authorizeURL({ redirect_uri, scope, state, code_challenge }) const { token } = await client.getToken({ code, redirect_uri, code_verifier }) const existing = client.createToken({ refresh_token }) const { token: t} = await existing.refresh({ grant_type: 'refresh_token' }) const t = client.createToken({ access_token, refresh_token }) await t.revokeAll() ``` See [Login Flow →](/integration/building-an-integration/login-flow) for the full OAuth 2.0 + PKCE implementation. # Template Examples (/integration/templates/examples) Five production templates showing common login screen patterns. Each is a complete `.ect` file. ## 1. Server URL Form [#1-server-url-form] Single URL field. The user enters their portal URL, then the handler redirects to OAuth. ```html <% extend 'login-template.ect' %>

Please enter the URL to your INTEGRATION_NAME portal.


``` Rendered with: ```ts return render(path.join(import.meta.dirname, 'select-serverurl'), { title: 'Select INTEGRATION_NAME Portal', action: urlObject.toString(), serverUrl: serverUrl || 'https://your-instance.example.com', logo, contact, error: serverUrlError ? 'Invalid Url (System is not a valid INTEGRATION_NAME system).' : undefined }) ``` ## 2. Credentials Form [#2-credentials-form] Three credential fields: cloud name, API key, and API secret. Validates against the platform API before completing login. ```html <% extend 'login-template.ect' %>

Please enter your credentials.


``` The handler re-renders this template with an `error` message on validation failure: ```ts const render = error => res.render(path.join(import.meta.dirname, 'login'), Object.assign({ title: 'INTEGRATION_NAME Login', action: endpointUrlWithParam({ state }), logo, providerName: 'INTEGRATION_NAME', error }, token)) ``` ## 3. Tenant URL + Environment Selector [#3-tenant-url--environment-selector] Conditional dropdown for server type (production/UAT) plus a tenant URL field. The `@displayDropDown` flag controls whether the environment selector appears. ```html <% extend 'login-template.ect' %>

Please enter your INTEGRATION_NAME Tenant URL.


<% if @displayDropDown : %>
<% end %>
``` Key pattern: `<% if @displayDropDown : %>` conditionally shows form sections based on integration configuration. ## 4. Organization Select [#4-organization-select] Dynamic dropdown populated from an array of organizations fetched after initial authentication. ```html <% extend 'login-template.ect' %>

Please select your organization.


<% if @organizations?.length : %>
<% end %>
``` The handler passes the organizations array: ```ts return render(path.join(import.meta.dirname, 'select-org'), { action: urlObject.toString(), organizations: orgs.map(o => ({ id: o.id, name: o.name })), logo, contact }) ``` Key patterns: * `@organizations?.length` safe-navigates and checks for a non-empty array * `<% for entry in @organizations : %>` loops to generate `