diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..12ff1e64 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,59 @@ +# Dependencies +node_modules/ +**/node_modules/ + +# Build outputs +dist/ +**/dist/ + +# Git +.git/ +.gitignore + +# CI/CD +.github/ +.gitlab-ci.yml +.travis.yml + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Testing +test/ +tests/ +__tests__/ +*.test.js +*.spec.js +coverage/ +.nyc_output/ + +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Environment +.env +.env.* + +# Temporary files +*.tmp +*.temp +.cache/ + +# Examples and scripts +examples/ +bin/ + +# Other packages (we only need mcp-server) +packages/*/ +!packages/mcp-server/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6e879421..f4392cba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,12 +1,14 @@ name: CI on: push: - branches-ignore: - - 'generated' - - 'codegen/**' - - 'integrated/**' - - 'stl-preview-head/**' - - 'stl-preview-base/**' + branches: + - '**' + - '!integrated/**' + - '!stl-preview-head/**' + - '!stl-preview-base/**' + - '!generated' + - '!codegen/**' + - 'codegen/stl/**' pull_request: branches-ignore: - 'stl-preview-head/**' @@ -17,7 +19,7 @@ jobs: timeout-minutes: 10 name: lint runs-on: ${{ github.repository == 'stainless-sdks/imagekit-typescript' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} - if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata') steps: - uses: actions/checkout@v6 @@ -36,7 +38,7 @@ jobs: timeout-minutes: 5 name: build runs-on: ${{ github.repository == 'stainless-sdks/imagekit-typescript' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} - if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata') permissions: contents: read id-token: write @@ -55,14 +57,18 @@ jobs: run: ./scripts/build - name: Get GitHub OIDC Token - if: github.repository == 'stainless-sdks/imagekit-typescript' + if: |- + github.repository == 'stainless-sdks/imagekit-typescript' && + !startsWith(github.ref, 'refs/heads/stl/') id: github-oidc uses: actions/github-script@v8 with: script: core.setOutput('github_token', await core.getIDToken()); - name: Upload tarball - if: github.repository == 'stainless-sdks/imagekit-typescript' + if: |- + github.repository == 'stainless-sdks/imagekit-typescript' && + !startsWith(github.ref, 'refs/heads/stl/') env: URL: https://pkg.stainless.com/s AUTH: ${{ steps.github-oidc.outputs.github_token }} @@ -70,7 +76,9 @@ jobs: run: ./scripts/utils/upload-artifact.sh - name: Upload MCP Server tarball - if: github.repository == 'stainless-sdks/imagekit-typescript' + if: |- + github.repository == 'stainless-sdks/imagekit-typescript' && + !startsWith(github.ref, 'refs/heads/stl/') env: URL: https://pkg.stainless.com/s?subpackage=mcp-server AUTH: ${{ steps.github-oidc.outputs.github_token }} diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 5de47cbe..fbddfc6a 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -33,13 +33,14 @@ jobs: - name: Publish to NPM run: | - if [ -n "${{ github.event.inputs.path }}" ]; then - PATHS_RELEASED='[\"${{ github.event.inputs.path }}\"]' + if [ -n "$INPUT_PATH" ]; then + PATHS_RELEASED="[\"$INPUT_PATH\"]" else PATHS_RELEASED='[\".\", \"packages/mcp-server\"]' fi yarn tsn scripts/publish-packages.ts "{ \"paths_released\": \"$PATHS_RELEASED\" }" env: + INPUT_PATH: ${{ github.event.inputs.path }} NPM_TOKEN: ${{ secrets.IMAGE_KIT_NPM_TOKEN || secrets.NPM_TOKEN }} - name: Upload MCP Server DXT GitHub release asset diff --git a/.gitignore b/.gitignore index d62bea50..b7d4f6b9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .prism.log +.stdy.log node_modules yarn-error.log codegen.log diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c575a162..6731678f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "7.3.0" + ".": "7.4.0" } diff --git a/.stats.yml b/.stats.yml index dbc39e12..749d6988 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 47 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/imagekit-inc%2Fimagekit-13fc3d7cafdea492f62eef7c1d63424d6d9d8adbff74b9f6ca6fd3fc12a36840.yml -openapi_spec_hash: a1fe6fa48207791657a1ea2d60a6dfcc +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/imagekit-inc%2Fimagekit-83a7f3659a437113f2a79e1e72794be19eff00ec232fd0206198c80364ccfebf.yml +openapi_spec_hash: b327552548ab641eb4ea3b45e643dfce config_hash: 47cb702ee2cb52c58d803ae39ade9b44 diff --git a/CHANGELOG.md b/CHANGELOG.md index 32b4dc54..e3a936ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,85 @@ # Changelog +## 7.4.0 (2026-04-02) + +Full Changelog: [v7.3.0...v7.4.0](https://github.com/imagekit-developer/imagekit-nodejs/compare/v7.3.0...v7.4.0) + +### Features + +* **api:** dpr type update ([81ec737](https://github.com/imagekit-developer/imagekit-nodejs/commit/81ec737f908203323d163470fd3a86abbb79db27)) +* **api:** revert dpr breaking change ([2543278](https://github.com/imagekit-developer/imagekit-nodejs/commit/2543278ccc78081ffa4cbd82dd1061310c480529)) +* **mcp:** add an option to disable code tool ([af87a8b](https://github.com/imagekit-developer/imagekit-nodejs/commit/af87a8ba4f06ca786ec611177663e21f85e2f8d4)) +* **mcp:** add initial server instructions ([cdce131](https://github.com/imagekit-developer/imagekit-nodejs/commit/cdce131dc17fba5469393a285ac536acd74742b2)) + + +### Bug Fixes + +* **client:** avoid memory leak with abort signals ([c08f7c0](https://github.com/imagekit-developer/imagekit-nodejs/commit/c08f7c04267e000d51cfad22ec8337e456d20171)) +* **client:** avoid removing abort listener too early ([0738e88](https://github.com/imagekit-developer/imagekit-nodejs/commit/0738e8884a59ddac579fab6a65e0221fdff4247c)) +* **client:** preserve URL params already embedded in path ([9fed3c5](https://github.com/imagekit-developer/imagekit-nodejs/commit/9fed3c543ed9c115c50f56d22a52bff307cc6d08)) +* **docs/contributing:** correct pnpm link command ([743a112](https://github.com/imagekit-developer/imagekit-nodejs/commit/743a1126b13d90832ccac545474eda7a1094043f)) +* fix request delays for retrying to be more respectful of high requested delays ([8cc484f](https://github.com/imagekit-developer/imagekit-nodejs/commit/8cc484fda37d8a3188f10f3dfa1cd9ab291f10f6)) +* **mcp:** bump agents version in cloudflare worker MCP servers ([207aff5](https://github.com/imagekit-developer/imagekit-nodejs/commit/207aff5eb71b0a5d0aed71de3cb6fe6c3c965340)) +* **mcp:** initialize SDK lazily to avoid failing the connection on init errors ([66c5305](https://github.com/imagekit-developer/imagekit-nodejs/commit/66c53054ce63794350a9939b8f38ecea3ddec428)) +* **mcp:** update prompt ([db925be](https://github.com/imagekit-developer/imagekit-nodejs/commit/db925be3e3cae3ab8cb5e4f4b8f34909a21791e7)) + + +### Chores + +* **ci:** escape input path in publish-npm workflow ([cbb4d36](https://github.com/imagekit-developer/imagekit-nodejs/commit/cbb4d3670cf06302124293e1221f8fc09fc48b0c)) +* **ci:** skip lint on metadata-only changes ([a4ff868](https://github.com/imagekit-developer/imagekit-nodejs/commit/a4ff868b281bc52a19bccd7a129a47222a8aae79)) +* **ci:** skip uploading artifacts on stainless-internal branches ([7d86a36](https://github.com/imagekit-developer/imagekit-nodejs/commit/7d86a36233f5ea27342329f6545d2b46eddbd219)) +* **client:** do not parse responses with empty content-length ([4b5fcbf](https://github.com/imagekit-developer/imagekit-nodejs/commit/4b5fcbfd1188573ccd1cea40b8e4924a5e2051dc)) +* **client:** restructure abort controller binding ([46c04e1](https://github.com/imagekit-developer/imagekit-nodejs/commit/46c04e16c46bca7bc1b0383d151f027d7d918611)) +* **internal/client:** fix form-urlencoded requests ([d96f483](https://github.com/imagekit-developer/imagekit-nodejs/commit/d96f4832db9e8c16cbeae32f9a7eb46234bb64ed)) +* **internal:** add health check to MCP server when running in HTTP mode ([83d1174](https://github.com/imagekit-developer/imagekit-nodejs/commit/83d1174751241a66748b9d0f4b2b92f37715d4ad)) +* **internal:** allow basic filtering of methods allowed for MCP code mode ([4a86182](https://github.com/imagekit-developer/imagekit-nodejs/commit/4a861827d463d2b6e9812a4aa58d2df14cb356bf)) +* **internal:** allow setting x-stainless-api-key header on mcp server requests ([a72133c](https://github.com/imagekit-developer/imagekit-nodejs/commit/a72133c81d0f9ad9587793bb92c06963fce21e8e)) +* **internal:** always generate MCP server dockerfiles and upgrade associated dependencies ([90eae18](https://github.com/imagekit-developer/imagekit-nodejs/commit/90eae18e29708d7596a6e783cad196c9a4f75f39)) +* **internal:** avoid type checking errors with ts-reset ([7cd3980](https://github.com/imagekit-developer/imagekit-nodejs/commit/7cd398067ad0736b67bfb3d8ace58d15a94c1fd2)) +* **internal:** bump @modelcontextprotocol/sdk, @hono/node-server, and minimatch ([a0031e0](https://github.com/imagekit-developer/imagekit-nodejs/commit/a0031e0a7be090912d18950ae5acffcef7b416e5)) +* **internal:** cache fetch instruction calls in MCP server ([7738ab8](https://github.com/imagekit-developer/imagekit-nodejs/commit/7738ab86d47fbca9a3c05c2cd48910d43d557c43)) +* **internal:** codegen related update ([60e54a6](https://github.com/imagekit-developer/imagekit-nodejs/commit/60e54a6b9efef0dd8c9f2ffc900ea9a518188ec3)) +* **internal:** codegen related update ([5c368b8](https://github.com/imagekit-developer/imagekit-nodejs/commit/5c368b89c0531200671ba1899121c2bf8c1bb40f)) +* **internal:** codegen related update ([4178900](https://github.com/imagekit-developer/imagekit-nodejs/commit/41789006a0bdd72bf302bea9c493efcca5927f5d)) +* **internal:** fix MCP docker image builds in yarn projects ([5f10f73](https://github.com/imagekit-developer/imagekit-nodejs/commit/5f10f733842b162e6ae8837b7c22def0cd6eaa79)) +* **internal:** fix MCP Dockerfiles so they can be built without buildkit ([9dde351](https://github.com/imagekit-developer/imagekit-nodejs/commit/9dde351b748d8a2e2fe56321b477ae214e679431)) +* **internal:** fix MCP Dockerfiles so they can be built without buildkit ([62b9ad0](https://github.com/imagekit-developer/imagekit-nodejs/commit/62b9ad0590c40c17cfcd1e7a68f2d5b2b6171cd1)) +* **internal:** fix MCP server TS errors that occur with required client options ([14154e2](https://github.com/imagekit-developer/imagekit-nodejs/commit/14154e2c6d8bdd5f11705deb3709acca73bc0f26)) +* **internal:** improve layout of generated MCP server files ([b2e0a75](https://github.com/imagekit-developer/imagekit-nodejs/commit/b2e0a75d79757596569d0277467ccad531d49bdd)) +* **internal:** improve local docs search for MCP servers ([ad984eb](https://github.com/imagekit-developer/imagekit-nodejs/commit/ad984eb6639ce557bea1b552e4ce6d9f66f0c56c)) +* **internal:** improve local docs search for MCP servers ([d4db198](https://github.com/imagekit-developer/imagekit-nodejs/commit/d4db19830e537311a352ea8a68a4662745e35332)) +* **internal:** make generated MCP servers compatible with Cloudflare worker environments ([419e72f](https://github.com/imagekit-developer/imagekit-nodejs/commit/419e72f03c8854a3c6b6d4654ea474c3c926287c)) +* **internal:** make MCP code execution location configurable via a flag ([497c926](https://github.com/imagekit-developer/imagekit-nodejs/commit/497c9269a3438a872c1ddb7a213d34abe90d6f6b)) +* **internal:** move stringifyQuery implementation to internal function ([60f7ea6](https://github.com/imagekit-developer/imagekit-nodejs/commit/60f7ea6ff1946645f7e65ab93b0c77c4db250f83)) +* **internal:** refactor flag parsing for MCP servers and add debug flag ([ff4b97e](https://github.com/imagekit-developer/imagekit-nodejs/commit/ff4b97e40fb46ca0b4f3229074c3f614b045641c)) +* **internal:** remove mock server code ([f1deef8](https://github.com/imagekit-developer/imagekit-nodejs/commit/f1deef8b69950e5917919a9fc619b558a65fe5b7)) +* **internal:** support custom-instructions-path flag in MCP servers ([14dec19](https://github.com/imagekit-developer/imagekit-nodejs/commit/14dec19d001aa203525ce5e713d79243a431342e)) +* **internal:** support local docs search in MCP servers ([03eef26](https://github.com/imagekit-developer/imagekit-nodejs/commit/03eef26ad1910d0d5da0fbe12f9a6bb6979f9b3e)) +* **internal:** support oauth authorization code flow for MCP servers ([5f6c688](https://github.com/imagekit-developer/imagekit-nodejs/commit/5f6c688f4f41df60d88fce94bc10cfdce4e29d78)) +* **internal:** support type annotations when running MCP in local execution mode ([bd8528f](https://github.com/imagekit-developer/imagekit-nodejs/commit/bd8528f9e38452de11e5a3976a0c7134102edbec)) +* **internal:** support x-stainless-mcp-client-envs header in MCP servers ([6b2f378](https://github.com/imagekit-developer/imagekit-nodejs/commit/6b2f37811676e4d1fdc24a175c477959b7aacde1)) +* **internal:** support x-stainless-mcp-client-permissions headers in MCP servers ([6e75dad](https://github.com/imagekit-developer/imagekit-nodejs/commit/6e75dad258809bb73b8d4e05195eea89afa7edf8)) +* **internal:** switch MCP servers to use pino for logging ([f08d300](https://github.com/imagekit-developer/imagekit-nodejs/commit/f08d3006d05cc29718533591605500ff6edd12f7)) +* **internal:** tweak CI branches ([aae2960](https://github.com/imagekit-developer/imagekit-nodejs/commit/aae29609043cb7d6fc385cfa886e877437397357)) +* **internal:** update agents version ([e39e377](https://github.com/imagekit-developer/imagekit-nodejs/commit/e39e3777d9d0ccd225774c2a889aa6b6c81a6402)) +* **internal:** update dependencies to address dependabot vulnerabilities ([c6f8d11](https://github.com/imagekit-developer/imagekit-nodejs/commit/c6f8d113f12ef419981dfb5df68208c079f1970b)) +* **internal:** update gitignore ([d36a938](https://github.com/imagekit-developer/imagekit-nodejs/commit/d36a938ec305af370a93674ff846e9ea695f8d6c)) +* **internal:** upgrade @modelcontextprotocol/sdk and hono ([446fc85](https://github.com/imagekit-developer/imagekit-nodejs/commit/446fc85863574d74d94918ee09aff23f4ed373b4)) +* **internal:** upgrade hono ([61a5d88](https://github.com/imagekit-developer/imagekit-nodejs/commit/61a5d8863e4fcb692d187bb0a7b44e1788faf8ee)) +* **internal:** use link instead of file in MCP server package.json files ([4939cda](https://github.com/imagekit-developer/imagekit-nodejs/commit/4939cdab635c72a63f2570de3e41f77b81976478)) +* **internal:** use x-stainless-mcp-client-envs header for MCP remote code tool calls ([d128af7](https://github.com/imagekit-developer/imagekit-nodejs/commit/d128af71272254b0f6fbc52029e941e674b594cf)) +* **mcp-server:** add support for session id, forward client info ([36ec509](https://github.com/imagekit-developer/imagekit-nodejs/commit/36ec509701f79fb629d69346ab9075d935b05d4e)) +* **mcp-server:** improve instructions ([9afa574](https://github.com/imagekit-developer/imagekit-nodejs/commit/9afa574d4589f6229784ba766e604a0498f506a3)) +* **mcp-server:** log client info ([20299c3](https://github.com/imagekit-developer/imagekit-nodejs/commit/20299c30d17b963360b904b6b9c1c5ebe19f79d5)) +* **mcp-server:** return access instructions for 404 without API key ([568dd2a](https://github.com/imagekit-developer/imagekit-nodejs/commit/568dd2ae4a631c3b64812d1b13af5e6aaba6ebd1)) +* **mcp:** correctly update version in sync with sdk ([57fa966](https://github.com/imagekit-developer/imagekit-nodejs/commit/57fa966d57b1069c554658921a3d649a563e4e12)) +* **mcp:** forward STAINLESS_API_KEY to docs search endpoint ([bf91d73](https://github.com/imagekit-developer/imagekit-nodejs/commit/bf91d7300f134a716038b00bbdcf0cd5932176ea)) +* **tests:** update webhook tests ([f179fa9](https://github.com/imagekit-developer/imagekit-nodejs/commit/f179fa9536d097bcaed31310deeadbfc74457814)) +* update mock server docs ([8d9ad04](https://github.com/imagekit-developer/imagekit-nodejs/commit/8d9ad04f864ca543a065a99cc041a436dd53069a)) +* update placeholder string ([f8f62ae](https://github.com/imagekit-developer/imagekit-nodejs/commit/f8f62ae1890416cb5322c7d7b7ee2235b252983b)) +* use proper capitalization for WebSockets ([e6e8ed6](https://github.com/imagekit-developer/imagekit-nodejs/commit/e6e8ed66ee0b76db104b7112c1540fa021b005ea)) + ## 7.3.0 (2026-02-02) Full Changelog: [v7.2.2...v7.3.0](https://github.com/imagekit-developer/imagekit-nodejs/compare/v7.2.2...v7.3.0) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 61483a34..8cdc92ac 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,17 +60,11 @@ $ yarn link @imagekit/nodejs # With pnpm $ pnpm link --global $ cd ../my-package -$ pnpm link -—global @imagekit/nodejs +$ pnpm link --global @imagekit/nodejs ``` ## Running tests -Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. - -```sh -$ npx prism mock path/to/your/openapi.yml -``` - ```sh $ yarn run test ``` diff --git a/package.json b/package.json index 2c422387..af9466f2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@imagekit/nodejs", - "version": "7.3.0", + "version": "7.4.0", "description": "Offical NodeJS SDK for ImageKit.io integration", "author": "Image Kit ", "types": "dist/index.d.ts", @@ -52,6 +52,17 @@ "typescript": "5.8.3", "typescript-eslint": "8.31.1" }, + "overrides": { + "minimatch": "^9.0.5" + }, + "pnpm": { + "overrides": { + "minimatch": "^9.0.5" + } + }, + "resolutions": { + "minimatch": "^9.0.5" + }, "exports": { ".": { "import": "./dist/index.mjs", diff --git a/packages/mcp-server/Dockerfile b/packages/mcp-server/Dockerfile new file mode 100644 index 00000000..591955c5 --- /dev/null +++ b/packages/mcp-server/Dockerfile @@ -0,0 +1,78 @@ +# Dockerfile for Image Kit MCP Server +# +# This Dockerfile builds a Docker image for the MCP Server. +# +# To build the image locally: +# docker build -f packages/mcp-server/Dockerfile -t @imagekit/api-mcp:local . +# +# To run the image: +# docker run -i @imagekit/api-mcp:local [OPTIONS] +# +# Common options: +# --tool= Include specific tools +# --resource= Include tools for specific resources +# --operation=read|write Filter by operation type +# --client= Set client compatibility (e.g., claude, cursor) +# --transport= Set transport type (stdio or http) +# +# For a full list of options: +# docker run -i @imagekit/api-mcp:local --help +# +# Note: The MCP server uses stdio transport by default. Docker's -i flag +# enables interactive mode, allowing the container to communicate over stdin/stdout. + +# Build stage +FROM node:24-alpine AS builder + +# Install bash for build script +RUN apk add --no-cache bash openssl + +# Set working directory +WORKDIR /build + +# Copy entire repository +COPY . . + +# Install all dependencies and build everything +RUN yarn install --frozen-lockfile && \ + yarn build && \ + # Remove the symlink to the SDK so it doesn't interfere with the explicit COPY below + rm -Rf packages/mcp-server/node_modules/@imagekit/nodejs + +FROM denoland/deno:alpine-2.7.1 + +# Install node and npm +RUN apk add --no-cache nodejs npm + +ENV LD_LIBRARY_PATH=/usr/lib:/usr/local/lib + +# Add non-root user +RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001 + +# Set working directory +WORKDIR /app + +# Copy the built mcp-server dist directory +COPY --from=builder /build/packages/mcp-server/dist ./ + +# Copy node_modules from mcp-server (includes all production deps) +COPY --from=builder /build/packages/mcp-server/node_modules ./node_modules + +# Copy the built @imagekit/nodejs into node_modules +COPY --from=builder /build/dist ./node_modules/@imagekit/nodejs + +# Change ownership to nodejs user +RUN chown -R nodejs:nodejs /app +RUN chown -R nodejs:nodejs /deno-dir + +# Switch to non-root user +USER nodejs + +# The MCP server uses stdio transport by default +# No exposed ports needed for stdio communication + +# Set the entrypoint to the MCP server +ENTRYPOINT ["node", "index.js"] + +# Allow passing arguments to the MCP server +CMD [] diff --git a/packages/mcp-server/cloudflare-worker/package.json b/packages/mcp-server/cloudflare-worker/package.json index dfdc2bbc..84c0823b 100644 --- a/packages/mcp-server/cloudflare-worker/package.json +++ b/packages/mcp-server/cloudflare-worker/package.json @@ -18,9 +18,9 @@ }, "dependencies": { "@cloudflare/workers-oauth-provider": "^0.0.5", - "@modelcontextprotocol/sdk": "^1.25.2", - "agents": "^0.0.88", - "hono": "^4.11.4", + "@modelcontextprotocol/sdk": "^1.27.1", + "agents": "^0.8.5", + "hono": "^4.12.4", "@imagekit/api-mcp": "latest", "zod": "^3.24.4" } diff --git a/packages/mcp-server/cloudflare-worker/worker-configuration.d.ts b/packages/mcp-server/cloudflare-worker/worker-configuration.d.ts index e145ef08..432fe3e0 100644 --- a/packages/mcp-server/cloudflare-worker/worker-configuration.d.ts +++ b/packages/mcp-server/cloudflare-worker/worker-configuration.d.ts @@ -8214,7 +8214,7 @@ interface Ai_Cf_Deepgram_Flux_Input { tag?: string; } /** - * Output will be returned as websocket messages. + * Output will be returned as WebSocket messages. */ interface Ai_Cf_Deepgram_Flux_Output { /** @@ -8428,7 +8428,7 @@ type AiOptions = { */ queueRequest?: boolean; /** - * Establish websocket connections, only works for supported models + * Establish WebSocket connections, only works for supported models */ websocket?: boolean; /** @@ -9372,7 +9372,7 @@ interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { certNotAfter: ""; } /** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = +declare type CertVerificationStatus = /** Authentication succeeded */ "SUCCESS" /** No certificate was presented */ @@ -9440,7 +9440,7 @@ interface D1ExecResult { count: number; duration: number; } -type D1SessionConstraint = +type D1SessionConstraint = // Indicates that the first query should go to the primary, and the rest queries // using the same D1DatabaseSession will go to any replica that is consistent with // the bookmark maintained by the session (returned by the first query). @@ -10061,7 +10061,7 @@ declare namespace Rpc { // The reason for using a generic type here is to build a serializable subset of structured // cloneable composite types. This allows types defined with the "interface" keyword to pass the // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. - type Serializable = + type Serializable = // Structured cloneables BaseType // Structured cloneable composites @@ -10435,7 +10435,7 @@ declare namespace TailStream { } // This marks the worker handler return information. // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue + // returning. For example - WebSockets that return an http upgrade response but then continue // streaming information or SSE http connections. interface Return { readonly type: "return"; diff --git a/packages/mcp-server/manifest.json b/packages/mcp-server/manifest.json index 0e5a8790..934e4661 100644 --- a/packages/mcp-server/manifest.json +++ b/packages/mcp-server/manifest.json @@ -1,7 +1,7 @@ { "dxt_version": "0.2", "name": "@imagekit/api-mcp", - "version": "0.0.1-alpha.0", + "version": "7.4.0", "description": "The official MCP Server for the Image Kit API", "author": { "name": "Image Kit", @@ -18,7 +18,9 @@ "entry_point": "index.js", "mcp_config": { "command": "node", - "args": ["${__dirname}/index.js"], + "args": [ + "${__dirname}/index.js" + ], "env": { "IMAGEKIT_PRIVATE_KEY": "${user_config.IMAGEKIT_PRIVATE_KEY}", "OPTIONAL_IMAGEKIT_IGNORES_THIS": "${user_config.OPTIONAL_IMAGEKIT_IGNORES_THIS}", @@ -53,5 +55,7 @@ "node": ">=18.0.0" } }, - "keywords": ["api"] + "keywords": [ + "api" + ] } diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 56c2098f..26fcf65c 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "@imagekit/api-mcp", - "version": "7.3.0", + "version": "7.4.0", "description": "The official MCP Server for the Image Kit API", "author": "Image Kit ", "types": "dist/index.d.ts", @@ -26,18 +26,26 @@ "format": "prettier --write --cache --cache-strategy metadata . !dist", "prepare": "npm run build", "tsn": "ts-node -r tsconfig-paths/register", - "lint": "eslint --ext ts,js .", - "fix": "eslint --fix --ext ts,js ." + "lint": "eslint .", + "fix": "eslint --fix ." }, "dependencies": { - "@imagekit/nodejs": "file:../../dist/", + "@imagekit/nodejs": "link:../../dist/", + "ajv": "^8.18.0", "@cloudflare/cabidela": "^0.2.4", - "@modelcontextprotocol/sdk": "^1.25.2", + "@hono/node-server": "^1.19.10", + "@modelcontextprotocol/sdk": "^1.27.1", + "hono": "^4.12.4", "@valtown/deno-http-worker": "^0.0.21", + "cookie-parser": "^1.4.6", "cors": "^2.8.5", "express": "^5.1.0", "fuse.js": "^7.1.0", + "minisearch": "^7.2.0", "jq-web": "https://github.com/stainless-api/jq-web/releases/download/v0.8.8/jq-web.tar.gz", + "pino": "^10.3.1", + "pino-http": "^11.0.0", + "pino-pretty": "^13.1.3", "qs": "^6.14.1", "typescript": "5.8.3", "yargs": "^17.7.2", @@ -50,6 +58,7 @@ }, "devDependencies": { "@anthropic-ai/mcpb": "^2.1.2", + "@types/cookie-parser": "^1.4.10", "@types/cors": "^2.8.19", "@types/express": "^5.0.3", "@types/jest": "^29.4.0", @@ -57,9 +66,9 @@ "@types/yargs": "^17.0.8", "@typescript-eslint/eslint-plugin": "8.31.1", "@typescript-eslint/parser": "8.31.1", - "eslint": "^8.49.0", - "eslint-plugin-prettier": "^5.0.1", - "eslint-plugin-unused-imports": "^3.0.0", + "eslint": "^9.39.1", + "eslint-plugin-prettier": "^5.4.1", + "eslint-plugin-unused-imports": "^4.1.4", "jest": "^29.4.0", "prettier": "^3.0.0", "ts-jest": "^29.1.0", diff --git a/packages/mcp-server/src/headers.ts b/packages/mcp-server/src/auth.ts similarity index 59% rename from packages/mcp-server/src/headers.ts rename to packages/mcp-server/src/auth.ts index 40fd3090..085cac43 100644 --- a/packages/mcp-server/src/headers.ts +++ b/packages/mcp-server/src/auth.ts @@ -2,8 +2,9 @@ import { IncomingMessage } from 'node:http'; import { ClientOptions } from '@imagekit/nodejs'; +import { McpOptions } from './options'; -export const parseAuthHeaders = (req: IncomingMessage): Partial => { +export const parseClientAuthHeaders = (req: IncomingMessage, required?: boolean): Partial => { if (req.headers.authorization) { const scheme = req.headers.authorization.split(' ')[0]!; const value = req.headers.authorization.slice(scheme.length + 1); @@ -19,6 +20,8 @@ export const parseAuthHeaders = (req: IncomingMessage): Partial = 'Unsupported authorization scheme. Expected the "Authorization" header to be a supported scheme (Basic).', ); } + } else if (required) { + throw new Error('Missing required Authorization header; see WWW-Authenticate header for details.'); } const privateKey = @@ -31,3 +34,17 @@ export const parseAuthHeaders = (req: IncomingMessage): Partial = : req.headers['x-optional-imagekit-ignores-this']; return { privateKey, password }; }; + +export const getStainlessApiKey = (req: IncomingMessage, mcpOptions: McpOptions): string | undefined => { + // Try to get the key from the x-stainless-api-key header + const headerKey = + Array.isArray(req.headers['x-stainless-api-key']) ? + req.headers['x-stainless-api-key'][0] + : req.headers['x-stainless-api-key']; + if (headerKey && typeof headerKey === 'string') { + return headerKey; + } + + // Fall back to value set in the mcpOptions (e.g. from environment variable), if provided + return mcpOptions.stainlessApiKey; +}; diff --git a/packages/mcp-server/src/code-tool-paths.cts b/packages/mcp-server/src/code-tool-paths.cts new file mode 100644 index 00000000..78263e45 --- /dev/null +++ b/packages/mcp-server/src/code-tool-paths.cts @@ -0,0 +1,5 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export function getWorkerPath(): string { + return require.resolve('./code-tool-worker.mjs'); +} diff --git a/packages/mcp-server/src/code-tool-types.ts b/packages/mcp-server/src/code-tool-types.ts index 394bec98..c29cbd38 100644 --- a/packages/mcp-server/src/code-tool-types.ts +++ b/packages/mcp-server/src/code-tool-types.ts @@ -8,6 +8,7 @@ export type WorkerInput = { client_opts: ClientOptions; intent?: string | undefined; }; + export type WorkerOutput = { is_error: boolean; result: unknown | null; diff --git a/packages/mcp-server/src/code-tool-worker.ts b/packages/mcp-server/src/code-tool-worker.ts new file mode 100644 index 00000000..23ff1794 --- /dev/null +++ b/packages/mcp-server/src/code-tool-worker.ts @@ -0,0 +1,327 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import path from 'node:path'; +import util from 'node:util'; +import Fuse from 'fuse.js'; +import ts from 'typescript'; +import { WorkerOutput } from './code-tool-types'; +import { ImageKit, ClientOptions } from '@imagekit/nodejs'; + +async function tseval(code: string) { + return import('data:application/typescript;charset=utf-8;base64,' + Buffer.from(code).toString('base64')); +} + +function getRunFunctionSource(code: string): { + type: 'declaration' | 'expression'; + client: string | undefined; + code: string; +} | null { + const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true); + const printer = ts.createPrinter(); + + for (const statement of sourceFile.statements) { + // Check for top-level function declarations + if (ts.isFunctionDeclaration(statement)) { + if (statement.name?.text === 'run') { + return { + type: 'declaration', + client: statement.parameters[0]?.name.getText(), + code: printer.printNode(ts.EmitHint.Unspecified, statement.body!, sourceFile), + }; + } + } + + // Check for variable declarations: const run = () => {} or const run = function() {} + if (ts.isVariableStatement(statement)) { + for (const declaration of statement.declarationList.declarations) { + if ( + ts.isIdentifier(declaration.name) && + declaration.name.text === 'run' && + // Check if it's initialized with a function + declaration.initializer && + (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer)) + ) { + return { + type: 'expression', + client: declaration.initializer.parameters[0]?.name.getText(), + code: printer.printNode(ts.EmitHint.Unspecified, declaration.initializer, sourceFile), + }; + } + } + } + } + + return null; +} + +function getTSDiagnostics(code: string): string[] { + const functionSource = getRunFunctionSource(code)!; + const codeWithImport = [ + 'import { ImageKit } from "@imagekit/nodejs";', + functionSource.type === 'declaration' ? + `async function run(${functionSource.client}: ImageKit)` + : `const run: (${functionSource.client}: ImageKit) => Promise =`, + functionSource.code, + ].join('\n'); + const sourcePath = path.resolve('code.ts'); + const ast = ts.createSourceFile(sourcePath, codeWithImport, ts.ScriptTarget.Latest, true); + const options = ts.getDefaultCompilerOptions(); + options.target = ts.ScriptTarget.Latest; + options.module = ts.ModuleKind.NodeNext; + options.moduleResolution = ts.ModuleResolutionKind.NodeNext; + const host = ts.createCompilerHost(options, true); + const newHost: typeof host = { + ...host, + getSourceFile: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return ast; + } + return host.getSourceFile(...args); + }, + readFile: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return codeWithImport; + } + return host.readFile(...args); + }, + fileExists: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return true; + } + return host.fileExists(...args); + }, + }; + const program = ts.createProgram({ + options, + rootNames: [sourcePath], + host: newHost, + }); + const diagnostics = ts.getPreEmitDiagnostics(program, ast); + return diagnostics.map((d) => { + const message = ts.flattenDiagnosticMessageText(d.messageText, '\n'); + if (!d.file || !d.start) return `- ${message}`; + const { line: lineNumber } = ts.getLineAndCharacterOfPosition(d.file, d.start); + const line = codeWithImport.split('\n').at(lineNumber)?.trim(); + return line ? `- ${message}\n ${line}` : `- ${message}`; + }); +} + +const fuse = new Fuse( + [ + 'client.customMetadataFields.create', + 'client.customMetadataFields.delete', + 'client.customMetadataFields.list', + 'client.customMetadataFields.update', + 'client.files.copy', + 'client.files.delete', + 'client.files.get', + 'client.files.move', + 'client.files.rename', + 'client.files.update', + 'client.files.upload', + 'client.files.bulk.addTags', + 'client.files.bulk.delete', + 'client.files.bulk.removeAITags', + 'client.files.bulk.removeTags', + 'client.files.versions.delete', + 'client.files.versions.get', + 'client.files.versions.list', + 'client.files.versions.restore', + 'client.files.metadata.get', + 'client.files.metadata.getFromURL', + 'client.savedExtensions.create', + 'client.savedExtensions.delete', + 'client.savedExtensions.get', + 'client.savedExtensions.list', + 'client.savedExtensions.update', + 'client.assets.list', + 'client.cache.invalidation.create', + 'client.cache.invalidation.get', + 'client.folders.copy', + 'client.folders.create', + 'client.folders.delete', + 'client.folders.move', + 'client.folders.rename', + 'client.folders.job.get', + 'client.accounts.usage.get', + 'client.accounts.origins.create', + 'client.accounts.origins.delete', + 'client.accounts.origins.get', + 'client.accounts.origins.list', + 'client.accounts.origins.update', + 'client.accounts.urlEndpoints.create', + 'client.accounts.urlEndpoints.delete', + 'client.accounts.urlEndpoints.get', + 'client.accounts.urlEndpoints.list', + 'client.accounts.urlEndpoints.update', + 'client.beta.v2.files.upload', + 'client.webhooks.unsafeUnwrap', + 'client.webhooks.unwrap', + ], + { threshold: 1, shouldSort: true }, +); + +function getMethodSuggestions(fullyQualifiedMethodName: string): string[] { + return fuse + .search(fullyQualifiedMethodName) + .map(({ item }) => item) + .slice(0, 5); +} + +const proxyToObj = new WeakMap(); +const objToProxy = new WeakMap(); + +type ClientProxyConfig = { + path: string[]; + isBelievedBad?: boolean; +}; + +function makeSdkProxy(obj: T, { path, isBelievedBad = false }: ClientProxyConfig): T { + let proxy: T = objToProxy.get(obj); + + if (!proxy) { + proxy = new Proxy(obj, { + get(target, prop, receiver) { + const propPath = [...path, String(prop)]; + const value = Reflect.get(target, prop, receiver); + + if (isBelievedBad || (!(prop in target) && value === undefined)) { + // If we're accessing a path that doesn't exist, it will probably eventually error. + // Let's proxy it and mark it bad so that we can control the error message. + // We proxy an empty class so that an invocation or construction attempt is possible. + return makeSdkProxy(class {}, { path: propPath, isBelievedBad: true }); + } + + if (value !== null && (typeof value === 'object' || typeof value === 'function')) { + return makeSdkProxy(value, { path: propPath, isBelievedBad }); + } + + return value; + }, + + apply(target, thisArg, args) { + if (isBelievedBad || typeof target !== 'function') { + const fullyQualifiedMethodName = path.join('.'); + const suggestions = getMethodSuggestions(fullyQualifiedMethodName); + throw new Error( + `${fullyQualifiedMethodName} is not a function. Did you mean: ${suggestions.join(', ')}`, + ); + } + + return Reflect.apply(target, proxyToObj.get(thisArg) ?? thisArg, args); + }, + + construct(target, args, newTarget) { + if (isBelievedBad || typeof target !== 'function') { + const fullyQualifiedMethodName = path.join('.'); + const suggestions = getMethodSuggestions(fullyQualifiedMethodName); + throw new Error( + `${fullyQualifiedMethodName} is not a constructor. Did you mean: ${suggestions.join(', ')}`, + ); + } + + return Reflect.construct(target, args, newTarget); + }, + }); + + objToProxy.set(obj, proxy); + proxyToObj.set(proxy, obj); + } + + return proxy; +} + +function parseError(code: string, error: unknown): string | undefined { + if (!(error instanceof Error)) return; + const message = error.name ? `${error.name}: ${error.message}` : error.message; + try { + // Deno uses V8; the first ":LINE:COLUMN" is the top of stack. + const lineNumber = error.stack?.match(/:([0-9]+):[0-9]+/)?.[1]; + // -1 for the zero-based indexing + const line = + lineNumber && + code + .split('\n') + .at(parseInt(lineNumber, 10) - 1) + ?.trim(); + return line ? `${message}\n at line ${lineNumber}\n ${line}` : message; + } catch { + return message; + } +} + +const fetch = async (req: Request): Promise => { + const { opts, code } = (await req.json()) as { opts: ClientOptions; code: string }; + + const runFunctionSource = code ? getRunFunctionSource(code) : null; + if (!runFunctionSource) { + const message = + code ? + 'The code is missing a top-level `run` function.' + : 'The code argument is missing. Provide one containing a top-level `run` function.'; + return Response.json( + { + is_error: true, + result: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``, + log_lines: [], + err_lines: [], + } satisfies WorkerOutput, + { status: 400, statusText: 'Code execution error' }, + ); + } + + const diagnostics = getTSDiagnostics(code); + if (diagnostics.length > 0) { + return Response.json( + { + is_error: true, + result: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`, + log_lines: [], + err_lines: [], + } satisfies WorkerOutput, + { status: 400, statusText: 'Code execution error' }, + ); + } + + const client = new ImageKit({ + ...opts, + }); + + const log_lines: string[] = []; + const err_lines: string[] = []; + const originalConsole = globalThis.console; + globalThis.console = { + ...originalConsole, + log: (...args: unknown[]) => { + log_lines.push(util.format(...args)); + }, + error: (...args: unknown[]) => { + err_lines.push(util.format(...args)); + }, + }; + try { + let run_ = async (client: any) => {}; + run_ = (await tseval(`${code}\nexport default run;`)).default; + const result = await run_(makeSdkProxy(client, { path: ['client'] })); + return Response.json({ + is_error: false, + result, + log_lines, + err_lines, + } satisfies WorkerOutput); + } catch (e) { + return Response.json( + { + is_error: true, + result: parseError(code, e), + log_lines, + err_lines, + } satisfies WorkerOutput, + { status: 400, statusText: 'Code execution error' }, + ); + } finally { + globalThis.console = originalConsole; + } +}; + +export default { fetch }; diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index 220b5c74..0d5a3ac3 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -1,14 +1,25 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } from './types'; +import { + ContentBlock, + McpRequestContext, + McpTool, + Metadata, + ToolCallResult, + asErrorResult, + asTextContentResult, +} from './types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; -import { readEnv, requireValue } from './server'; +import { readEnv, requireValue } from './util'; import { WorkerInput, WorkerOutput } from './code-tool-types'; -import { ImageKit } from '@imagekit/nodejs'; +import { getLogger } from './logger'; +import { SdkMethod } from './methods'; +import { McpCodeExecutionMode } from './options'; +import { ClientOptions } from '@imagekit/nodejs'; const prompt = `Runs JavaScript code to interact with the Image Kit API. -You are a skilled programmer writing code to interface with the service. +You are a skilled TypeScript programmer writing code to interface with the service. Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run. For example: @@ -24,7 +35,9 @@ You will be returned anything that your function returns, plus the results of an Do not add try-catch blocks for single API calls. The tool will handle errors for you. Do not add comments unless necessary for generating better code. Code will run in a container, and cannot interact with the network outside of the given SDK client. -Variables will not persist between calls, so make sure to return or log any data you might need later.`; +Variables will not persist between calls, so make sure to return or log any data you might need later. +Remember that you are writing TypeScript code, so you need to be careful with your types. +Always type dynamic key-value stores explicitly as Record instead of {}.`; /** * A tool that runs code against a copy of the SDK. @@ -33,9 +46,19 @@ Variables will not persist between calls, so make sure to return or log any data * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then * a generic endpoint that can be used to invoke any endpoint with the provided arguments. * - * @param endpoints - The endpoints to include in the list. + * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string + * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API + * with limited API keys. + * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote + * sandbox environment hosted by Stainless. */ -export function codeTool(): McpTool { +export function codeTool({ + blockedMethods, + codeExecutionMode, +}: { + blockedMethods: SdkMethod[] | undefined; + codeExecutionMode: McpCodeExecutionMode; +}): McpTool { const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] }; const tool: Tool = { name: 'execute', @@ -55,60 +78,321 @@ export function codeTool(): McpTool { required: ['code'], }, }; - const handler = async (client: ImageKit, args: any): Promise => { + + const logger = getLogger(); + + const handler = async ({ + reqContext, + args, + }: { + reqContext: McpRequestContext; + args: any; + }): Promise => { const code = args.code as string; - const intent = args.intent as string | undefined; - - // this is not required, but passing a Stainless API key for the matching project_name - // will allow you to run code-mode queries against non-published versions of your SDK. - const stainlessAPIKey = readEnv('STAINLESS_API_KEY'); - const codeModeEndpoint = - readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool'; - - const res = await fetch(codeModeEndpoint, { - method: 'POST', - headers: { - ...(stainlessAPIKey && { Authorization: stainlessAPIKey }), - 'Content-Type': 'application/json', - client_envs: JSON.stringify({ - IMAGEKIT_PRIVATE_KEY: requireValue( - readEnv('IMAGEKIT_PRIVATE_KEY') ?? client.privateKey, - 'set IMAGEKIT_PRIVATE_KEY environment variable or provide privateKey client option', - ), - OPTIONAL_IMAGEKIT_IGNORES_THIS: - readEnv('OPTIONAL_IMAGEKIT_IGNORES_THIS') ?? client.password ?? undefined, - IMAGEKIT_WEBHOOK_SECRET: readEnv('IMAGEKIT_WEBHOOK_SECRET') ?? client.webhookSecret ?? undefined, - IMAGE_KIT_BASE_URL: readEnv('IMAGE_KIT_BASE_URL') ?? client.baseURL ?? undefined, - }), + // Do very basic blocking of code that includes forbidden method names. + // + // WARNING: This is not secure against obfuscation and other evasion methods. If + // stronger security blocks are required, then these should be enforced in the downstream + // API (e.g., by having users call the MCP server with API keys with limited permissions). + if (blockedMethods) { + const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName)); + if (blockedMatches.length > 0) { + return asErrorResult( + `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches + .map((m) => m.fullyQualifiedName) + .join(', ')}`, + ); + } + } + + let result: ToolCallResult; + const startTime = Date.now(); + + if (codeExecutionMode === 'local') { + logger.debug('Executing code in local Deno environment'); + result = await localDenoHandler({ reqContext, args }); + } else { + logger.debug('Executing code in remote Stainless environment'); + result = await remoteStainlessHandler({ reqContext, args }); + } + + logger.info( + { + codeExecutionMode, + durationMs: Date.now() - startTime, + isError: result.isError, + contentRows: result.content?.length ?? 0, }, - body: JSON.stringify({ - project_name: 'imagekit', - code, - intent, - client_opts: {}, - } satisfies WorkerInput), - }); + 'Got code tool execution result', + ); + return result; + }; + + return { metadata, tool, handler }; +} + +const remoteStainlessHandler = async ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: any; +}): Promise => { + const code = args.code as string; + const intent = args.intent as string | undefined; + const client = reqContext.client; + + const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool'; + + const localClientEnvs = { + IMAGEKIT_PRIVATE_KEY: requireValue( + readEnv('IMAGEKIT_PRIVATE_KEY') ?? client.privateKey, + 'set IMAGEKIT_PRIVATE_KEY environment variable or provide privateKey client option', + ), + OPTIONAL_IMAGEKIT_IGNORES_THIS: readEnv('OPTIONAL_IMAGEKIT_IGNORES_THIS') ?? client.password ?? undefined, + IMAGEKIT_WEBHOOK_SECRET: readEnv('IMAGEKIT_WEBHOOK_SECRET') ?? client.webhookSecret ?? undefined, + IMAGE_KIT_BASE_URL: readEnv('IMAGE_KIT_BASE_URL') ?? client.baseURL ?? undefined, + }; + // Merge any upstream client envs from the request header, with upstream values taking precedence. + const mergedClientEnvs = { ...localClientEnvs, ...reqContext.upstreamClientEnvs }; + + // Setting a Stainless API key authenticates requests to the code tool endpoint. + const res = await fetch(codeModeEndpoint, { + method: 'POST', + headers: { + ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }), + 'Content-Type': 'application/json', + 'x-stainless-mcp-client-envs': JSON.stringify(mergedClientEnvs), + }, + body: JSON.stringify({ + project_name: 'imagekit', + code, + intent, + client_opts: {}, + } satisfies WorkerInput), + }); - if (!res.ok) { + if (!res.ok) { + if (res.status === 404 && !reqContext.stainlessApiKey) { throw new Error( - `${res.status}: ${ - res.statusText - } error when trying to contact Code Tool server. Details: ${await res.text()}`, + 'Could not access code tool for this project. You may need to provide a Stainless API key via the STAINLESS_API_KEY environment variable, the --stainless-api-key flag, or the x-stainless-api-key HTTP header.', ); } + throw new Error( + `${res.status}: ${ + res.statusText + } error when trying to contact Code Tool server. Details: ${await res.text()}`, + ); + } - const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput; - const hasLogs = log_lines.length > 0 || err_lines.length > 0; - const output = { - result, - ...(log_lines.length > 0 && { log_lines }), - ...(err_lines.length > 0 && { err_lines }), - }; - if (is_error) { - return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2)); - } - return asTextContentResult(output); + const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput; + const hasLogs = log_lines.length > 0 || err_lines.length > 0; + const output = { + result, + ...(log_lines.length > 0 && { log_lines }), + ...(err_lines.length > 0 && { err_lines }), }; + if (is_error) { + return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2)); + } + return asTextContentResult(output); +}; - return { metadata, tool, handler }; -} +const localDenoHandler = async ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: unknown; +}): Promise => { + const fs = await import('node:fs'); + const path = await import('node:path'); + const url = await import('node:url'); + const { newDenoHTTPWorker } = await import('@valtown/deno-http-worker'); + const { getWorkerPath } = await import('./code-tool-paths.cjs'); + const workerPath = getWorkerPath(); + + const client = reqContext.client; + const baseURLHostname = new URL(client.baseURL).hostname; + const { code } = args as { code: string }; + + let denoPath: string; + + const packageRoot = path.resolve(path.dirname(workerPath), '..'); + const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules'); + + // Check if deno is in PATH + const { execSync } = await import('node:child_process'); + try { + execSync('command -v deno', { stdio: 'ignore' }); + denoPath = 'deno'; + } catch { + try { + // Use deno binary in node_modules if it's found + const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs'); + await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK); + denoPath = denoNodeModulesPath; + } catch { + return asErrorResult( + 'Deno is required for code execution but was not found. ' + + 'Install it from https://deno.land or run: npm install deno', + ); + } + } + + const allowReadPaths = [ + 'code-tool-worker.mjs', + `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`, + packageRoot, + ]; + + // Follow symlinks in node_modules to allow read access to workspace-linked packages + try { + const sdkPkgName = '@imagekit/nodejs'; + const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName); + const realSdkDir = fs.realpathSync(sdkDir); + if (realSdkDir !== sdkDir) { + allowReadPaths.push(realSdkDir); + } + } catch { + // Ignore if symlink resolution fails + } + + const allowRead = allowReadPaths.join(','); + + const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), { + denoExecutable: denoPath, + runFlags: [ + `--node-modules-dir=manual`, + `--allow-read=${allowRead}`, + `--allow-net=${baseURLHostname}`, + // Allow environment variables because instantiating the client will try to read from them, + // even though they are not set. + '--allow-env', + ], + printOutput: true, + spawnOptions: { + cwd: path.dirname(workerPath), + // Merge any upstream client envs into the Deno subprocess environment, + // with the upstream env vars taking precedence. + env: { ...process.env, ...reqContext.upstreamClientEnvs }, + }, + }); + + try { + const resp = await new Promise((resolve, reject) => { + worker.addEventListener('exit', (exitCode) => { + reject(new Error(`Worker exited with code ${exitCode}`)); + }); + + // Strip null/undefined values so that the worker SDK client can fall back to + // reading from environment variables (including any upstreamClientEnvs). + const opts = { + ...(client.baseURL != null ? { baseURL: client.baseURL } : undefined), + ...(client.privateKey != null ? { privateKey: client.privateKey } : undefined), + ...(client.password != null ? { password: client.password } : undefined), + ...(client.webhookSecret != null ? { webhookSecret: client.webhookSecret } : undefined), + defaultHeaders: { + 'X-Stainless-MCP': 'true', + }, + } satisfies Partial as ClientOptions; + + const req = worker.request( + 'http://localhost', + { + headers: { + 'content-type': 'application/json', + }, + method: 'POST', + }, + (resp) => { + const body: Uint8Array[] = []; + resp.on('error', (err) => { + reject(err); + }); + resp.on('data', (chunk) => { + body.push(chunk); + }); + resp.on('end', () => { + resolve( + new Response(Buffer.concat(body).toString(), { + status: resp.statusCode ?? 200, + headers: resp.headers as any, + }), + ); + }); + }, + ); + + const body = JSON.stringify({ + opts, + code, + }); + + req.write(body, (err) => { + if (err != null) { + reject(err); + } + }); + + req.end(); + }); + + if (resp.status === 200) { + const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput; + const returnOutput: ContentBlock | null = + result == null ? null : ( + { + type: 'text', + text: typeof result === 'string' ? result : JSON.stringify(result), + } + ); + const logOutput: ContentBlock | null = + log_lines.length === 0 ? + null + : { + type: 'text', + text: log_lines.join('\n'), + }; + const errOutput: ContentBlock | null = + err_lines.length === 0 ? + null + : { + type: 'text', + text: 'Error output:\n' + err_lines.join('\n'), + }; + return { + content: [returnOutput, logOutput, errOutput].filter((block) => block !== null), + }; + } else { + const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput; + const messageOutput: ContentBlock | null = + result == null ? null : ( + { + type: 'text', + text: typeof result === 'string' ? result : JSON.stringify(result), + } + ); + const logOutput: ContentBlock | null = + log_lines.length === 0 ? + null + : { + type: 'text', + text: log_lines.join('\n'), + }; + const errOutput: ContentBlock | null = + err_lines.length === 0 ? + null + : { + type: 'text', + text: 'Error output:\n' + err_lines.join('\n'), + }; + return { + content: [messageOutput, logOutput, errOutput].filter((block) => block !== null), + isError: true, + }; + } + } finally { + worker.terminate(); + } +}; diff --git a/packages/mcp-server/src/docs-search-tool.ts b/packages/mcp-server/src/docs-search-tool.ts index 9af38ab5..476e7007 100644 --- a/packages/mcp-server/src/docs-search-tool.ts +++ b/packages/mcp-server/src/docs-search-tool.ts @@ -1,8 +1,9 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from './types'; - import { Tool } from '@modelcontextprotocol/sdk/types.js'; +import { Metadata, McpRequestContext, asTextContentResult } from './types'; +import { getLogger } from './logger'; +import type { LocalDocsSearch } from './local-docs-search'; export const metadata: Metadata = { resource: 'all', @@ -13,7 +14,8 @@ export const metadata: Metadata = { export const tool: Tool = { name: 'search_docs', - description: 'Search for documentation for how to use the client to interact with the API.', + description: + 'Search SDK documentation to find methods, parameters, and usage examples for interacting with the API. Use this before writing code when you need to discover the right approach.', inputSchema: { type: 'object', properties: { @@ -42,18 +44,95 @@ export const tool: Tool = { const docsSearchURL = process.env['DOCS_SEARCH_URL'] || 'https://api.stainless.com/api/projects/imagekit/docs/search'; -export const handler = async (_: unknown, args: Record | undefined) => { +let _localSearch: LocalDocsSearch | undefined; + +export function setLocalSearch(search: LocalDocsSearch): void { + _localSearch = search; +} + +async function searchLocal(args: Record): Promise { + if (!_localSearch) { + throw new Error('Local search not initialized'); + } + + const query = (args['query'] as string) ?? ''; + const language = (args['language'] as string) ?? 'typescript'; + const detail = (args['detail'] as string) ?? 'default'; + + return _localSearch.search({ + query, + language, + detail, + maxResults: 5, + }).results; +} + +async function searchRemote(args: Record, reqContext: McpRequestContext): Promise { const body = args as any; const query = new URLSearchParams(body).toString(); - const result = await fetch(`${docsSearchURL}?${query}`); + + const startTime = Date.now(); + const result = await fetch(`${docsSearchURL}?${query}`, { + headers: { + ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }), + ...(reqContext.mcpSessionId && { 'x-stainless-mcp-session-id': reqContext.mcpSessionId }), + ...(reqContext.mcpClientInfo && { + 'x-stainless-mcp-client-info': JSON.stringify(reqContext.mcpClientInfo), + }), + }, + }); + + const logger = getLogger(); if (!result.ok) { + const errorText = await result.text(); + logger.warn( + { + durationMs: Date.now() - startTime, + query: body.query, + status: result.status, + statusText: result.statusText, + errorText, + }, + 'Got error response from docs search tool', + ); + + if (result.status === 404 && !reqContext.stainlessApiKey) { + throw new Error( + 'Could not find docs for this project. You may need to provide a Stainless API key via the STAINLESS_API_KEY environment variable, the --stainless-api-key flag, or the x-stainless-api-key HTTP header.', + ); + } + throw new Error( - `${result.status}: ${result.statusText} when using doc search tool. Details: ${await result.text()}`, + `${result.status}: ${result.statusText} when using doc search tool. Details: ${errorText}`, ); } - return asTextContentResult(await result.json()); + const resultBody = await result.json(); + logger.info( + { + durationMs: Date.now() - startTime, + query: body.query, + }, + 'Got docs search result', + ); + return resultBody; +} + +export const handler = async ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: Record | undefined; +}) => { + const body = args ?? {}; + + if (_localSearch) { + return asTextContentResult(await searchLocal(body)); + } + + return asTextContentResult(await searchRemote(body, reqContext)); }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/http.ts b/packages/mcp-server/src/http.ts index dcfeba6a..08c31bed 100644 --- a/packages/mcp-server/src/http.ts +++ b/packages/mcp-server/src/http.ts @@ -2,41 +2,93 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; - +import { ClientOptions } from '@imagekit/nodejs'; import express from 'express'; +import pino from 'pino'; +import pinoHttp from 'pino-http'; +import { getStainlessApiKey, parseClientAuthHeaders } from './auth'; +import { getLogger } from './logger'; import { McpOptions } from './options'; -import { ClientOptions, initMcpServer, newMcpServer } from './server'; -import { parseAuthHeaders } from './headers'; +import { initMcpServer, newMcpServer } from './server'; -const newServer = ({ +const newServer = async ({ clientOptions, + mcpOptions, req, res, }: { clientOptions: ClientOptions; + mcpOptions: McpOptions; req: express.Request; res: express.Response; -}): McpServer | null => { - const server = newMcpServer(); - - try { - const authOptions = parseAuthHeaders(req); - initMcpServer({ - server: server, - clientOptions: { - ...clientOptions, - ...authOptions, - }, - }); - } catch (error) { - res.status(401).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: `Unauthorized: ${error instanceof Error ? error.message : error}`, - }, - }); - return null; +}): Promise => { + const stainlessApiKey = getStainlessApiKey(req, mcpOptions); + const customInstructionsPath = mcpOptions.customInstructionsPath; + const server = await newMcpServer({ stainlessApiKey, customInstructionsPath }); + + const authOptions = parseClientAuthHeaders(req, false); + + let upstreamClientEnvs: Record | undefined; + const clientEnvsHeader = req.headers['x-stainless-mcp-client-envs']; + if (typeof clientEnvsHeader === 'string') { + try { + const parsed = JSON.parse(clientEnvsHeader); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + upstreamClientEnvs = parsed; + } + } catch { + // Ignore malformed header + } + } + + // Parse x-stainless-mcp-client-permissions header to override permission options + // + // Note: Permissions are best-effort and intended to prevent clients from doing unexpected things; + // they're not a hard security boundary, so we allow arbitrary, client-driven overrides. + // + // See the Stainless MCP documentation for more details. + let effectiveMcpOptions = mcpOptions; + const clientPermissionsHeader = req.headers['x-stainless-mcp-client-permissions']; + if (typeof clientPermissionsHeader === 'string') { + try { + const parsed = JSON.parse(clientPermissionsHeader); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + effectiveMcpOptions = { + ...mcpOptions, + ...(typeof parsed.allow_http_gets === 'boolean' && { codeAllowHttpGets: parsed.allow_http_gets }), + ...(Array.isArray(parsed.allowed_methods) && { codeAllowedMethods: parsed.allowed_methods }), + ...(Array.isArray(parsed.blocked_methods) && { codeBlockedMethods: parsed.blocked_methods }), + }; + getLogger().info( + { clientPermissions: parsed }, + 'Overriding code execution permissions from x-stainless-mcp-client-permissions header', + ); + } + } catch (error) { + getLogger().warn({ error }, 'Failed to parse x-stainless-mcp-client-permissions header'); + } + } + + const mcpClientInfo = + typeof req.body?.params?.clientInfo?.name === 'string' ? + { name: req.body.params.clientInfo.name, version: String(req.body.params.clientInfo.version ?? '') } + : undefined; + + await initMcpServer({ + server: server, + mcpOptions: effectiveMcpOptions, + clientOptions: { + ...clientOptions, + ...authOptions, + }, + stainlessApiKey: stainlessApiKey, + upstreamClientEnvs, + mcpSessionId: (req as any).mcpSessionId, + mcpClientInfo, + }); + + if (mcpClientInfo) { + getLogger().info({ mcpSessionId: (req as any).mcpSessionId, mcpClientInfo }, 'MCP client connected'); } return server; @@ -45,7 +97,7 @@ const newServer = ({ const post = (options: { clientOptions: ClientOptions; mcpOptions: McpOptions }) => async (req: express.Request, res: express.Response) => { - const server = newServer({ ...options, req, res }); + const server = await newServer({ ...options, req, res }); // If we return null, we already set the authorization error. if (server === null) return; const transport = new StreamableHTTPServerTransport(); @@ -73,17 +125,78 @@ const del = async (req: express.Request, res: express.Response) => { }); }; +const redactHeaders = (headers: Record) => { + const hiddenHeaders = /auth|cookie|key|token|x-stainless-mcp-client-envs/i; + const filtered = { ...headers }; + Object.keys(filtered).forEach((key) => { + if (hiddenHeaders.test(key)) { + filtered[key] = '[REDACTED]'; + } + }); + return filtered; +}; + export const streamableHTTPApp = ({ clientOptions = {}, - mcpOptions = {}, + mcpOptions, }: { clientOptions?: ClientOptions; - mcpOptions?: McpOptions; + mcpOptions: McpOptions; }): express.Express => { const app = express(); app.set('query parser', 'extended'); app.use(express.json()); + app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { + const existing = req.headers['mcp-session-id']; + const sessionId = (Array.isArray(existing) ? existing[0] : existing) || crypto.randomUUID(); + (req as any).mcpSessionId = sessionId; + const origWriteHead = res.writeHead.bind(res); + res.writeHead = function (statusCode: number, ...rest: any[]) { + res.setHeader('mcp-session-id', sessionId); + return origWriteHead(statusCode, ...rest); + } as typeof res.writeHead; + next(); + }); + app.use( + pinoHttp({ + logger: getLogger(), + customProps: (req) => ({ + mcpSessionId: (req as any).mcpSessionId, + }), + customLogLevel: (req, res) => { + if (res.statusCode >= 500) { + return 'error'; + } else if (res.statusCode >= 400) { + return 'warn'; + } + return 'info'; + }, + customSuccessMessage: function (req, res) { + return `Request ${req.method} to ${req.url} completed with status ${res.statusCode}`; + }, + customErrorMessage: function (req, res, err) { + return `Request ${req.method} to ${req.url} errored with status ${res.statusCode}`; + }, + serializers: { + req: pino.stdSerializers.wrapRequestSerializer((req) => { + return { + ...req, + headers: redactHeaders(req.raw.headers), + }; + }), + res: pino.stdSerializers.wrapResponseSerializer((res) => { + return { + ...res, + headers: redactHeaders(res.headers), + }; + }), + }, + }), + ); + app.get('/health', async (req: express.Request, res: express.Response) => { + res.status(200).send('OK'); + }); app.get('/', get); app.post('/', post({ clientOptions, mcpOptions })); app.delete('/', del); @@ -91,16 +204,24 @@ export const streamableHTTPApp = ({ return app; }; -export const launchStreamableHTTPServer = async (options: McpOptions, port: number | string | undefined) => { - const app = streamableHTTPApp({ mcpOptions: options }); +export const launchStreamableHTTPServer = async ({ + mcpOptions, + port, +}: { + mcpOptions: McpOptions; + port: number | string | undefined; +}) => { + const app = streamableHTTPApp({ mcpOptions }); const server = app.listen(port); const address = server.address(); + const logger = getLogger(); + if (typeof address === 'string') { - console.error(`MCP Server running on streamable HTTP at ${address}`); + logger.info(`MCP Server running on streamable HTTP at ${address}`); } else if (address !== null) { - console.error(`MCP Server running on streamable HTTP on port ${address.port}`); + logger.info(`MCP Server running on streamable HTTP on port ${address.port}`); } else { - console.error(`MCP Server running on streamable HTTP on port ${port}`); + logger.info(`MCP Server running on streamable HTTP on port ${port}`); } }; diff --git a/packages/mcp-server/src/index.ts b/packages/mcp-server/src/index.ts index 0f6dd426..5bca4a60 100644 --- a/packages/mcp-server/src/index.ts +++ b/packages/mcp-server/src/index.ts @@ -5,30 +5,39 @@ import { McpOptions, parseCLIOptions } from './options'; import { launchStdioServer } from './stdio'; import { launchStreamableHTTPServer } from './http'; import type { McpTool } from './types'; +import { configureLogger, getLogger } from './logger'; async function main() { const options = parseOptionsOrError(); + configureLogger({ + level: options.debug ? 'debug' : 'info', + pretty: options.logFormat === 'pretty', + }); const selectedTools = await selectToolsOrError(options); - console.error( - `MCP Server starting with ${selectedTools.length} tools:`, - selectedTools.map((e) => e.tool.name), + getLogger().info( + { tools: selectedTools.map((e) => e.tool.name) }, + `MCP Server starting with ${selectedTools.length} tools`, ); switch (options.transport) { case 'stdio': - await launchStdioServer(); + await launchStdioServer(options); break; case 'http': - await launchStreamableHTTPServer(options, options.port ?? options.socket); + await launchStreamableHTTPServer({ + mcpOptions: options, + port: options.socket ?? options.port, + }); break; } } if (require.main === module) { main().catch((error) => { - console.error('Fatal error in main():', error); + // Logger might not be initialized yet + console.error('Fatal error in main()', error); process.exit(1); }); } @@ -37,7 +46,8 @@ function parseOptionsOrError() { try { return parseCLIOptions(); } catch (error) { - console.error('Error parsing options:', error); + // Logger is initialized after options, so use console.error here + console.error('Error parsing options', error); process.exit(1); } } @@ -46,16 +56,12 @@ async function selectToolsOrError(options: McpOptions): Promise { try { const includedTools = selectTools(options); if (includedTools.length === 0) { - console.error('No tools match the provided filters.'); + getLogger().error('No tools match the provided filters'); process.exit(1); } return includedTools; } catch (error) { - if (error instanceof Error) { - console.error('Error filtering tools:', error.message); - } else { - console.error('Error filtering tools:', error); - } + getLogger().error({ error }, 'Error filtering tools'); process.exit(1); } } diff --git a/packages/mcp-server/src/instructions.ts b/packages/mcp-server/src/instructions.ts new file mode 100644 index 00000000..09c278fd --- /dev/null +++ b/packages/mcp-server/src/instructions.ts @@ -0,0 +1,83 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import fs from 'fs/promises'; +import { readEnv } from './util'; +import { getLogger } from './logger'; + +const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes + +interface InstructionsCacheEntry { + fetchedInstructions: string; + fetchedAt: number; +} + +const instructionsCache = new Map(); + +export async function getInstructions({ + stainlessApiKey, + customInstructionsPath, +}: { + stainlessApiKey?: string | undefined; + customInstructionsPath?: string | undefined; +}): Promise { + const now = Date.now(); + const cacheKey = customInstructionsPath ?? stainlessApiKey ?? ''; + const cached = instructionsCache.get(cacheKey); + + if (cached && now - cached.fetchedAt <= INSTRUCTIONS_CACHE_TTL_MS) { + return cached.fetchedInstructions; + } + + // Evict stale entries so the cache doesn't grow unboundedly. + for (const [key, entry] of instructionsCache) { + if (now - entry.fetchedAt > INSTRUCTIONS_CACHE_TTL_MS) { + instructionsCache.delete(key); + } + } + + let fetchedInstructions: string; + + if (customInstructionsPath) { + fetchedInstructions = await fetchLatestInstructionsFromFile(customInstructionsPath); + } else { + fetchedInstructions = await fetchLatestInstructionsFromApi(stainlessApiKey); + } + + instructionsCache.set(cacheKey, { fetchedInstructions, fetchedAt: now }); + return fetchedInstructions; +} + +async function fetchLatestInstructionsFromFile(path: string): Promise { + try { + return await fs.readFile(path, 'utf-8'); + } catch (error) { + getLogger().error({ error, path }, 'Error fetching instructions from file'); + throw error; + } +} + +async function fetchLatestInstructionsFromApi(stainlessApiKey: string | undefined): Promise { + // Setting the stainless API key is optional, but may be required + // to authenticate requests to the Stainless API. + const response = await fetch( + readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/imagekit', + { + method: 'GET', + headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) }, + }, + ); + + let instructions: string | undefined; + if (!response.ok) { + getLogger().warn( + 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...', + ); + + instructions = + '\n This is the imagekit MCP server.\n\n Available tools:\n - search_docs: Search SDK documentation to find the right methods and parameters.\n - execute: Run TypeScript code against a pre-authenticated SDK client. Define an async run(client) function.\n\n Workflow:\n - If unsure about the API, call search_docs first.\n - Write complete solutions in a single execute call when possible. For large datasets, use API filters to narrow results or paginate within a single execute block.\n - If execute returns an error, read the error and fix your code rather than retrying the same approach.\n - Variables do not persist between execute calls. Return or log all data you need.\n - Individual HTTP requests to the API have a 30-second timeout. If a request times out, try a smaller query or add filters.\n - Code execution has a total timeout of approximately 5 minutes. If your code times out, simplify it or break it into smaller steps.\n '; + } + + instructions ??= ((await response.json()) as { instructions: string }).instructions; + + return instructions; +} diff --git a/packages/mcp-server/src/local-docs-search.ts b/packages/mcp-server/src/local-docs-search.ts new file mode 100644 index 00000000..294e25cf --- /dev/null +++ b/packages/mcp-server/src/local-docs-search.ts @@ -0,0 +1,3380 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import MiniSearch from 'minisearch'; +import * as fs from 'node:fs/promises'; +import * as path from 'node:path'; +import { getLogger } from './logger'; + +type PerLanguageData = { + method?: string; + example?: string; +}; + +type MethodEntry = { + name: string; + endpoint: string; + httpMethod: string; + summary: string; + description: string; + stainlessPath: string; + qualified: string; + params?: string[]; + response?: string; + markdown?: string; + perLanguage?: Record; +}; + +type ProseChunk = { + content: string; + tag: string; + sectionContext?: string; + source?: string; +}; + +type MiniSearchDocument = { + id: string; + kind: 'http_method' | 'prose'; + name?: string; + endpoint?: string; + summary?: string; + description?: string; + qualified?: string; + stainlessPath?: string; + content?: string; + sectionContext?: string; + _original: Record; +}; + +type SearchResult = { + results: (string | Record)[]; +}; + +const EMBEDDED_METHODS: MethodEntry[] = [ + { + name: 'create', + endpoint: '/v1/customMetadataFields', + httpMethod: 'post', + summary: 'Create new field', + description: + 'This API creates a new custom metadata field. Once a custom metadata field is created either through this API or using the dashboard UI, its value can be set on the assets. The value of a field for an asset can be set using the media library UI or programmatically through upload or update assets API.\n', + stainlessPath: '(resource) customMetadataFields > (method) create', + qualified: 'client.customMetadataFields.create', + params: [ + 'label: string;', + 'name: string;', + "schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; };", + ], + response: + "{ id: string; label: string; name: string; schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }; }", + markdown: + "## create\n\n`client.customMetadataFields.create(label: string, name: string, schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }): { id: string; label: string; name: string; schema: object; }`\n\n**post** `/v1/customMetadataFields`\n\nThis API creates a new custom metadata field. Once a custom metadata field is created either through this API or using the dashboard UI, its value can be set on the assets. The value of a field for an asset can be set using the media library UI or programmatically through upload or update assets API.\n\n\n### Parameters\n\n- `label: string`\n Human readable name of the custom metadata field. This should be unique across all non deleted custom metadata fields. This name is displayed as form field label to the users while setting field value on an asset in the media library UI.\n\n- `name: string`\n API name of the custom metadata field. This should be unique across all (including deleted) custom metadata fields.\n\n- `schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }`\n - `type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'`\n Type of the custom metadata field.\n - `defaultValue?: string | number | boolean | string | number | boolean[]`\n The default value for this custom metadata field. This property is only required if `isValueRequired` property is set to `true`. The value should match the `type` of custom metadata field.\n\n - `isValueRequired?: boolean`\n Sets this custom metadata field as required. Setting custom metadata fields on an asset will throw error if the value for all required fields are not present in upload or update asset API request body.\n\n - `maxLength?: number`\n Maximum length of string. Only set this property if `type` is set to `Text` or `Textarea`.\n\n - `maxValue?: string | number`\n Maximum value of the field. Only set this property if field type is `Date` or `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type field, set the minimum numeric value.\n\n - `minLength?: number`\n Minimum length of string. Only set this property if `type` is set to `Text` or `Textarea`.\n\n - `minValue?: string | number`\n Minimum value of the field. Only set this property if field type is `Date` or `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type field, set the minimum numeric value.\n\n - `selectOptions?: string | number | boolean[]`\n An array of allowed values. This property is only required if `type` property is set to `SingleSelect` or `MultiSelect`.\n\n\n### Returns\n\n- `{ id: string; label: string; name: string; schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }; }`\n Object containing details of a custom metadata field.\n\n - `id: string`\n - `label: string`\n - `name: string`\n - `schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst customMetadataField = await client.customMetadataFields.create({\n label: 'price',\n name: 'price',\n schema: { type: 'Number' },\n});\n\nconsole.log(customMetadataField);\n```", + perLanguage: { + cli: { + method: 'customMetadataFields create', + example: + "imagekit custom-metadata-fields create \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --label price \\\n --name price \\\n --schema '{type: Number}'", + }, + csharp: { + method: 'CustomMetadataFields.Create', + example: + 'CustomMetadataFieldCreateParams parameters = new()\n{\n Label = "price",\n Name = "price",\n Schema = new()\n {\n Type = Type.Number,\n DefaultValue = "string",\n IsValueRequired = true,\n MaxLength = 0,\n MaxValue = 3000,\n MinLength = 0,\n MinValue = 1000,\n SelectOptions =\n [\n "small", "medium", "large", 30, 40, true\n ],\n },\n};\n\nvar customMetadataField = await client.CustomMetadataFields.Create(parameters);\n\nConsole.WriteLine(customMetadataField);', + }, + go: { + method: 'client.CustomMetadataFields.New', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tcustomMetadataField, err := client.CustomMetadataFields.New(context.TODO(), imagekit.CustomMetadataFieldNewParams{\n\t\tLabel: "price",\n\t\tName: "price",\n\t\tSchema: imagekit.CustomMetadataFieldNewParamsSchema{\n\t\t\tType: "Number",\n\t\t\tMinValue: imagekit.CustomMetadataFieldNewParamsSchemaMinValueUnion{\n\t\t\t\tOfFloat: imagekit.Float(1000),\n\t\t\t},\n\t\t\tMaxValue: imagekit.CustomMetadataFieldNewParamsSchemaMaxValueUnion{\n\t\t\t\tOfFloat: imagekit.Float(3000),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", customMetadataField.ID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/customMetadataFields \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "label": "price",\n "name": "price",\n "schema": {\n "type": "Number",\n "maxValue": 3000,\n "minValue": 1000\n }\n }\'', + }, + java: { + method: 'customMetadataFields().create', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataField;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataFieldCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n CustomMetadataFieldCreateParams params = CustomMetadataFieldCreateParams.builder()\n .label("price")\n .name("price")\n .schema(CustomMetadataFieldCreateParams.Schema.builder()\n .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER)\n .build())\n .build();\n CustomMetadataField customMetadataField = client.customMetadataFields().create(params);\n }\n}', + }, + php: { + method: 'customMetadataFields->create', + example: + "customMetadataFields->create(\n label: 'price',\n name: 'price',\n schema: [\n 'type' => 'Number',\n 'defaultValue' => 'string',\n 'isValueRequired' => true,\n 'maxLength' => 0,\n 'maxValue' => 3000,\n 'minLength' => 0,\n 'minValue' => 1000,\n 'selectOptions' => ['small', 'medium', 'large', 30, 40, true],\n ],\n);\n\nvar_dump($customMetadataField);", + }, + python: { + method: 'custom_metadata_fields.create', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\ncustom_metadata_field = client.custom_metadata_fields.create(\n label="price",\n name="price",\n schema={\n "type": "Number",\n "min_value": 1000,\n "max_value": 3000,\n },\n)\nprint(custom_metadata_field.id)', + }, + ruby: { + method: 'custom_metadata_fields.create', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\ncustom_metadata_field = image_kit.custom_metadata_fields.create(label: "price", name: "price", schema: {type: :Number})\n\nputs(custom_metadata_field)', + }, + typescript: { + method: 'client.customMetadataFields.create', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst customMetadataField = await client.customMetadataFields.create({\n label: 'price',\n name: 'price',\n schema: {\n type: 'Number',\n minValue: 1000,\n maxValue: 3000,\n },\n});\n\nconsole.log(customMetadataField.id);", + }, + }, + }, + { + name: 'list', + endpoint: '/v1/customMetadataFields', + httpMethod: 'get', + summary: 'List all fields', + description: + 'This API returns the array of created custom metadata field objects. By default the API returns only non deleted field objects, but you can include deleted fields in the API response.\n\nYou can also filter results by a specific folder path to retrieve custom metadata fields applicable at that location. This path-specific filtering is useful when using the **Path policy** feature to determine which custom metadata fields are selected for a given path.\n', + stainlessPath: '(resource) customMetadataFields > (method) list', + qualified: 'client.customMetadataFields.list', + params: ['folderPath?: string;', 'includeDeleted?: boolean;'], + response: + "{ id: string; label: string; name: string; schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }; }[]", + markdown: + "## list\n\n`client.customMetadataFields.list(folderPath?: string, includeDeleted?: boolean): object[]`\n\n**get** `/v1/customMetadataFields`\n\nThis API returns the array of created custom metadata field objects. By default the API returns only non deleted field objects, but you can include deleted fields in the API response.\n\nYou can also filter results by a specific folder path to retrieve custom metadata fields applicable at that location. This path-specific filtering is useful when using the **Path policy** feature to determine which custom metadata fields are selected for a given path.\n\n\n### Parameters\n\n- `folderPath?: string`\n The folder path (e.g., `/path/to/folder`) for which to retrieve applicable custom metadata fields. Useful for determining path-specific field selections when the [Path policy](https://imagekit.io/docs/dam/path-policy) feature is in use.\n\n\n- `includeDeleted?: boolean`\n Set it to `true` to include deleted field objects in the API response.\n\n\n### Returns\n\n- `{ id: string; label: string; name: string; schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }; }[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst customMetadataFields = await client.customMetadataFields.list();\n\nconsole.log(customMetadataFields);\n```", + perLanguage: { + cli: { + method: 'customMetadataFields list', + example: + "imagekit custom-metadata-fields list \\\n --private-key 'My Private Key' \\\n --password 'My Password'", + }, + csharp: { + method: 'CustomMetadataFields.List', + example: + 'CustomMetadataFieldListParams parameters = new();\n\nvar customMetadataFields = await client.CustomMetadataFields.List(parameters);\n\nConsole.WriteLine(customMetadataFields);', + }, + go: { + method: 'client.CustomMetadataFields.List', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tcustomMetadataFields, err := client.CustomMetadataFields.List(context.TODO(), imagekit.CustomMetadataFieldListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", customMetadataFields)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/customMetadataFields \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'customMetadataFields().list', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataField;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataFieldListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n List customMetadataFields = client.customMetadataFields().list();\n }\n}', + }, + php: { + method: 'customMetadataFields->list', + example: + "customMetadataFields->list(\n folderPath: 'folderPath', includeDeleted: true\n);\n\nvar_dump($customMetadataFields);", + }, + python: { + method: 'custom_metadata_fields.list', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\ncustom_metadata_fields = client.custom_metadata_fields.list()\nprint(custom_metadata_fields)', + }, + ruby: { + method: 'custom_metadata_fields.list', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\ncustom_metadata_fields = image_kit.custom_metadata_fields.list\n\nputs(custom_metadata_fields)', + }, + typescript: { + method: 'client.customMetadataFields.list', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst customMetadataFields = await client.customMetadataFields.list();\n\nconsole.log(customMetadataFields);", + }, + }, + }, + { + name: 'update', + endpoint: '/v1/customMetadataFields/{id}', + httpMethod: 'patch', + summary: 'Update existing field', + description: 'This API updates the label or schema of an existing custom metadata field.\n', + stainlessPath: '(resource) customMetadataFields > (method) update', + qualified: 'client.customMetadataFields.update', + params: [ + 'id: string;', + 'label?: string;', + 'schema?: { defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; };', + ], + response: + "{ id: string; label: string; name: string; schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }; }", + markdown: + "## update\n\n`client.customMetadataFields.update(id: string, label?: string, schema?: { defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }): { id: string; label: string; name: string; schema: object; }`\n\n**patch** `/v1/customMetadataFields/{id}`\n\nThis API updates the label or schema of an existing custom metadata field.\n\n\n### Parameters\n\n- `id: string`\n\n- `label?: string`\n Human readable name of the custom metadata field. This should be unique across all non deleted custom metadata fields. This name is displayed as form field label to the users while setting field value on an asset in the media library UI. This parameter is required if `schema` is not provided.\n\n- `schema?: { defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }`\n An object that describes the rules for the custom metadata key. This parameter is required if `label` is not provided. Note: `type` cannot be updated and will be ignored if sent with the `schema`. The schema will be validated as per the existing `type`.\n\n - `defaultValue?: string | number | boolean | string | number | boolean[]`\n The default value for this custom metadata field. This property is only required if `isValueRequired` property is set to `true`. The value should match the `type` of custom metadata field.\n\n - `isValueRequired?: boolean`\n Sets this custom metadata field as required. Setting custom metadata fields on an asset will throw error if the value for all required fields are not present in upload or update asset API request body.\n\n - `maxLength?: number`\n Maximum length of string. Only set this property if `type` is set to `Text` or `Textarea`.\n\n - `maxValue?: string | number`\n Maximum value of the field. Only set this property if field type is `Date` or `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type field, set the minimum numeric value.\n\n - `minLength?: number`\n Minimum length of string. Only set this property if `type` is set to `Text` or `Textarea`.\n\n - `minValue?: string | number`\n Minimum value of the field. Only set this property if field type is `Date` or `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type field, set the minimum numeric value.\n\n - `selectOptions?: string | number | boolean[]`\n An array of allowed values. This property is only required if `type` property is set to `SingleSelect` or `MultiSelect`.\n\n\n### Returns\n\n- `{ id: string; label: string; name: string; schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }; }`\n Object containing details of a custom metadata field.\n\n - `id: string`\n - `label: string`\n - `name: string`\n - `schema: { type: 'Text' | 'Textarea' | 'Number' | 'Date' | 'Boolean' | 'SingleSelect' | 'MultiSelect'; defaultValue?: string | number | boolean | string | number | boolean[]; isValueRequired?: boolean; maxLength?: number; maxValue?: string | number; minLength?: number; minValue?: string | number; selectOptions?: string | number | boolean[]; }`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst customMetadataField = await client.customMetadataFields.update('id');\n\nconsole.log(customMetadataField);\n```", + perLanguage: { + cli: { + method: 'customMetadataFields update', + example: + "imagekit custom-metadata-fields update \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'CustomMetadataFields.Update', + example: + 'CustomMetadataFieldUpdateParams parameters = new() { ID = "id" };\n\nvar customMetadataField = await client.CustomMetadataFields.Update(parameters);\n\nConsole.WriteLine(customMetadataField);', + }, + go: { + method: 'client.CustomMetadataFields.Update', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tcustomMetadataField, err := client.CustomMetadataFields.Update(\n\t\tcontext.TODO(),\n\t\t"id",\n\t\timagekit.CustomMetadataFieldUpdateParams{\n\t\t\tLabel: imagekit.String("price"),\n\t\t\tSchema: imagekit.CustomMetadataFieldUpdateParamsSchema{\n\t\t\t\tMinValue: imagekit.CustomMetadataFieldUpdateParamsSchemaMinValueUnion{\n\t\t\t\t\tOfFloat: imagekit.Float(1000),\n\t\t\t\t},\n\t\t\t\tMaxValue: imagekit.CustomMetadataFieldUpdateParamsSchemaMaxValueUnion{\n\t\t\t\t\tOfFloat: imagekit.Float(3000),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", customMetadataField.ID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/customMetadataFields/$ID \\\n -X PATCH \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'customMetadataFields().update', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataField;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataFieldUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n CustomMetadataField customMetadataField = client.customMetadataFields().update("id");\n }\n}', + }, + php: { + method: 'customMetadataFields->update', + example: + "customMetadataFields->update(\n 'id',\n label: 'price',\n schema: [\n 'defaultValue' => 'string',\n 'isValueRequired' => true,\n 'maxLength' => 0,\n 'maxValue' => 3000,\n 'minLength' => 0,\n 'minValue' => 1000,\n 'selectOptions' => ['small', 'medium', 'large', 30, 40, true],\n ],\n);\n\nvar_dump($customMetadataField);", + }, + python: { + method: 'custom_metadata_fields.update', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\ncustom_metadata_field = client.custom_metadata_fields.update(\n id="id",\n label="price",\n schema={\n "min_value": 1000,\n "max_value": 3000,\n },\n)\nprint(custom_metadata_field.id)', + }, + ruby: { + method: 'custom_metadata_fields.update', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\ncustom_metadata_field = image_kit.custom_metadata_fields.update("id")\n\nputs(custom_metadata_field)', + }, + typescript: { + method: 'client.customMetadataFields.update', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst customMetadataField = await client.customMetadataFields.update('id', {\n label: 'price',\n schema: { minValue: 1000, maxValue: 3000 },\n});\n\nconsole.log(customMetadataField.id);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/customMetadataFields/{id}', + httpMethod: 'delete', + summary: 'Delete a field', + description: + 'This API deletes a custom metadata field. Even after deleting a custom metadata field, you cannot create any new custom metadata field with the same name.\n', + stainlessPath: '(resource) customMetadataFields > (method) delete', + qualified: 'client.customMetadataFields.delete', + params: ['id: string;'], + response: '{ }', + markdown: + "## delete\n\n`client.customMetadataFields.delete(id: string): { }`\n\n**delete** `/v1/customMetadataFields/{id}`\n\nThis API deletes a custom metadata field. Even after deleting a custom metadata field, you cannot create any new custom metadata field with the same name.\n\n\n### Parameters\n\n- `id: string`\n\n### Returns\n\n- `{ }`\n\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst customMetadataField = await client.customMetadataFields.delete('id');\n\nconsole.log(customMetadataField);\n```", + perLanguage: { + cli: { + method: 'customMetadataFields delete', + example: + "imagekit custom-metadata-fields delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'CustomMetadataFields.Delete', + example: + 'CustomMetadataFieldDeleteParams parameters = new() { ID = "id" };\n\nvar customMetadataField = await client.CustomMetadataFields.Delete(parameters);\n\nConsole.WriteLine(customMetadataField);', + }, + go: { + method: 'client.CustomMetadataFields.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tcustomMetadataField, err := client.CustomMetadataFields.Delete(context.TODO(), "id")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", customMetadataField)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/customMetadataFields/$ID \\\n -X DELETE \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'customMetadataFields().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteParams;\nimport com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n CustomMetadataFieldDeleteResponse customMetadataField = client.customMetadataFields().delete("id");\n }\n}', + }, + php: { + method: 'customMetadataFields->delete', + example: + "customMetadataFields->delete('id');\n\nvar_dump($customMetadataField);", + }, + python: { + method: 'custom_metadata_fields.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\ncustom_metadata_field = client.custom_metadata_fields.delete(\n "id",\n)\nprint(custom_metadata_field)', + }, + ruby: { + method: 'custom_metadata_fields.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\ncustom_metadata_field = image_kit.custom_metadata_fields.delete("id")\n\nputs(custom_metadata_field)', + }, + typescript: { + method: 'client.customMetadataFields.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst customMetadataField = await client.customMetadataFields.delete('id');\n\nconsole.log(customMetadataField);", + }, + }, + }, + { + name: 'upload', + endpoint: '/api/v1/files/upload', + httpMethod: 'post', + summary: 'Upload file V1', + description: + 'ImageKit.io allows you to upload files directly from both the server and client sides. For server-side uploads, private API key authentication is used. For client-side uploads, generate a one-time `token`, `signature`, and `expire` from your secure backend using private API. [Learn more](/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload) about how to implement client-side file upload.\n\nThe [V2 API](/docs/api-reference/upload-file/upload-file-v2) enhances security by verifying the entire payload using JWT.\n\n**File size limit** \\\nOn the free plan, the maximum upload file sizes are 25MB for images, audio, and raw files and 100MB for videos. On the Lite paid plan, these limits increase to 40MB for images, audio, and raw files and 300MB for videos, whereas on the Pro paid plan, these limits increase to 50MB for images, audio, and raw files and 2GB for videos. These limits can be further increased with enterprise plans.\n\n**Version limit** \\\nA file can have a maximum of 100 versions.\n\n**Demo applications**\n\n- A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more.\n- [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies.\n', + stainlessPath: '(resource) files > (method) upload', + qualified: 'client.files.upload', + params: [ + 'file: string;', + 'fileName: string;', + 'token?: string;', + 'checks?: string;', + 'customCoordinates?: string;', + 'customMetadata?: object;', + 'description?: string;', + 'expire?: number;', + "extensions?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; } | { id: string; name: 'saved-extension'; }[];", + 'folder?: string;', + 'isPrivateFile?: boolean;', + 'isPublished?: boolean;', + 'overwriteAITags?: boolean;', + 'overwriteCustomMetadata?: boolean;', + 'overwriteFile?: boolean;', + 'overwriteTags?: boolean;', + 'publicKey?: string;', + 'responseFields?: string[];', + 'signature?: string;', + 'tags?: string[];', + "transformation?: { post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]; pre?: string; };", + 'useUniqueFileName?: boolean;', + 'webhookUrl?: string;', + ], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; extensionStatus?: { ai-auto-description?: 'success' | 'pending' | 'failed'; ai-tasks?: 'success' | 'pending' | 'failed'; aws-auto-tagging?: 'success' | 'pending' | 'failed'; google-auto-tagging?: 'success' | 'pending' | 'failed'; remove-bg?: 'success' | 'pending' | 'failed'; }; fileId?: string; filePath?: string; fileType?: string; height?: number; isPrivateFile?: boolean; isPublished?: boolean; metadata?: { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: object; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnailUrl?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }", + markdown: + "## upload\n\n`client.files.upload(file: string, fileName: string, token?: string, checks?: string, customCoordinates?: string, customMetadata?: object, description?: string, expire?: number, extensions?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; } | { id: string; name: 'saved-extension'; }[], folder?: string, isPrivateFile?: boolean, isPublished?: boolean, overwriteAITags?: boolean, overwriteCustomMetadata?: boolean, overwriteFile?: boolean, overwriteTags?: boolean, publicKey?: string, responseFields?: string[], signature?: string, tags?: string[], transformation?: { post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]; pre?: string; }, useUniqueFileName?: boolean, webhookUrl?: string): { AITags?: object[]; audioCodec?: string; bitRate?: number; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; extensionStatus?: object; fileId?: string; filePath?: string; fileType?: string; height?: number; isPrivateFile?: boolean; isPublished?: boolean; metadata?: metadata; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnailUrl?: string; url?: string; versionInfo?: object; videoCodec?: string; width?: number; }`\n\n**post** `/api/v1/files/upload`\n\nImageKit.io allows you to upload files directly from both the server and client sides. For server-side uploads, private API key authentication is used. For client-side uploads, generate a one-time `token`, `signature`, and `expire` from your secure backend using private API. [Learn more](/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload) about how to implement client-side file upload.\n\nThe [V2 API](/docs/api-reference/upload-file/upload-file-v2) enhances security by verifying the entire payload using JWT.\n\n**File size limit** \\\nOn the free plan, the maximum upload file sizes are 25MB for images, audio, and raw files and 100MB for videos. On the Lite paid plan, these limits increase to 40MB for images, audio, and raw files and 300MB for videos, whereas on the Pro paid plan, these limits increase to 50MB for images, audio, and raw files and 2GB for videos. These limits can be further increased with enterprise plans.\n\n**Version limit** \\\nA file can have a maximum of 100 versions.\n\n**Demo applications**\n\n- A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more.\n- [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies.\n\n\n### Parameters\n\n- `file: string`\n The API accepts any of the following:\n\n- **Binary data** – send the raw bytes as `multipart/form-data`.\n- **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch.\n- **Base64 string** – the file encoded as a Base64 data URI or plain Base64.\n\nWhen supplying a URL, the server must receive the response headers within 8 seconds; otherwise the request fails with 400 Bad Request.\n\n\n- `fileName: string`\n The name with which the file has to be uploaded.\nThe file name can contain:\n\n - Alphanumeric Characters: `a-z`, `A-Z`, `0-9`.\n - Special Characters: `.`, `-`\n\nAny other character including space will be replaced by `_`\n\n\n- `token?: string`\n A unique value that the ImageKit.io server will use to recognize and prevent subsequent retries for the same request. We suggest using V4 UUIDs, or another random string with enough entropy to avoid collisions. This field is only required for authentication when uploading a file from the client side.\n\n**Note**: Sending a value that has been used in the past will result in a validation error. Even if your previous request resulted in an error, you should always send a new value for this field.\n\n\n- `checks?: string`\n Server-side checks to run on the asset.\nRead more about [Upload API checks](/docs/api-reference/upload-file/upload-file#upload-api-checks).\n\n\n- `customCoordinates?: string`\n Define an important area in the image. This is only relevant for image type files.\n\n - To be passed as a string with the x and y coordinates of the top-left corner, and width and height of the area of interest in the format `x,y,width,height`. For example - `10,10,100,100`\n - Can be used with fo-customtransformation.\n - If this field is not specified and the file is overwritten, then customCoordinates will be removed.\n\n\n- `customMetadata?: object`\n JSON key-value pairs to associate with the asset. Create the custom metadata fields before setting these values.\n\n\n- `description?: string`\n Optional text to describe the contents of the file.\n\n\n- `expire?: number`\n The time until your signature is valid. It must be a [Unix time](https://en.wikipedia.org/wiki/Unix_time) in less than 1 hour into the future. It should be in seconds. This field is only required for authentication when uploading a file from the client side.\n\n\n- `extensions?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; } | { id: string; name: 'saved-extension'; }[]`\n Array of extensions to be applied to the asset. Each extension can be configured with specific parameters based on the extension type.\n\n\n- `folder?: string`\n The folder path in which the image has to be uploaded. If the folder(s) didn't exist before, a new folder(s) is created.\n\nThe folder name can contain:\n\n - Alphanumeric Characters: `a-z` , `A-Z` , `0-9`\n - Special Characters: `/` , `_` , `-`\n\nUsing multiple `/` creates a nested folder.\n\n\n- `isPrivateFile?: boolean`\n Whether to mark the file as private or not.\n\nIf `true`, the file is marked as private and is accessible only using named transformation or signed URL.\n\n\n- `isPublished?: boolean`\n Whether to upload file as published or not.\n\nIf `false`, the file is marked as unpublished, which restricts access to the file only via the media library. Files in draft or unpublished state can only be publicly accessed after being published.\n\nThe option to upload in draft state is only available in custom enterprise pricing plans.\n\n\n- `overwriteAITags?: boolean`\n If set to `true` and a file already exists at the exact location, its AITags will be removed. Set `overwriteAITags` to `false` to preserve AITags.\n\n\n- `overwriteCustomMetadata?: boolean`\n If the request does not have `customMetadata`, and a file already exists at the exact location, existing customMetadata will be removed.\n\n\n- `overwriteFile?: boolean`\n If `false` and `useUniqueFileName` is also `false`, and a file already exists at the exact location, upload API will return an error immediately.\n\n\n- `overwriteTags?: boolean`\n If the request does not have `tags`, and a file already exists at the exact location, existing tags will be removed.\n\n\n- `publicKey?: string`\n Your ImageKit.io public key. This field is only required for authentication when uploading a file from the client side.\n\n\n- `responseFields?: string[]`\n Array of response field keys to include in the API response body.\n\n\n- `signature?: string`\n HMAC-SHA1 digest of the token+expire using your ImageKit.io private API key as a key. Learn how to create a signature on the page below. This should be in lowercase.\n\nSignature must be calculated on the server-side. This field is only required for authentication when uploading a file from the client side.\n\n\n- `tags?: string[]`\n Set the tags while uploading the file.\nProvide an array of tag strings (e.g. `[\"tag1\", \"tag2\", \"tag3\"]`). The combined length of all tag characters must not exceed 500, and the `%` character is not allowed.\nIf this field is not specified and the file is overwritten, the existing tags will be removed.\n\n\n- `transformation?: { post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]; pre?: string; }`\n Configure pre-processing (`pre`) and post-processing (`post`) transformations.\n\n- `pre` — applied before the file is uploaded to the Media Library. \n Useful for reducing file size or applying basic optimizations upfront (e.g., resize, compress).\n\n- `post` — applied immediately after upload. \n Ideal for generating transformed versions (like video encodes or thumbnails) in advance, so they're ready for delivery without delay.\n\nYou can mix and match any combination of post-processing types.\n\n - `post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]`\n List of transformations to apply *after* the file is uploaded. \nEach item must match one of the following types:\n`transformation`, `gif-to-video`, `thumbnail`, `abs`.\n\n - `pre?: string`\n Transformation string to apply before uploading the file to the Media Library. Useful for optimizing files at ingestion.\n\n\n- `useUniqueFileName?: boolean`\n Whether to use a unique filename for this file or not.\n\nIf `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique filename.\n\nIf `false`, then the image is uploaded with the provided filename parameter, and any existing file with the same name is replaced.\n\n\n- `webhookUrl?: string`\n The final status of extensions after they have completed execution will be delivered to this endpoint as a POST request. [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) about the webhook payload structure.\n\n\n### Returns\n\n- `{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; extensionStatus?: { ai-auto-description?: 'success' | 'pending' | 'failed'; ai-tasks?: 'success' | 'pending' | 'failed'; aws-auto-tagging?: 'success' | 'pending' | 'failed'; google-auto-tagging?: 'success' | 'pending' | 'failed'; remove-bg?: 'success' | 'pending' | 'failed'; }; fileId?: string; filePath?: string; fileType?: string; height?: number; isPrivateFile?: boolean; isPublished?: boolean; metadata?: { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: object; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnailUrl?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }`\n Object containing details of a successful upload.\n\n - `AITags?: { confidence?: number; name?: string; source?: string; }[]`\n - `audioCodec?: string`\n - `bitRate?: number`\n - `customCoordinates?: string`\n - `customMetadata?: object`\n - `description?: string`\n - `duration?: number`\n - `embeddedMetadata?: object`\n - `extensionStatus?: { ai-auto-description?: 'success' | 'pending' | 'failed'; ai-tasks?: 'success' | 'pending' | 'failed'; aws-auto-tagging?: 'success' | 'pending' | 'failed'; google-auto-tagging?: 'success' | 'pending' | 'failed'; remove-bg?: 'success' | 'pending' | 'failed'; }`\n - `fileId?: string`\n - `filePath?: string`\n - `fileType?: string`\n - `height?: number`\n - `isPrivateFile?: boolean`\n - `isPublished?: boolean`\n - `metadata?: { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: { exif?: { ApertureValue?: number; ColorSpace?: number; CreateDate?: string; CustomRendered?: number; DateTimeOriginal?: string; ExifImageHeight?: number; ExifImageWidth?: number; ExifVersion?: string; ExposureCompensation?: number; ExposureMode?: number; ExposureProgram?: number; ExposureTime?: number; Flash?: number; FlashpixVersion?: string; FNumber?: number; FocalLength?: number; FocalPlaneResolutionUnit?: number; FocalPlaneXResolution?: number; FocalPlaneYResolution?: number; InteropOffset?: number; ISO?: number; MeteringMode?: number; SceneCaptureType?: number; ShutterSpeedValue?: number; SubSecTime?: string; WhiteBalance?: number; }; gps?: { GPSVersionID?: number[]; }; image?: { ExifOffset?: number; GPSInfo?: number; Make?: string; Model?: string; ModifyDate?: string; Orientation?: number; ResolutionUnit?: number; Software?: string; XResolution?: number; YCbCrPositioning?: number; YResolution?: number; }; interoperability?: { InteropIndex?: string; InteropVersion?: string; }; makernote?: object; thumbnail?: { Compression?: number; ResolutionUnit?: number; ThumbnailLength?: number; ThumbnailOffset?: number; XResolution?: number; YResolution?: number; }; }; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }`\n - `name?: string`\n - `selectedFieldsSchema?: object`\n - `size?: number`\n - `tags?: string[]`\n - `thumbnailUrl?: string`\n - `url?: string`\n - `versionInfo?: { id?: string; name?: string; }`\n - `videoCodec?: string`\n - `width?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.files.upload({ file: fs.createReadStream('path/to/file'), fileName: 'fileName' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'files upload', + example: + "imagekit files upload \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file 'Example data' \\\n --file-name fileName", + }, + csharp: { + method: 'Files.Upload', + example: + 'FileUploadParams parameters = new()\n{\n File = Encoding.UTF8.GetBytes("Example data"),\n FileName = "fileName",\n};\n\nvar response = await client.Files.Upload(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Files.Upload', + example: + 'package main\n\nimport (\n\t"bytes"\n\t"context"\n\t"fmt"\n\t"io"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Files.Upload(context.TODO(), imagekit.FileUploadParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte("Example data"))),\n\t\tFileName: "fileName",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.VideoCodec)\n}\n', + }, + http: { + example: + 'curl https://upload.imagekit.io/api/v1/files/upload \\\n -H \'Content-Type: multipart/form-data\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -F \'file=@/path/to/file\' \\\n -F fileName=fileName \\\n -F checks=\'"request.folder" : "marketing/"\n \' \\\n -F customMetadata=\'{"brand":"bar","color":"bar"}\' \\\n -F description=\'Running shoes\' \\\n -F extensions=\'[{"name":"remove-bg","options":{"add_shadow":true}},{"maxTags":5,"minConfidence":95,"name":"google-auto-tagging"},{"name":"ai-auto-description"},{"name":"ai-tasks","tasks":[{"instruction":"What types of clothing items are visible in this image?","type":"select_tags","vocabulary":["shirt","tshirt","dress","trousers","jacket"]},{"instruction":"Is this a luxury or high-end fashion item?","type":"yes_no","on_yes":{"add_tags":["luxury","premium"]}}]},{"id":"ext_abc123","name":"saved-extension"}]\' \\\n -F responseFields=\'["tags","customCoordinates","isPrivateFile"]\' \\\n -F tags=\'["t-shirt","round-neck","men"]\' \\\n -F transformation=\'{"post":[{"type":"thumbnail","value":"w-150,h-150"},{"protocol":"dash","type":"abs","value":"sr-240_360_480_720_1080"}]}\'', + }, + java: { + method: 'files().upload', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FileUploadParams params = FileUploadParams.builder()\n .file(new ByteArrayInputStream("Example data".getBytes()))\n .fileName("fileName")\n .build();\n FileUploadResponse response = client.files().upload(params);\n }\n}', + }, + php: { + method: 'files->upload', + example: + "files->upload(\n file: 'file',\n fileName: 'fileName',\n token: 'token',\n checks: \"\\\"request.folder\\\" : \\\"marketing/\\\"\\n\",\n customCoordinates: 'customCoordinates',\n customMetadata: ['brand' => 'bar', 'color' => 'bar'],\n description: 'Running shoes',\n expire: 0,\n extensions: [\n [\n 'name' => 'remove-bg',\n 'options' => [\n 'addShadow' => true,\n 'bgColor' => 'bg_color',\n 'bgImageURL' => 'bg_image_url',\n 'semitransparency' => true,\n ],\n ],\n ['maxTags' => 5, 'minConfidence' => 95, 'name' => 'google-auto-tagging'],\n ['name' => 'ai-auto-description'],\n [\n 'name' => 'ai-tasks',\n 'tasks' => [\n [\n 'instruction' => 'What types of clothing items are visible in this image?',\n 'type' => 'select_tags',\n 'maxSelections' => 1,\n 'minSelections' => 0,\n 'vocabulary' => ['shirt', 'tshirt', 'dress', 'trousers', 'jacket'],\n ],\n [\n 'instruction' => 'Is this a luxury or high-end fashion item?',\n 'type' => 'yes_no',\n 'onNo' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n 'onUnknown' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n 'onYes' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n ],\n ],\n ],\n ['id' => 'ext_abc123', 'name' => 'saved-extension'],\n ],\n folder: 'folder',\n isPrivateFile: true,\n isPublished: true,\n overwriteAITags: true,\n overwriteCustomMetadata: true,\n overwriteFile: true,\n overwriteTags: true,\n publicKey: 'publicKey',\n responseFields: ['tags', 'customCoordinates', 'isPrivateFile'],\n signature: 'signature',\n tags: ['t-shirt', 'round-neck', 'men'],\n transformation: [\n 'post' => [\n ['type' => 'thumbnail', 'value' => 'w-150,h-150'],\n [\n 'protocol' => 'dash',\n 'type' => 'abs',\n 'value' => 'sr-240_360_480_720_1080',\n ],\n ],\n 'pre' => 'w-300,h-300,q-80',\n ],\n useUniqueFileName: true,\n webhookURL: 'https://example.com',\n);\n\nvar_dump($response);", + }, + python: { + method: 'files.upload', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.files.upload(\n file=b"Example data",\n file_name="fileName",\n)\nprint(response.video_codec)', + }, + ruby: { + method: 'files.upload', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.files.upload(file: StringIO.new("Example data"), file_name: "fileName")\n\nputs(response)', + }, + typescript: { + method: 'client.files.upload', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.upload({\n file: fs.createReadStream('path/to/file'),\n fileName: 'fileName',\n});\n\nconsole.log(response.videoCodec);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/files/{fileId}/details', + httpMethod: 'get', + summary: 'Get file details', + description: + 'This API returns an object with details or attributes about the current version of the file.', + stainlessPath: '(resource) files > (method) get', + qualified: 'client.files.get', + params: ['fileId: string;'], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }", + markdown: + "## get\n\n`client.files.get(fileId: string): { AITags?: object[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: object; videoCodec?: string; width?: number; }`\n\n**get** `/v1/files/{fileId}/details`\n\nThis API returns an object with details or attributes about the current version of the file.\n\n### Parameters\n\n- `fileId: string`\n\n### Returns\n\n- `{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }`\n Object containing details of a file or file version.\n\n - `AITags?: { confidence?: number; name?: string; source?: string; }[]`\n - `audioCodec?: string`\n - `bitRate?: number`\n - `createdAt?: string`\n - `customCoordinates?: string`\n - `customMetadata?: object`\n - `description?: string`\n - `duration?: number`\n - `embeddedMetadata?: object`\n - `fileId?: string`\n - `filePath?: string`\n - `fileType?: string`\n - `hasAlpha?: boolean`\n - `height?: number`\n - `isPrivateFile?: boolean`\n - `isPublished?: boolean`\n - `mime?: string`\n - `name?: string`\n - `selectedFieldsSchema?: object`\n - `size?: number`\n - `tags?: string[]`\n - `thumbnail?: string`\n - `type?: 'file' | 'file-version'`\n - `updatedAt?: string`\n - `url?: string`\n - `versionInfo?: { id?: string; name?: string; }`\n - `videoCodec?: string`\n - `width?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst file = await client.files.get('fileId');\n\nconsole.log(file);\n```", + perLanguage: { + cli: { + method: 'files get', + example: + "imagekit files get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId", + }, + csharp: { + method: 'Files.Get', + example: + 'FileGetParams parameters = new() { FileID = "fileId" };\n\nvar file = await client.Files.Get(parameters);\n\nConsole.WriteLine(file);', + }, + go: { + method: 'client.Files.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tfile, err := client.Files.Get(context.TODO(), "fileId")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", file.VideoCodec)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID/details \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.File;\nimport com.imagekit.api.models.files.FileGetParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n File file = client.files().get("fileId");\n }\n}', + }, + php: { + method: 'files->get', + example: + "files->get('fileId');\n\nvar_dump($file);", + }, + python: { + method: 'files.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nfile = client.files.get(\n "fileId",\n)\nprint(file.video_codec)', + }, + ruby: { + method: 'files.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nfile = image_kit.files.get("fileId")\n\nputs(file)', + }, + typescript: { + method: 'client.files.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst file = await client.files.get('fileId');\n\nconsole.log(file.videoCodec);", + }, + }, + }, + { + name: 'update', + endpoint: '/v1/files/{fileId}/details', + httpMethod: 'patch', + summary: 'Update file details', + description: + 'This API updates the details or attributes of the current version of the file. You can update `tags`, `customCoordinates`, `customMetadata`, publication status, remove existing `AITags` and apply extensions using this API.\n', + stainlessPath: '(resource) files > (method) update', + qualified: 'client.files.update', + params: [ + 'fileId: string;', + "UpdateFileRequest: { customCoordinates?: string; customMetadata?: object; description?: string; extensions?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; } | { id: string; name: 'saved-extension'; }[]; removeAITags?: string[] | 'all'; tags?: string[]; webhookUrl?: string; } | { publish?: { isPublished: boolean; includeFileVersions?: boolean; }; };", + ], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }", + perLanguage: { + cli: { + method: 'files update', + example: + "imagekit files update \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId", + }, + csharp: { + method: 'Files.Update', + example: + 'FileUpdateParams parameters = new()\n{\n FileID = "fileId",\n UpdateFileRequest = new UpdateFileDetails()\n {\n CustomCoordinates = "10,10,100,100",\n CustomMetadata = new Dictionary()\n {\n { "brand", JsonSerializer.SerializeToElement("bar") },\n { "color", JsonSerializer.SerializeToElement("bar") },\n },\n Description = "description",\n Extensions =\n [\n new RemoveBg()\n {\n Options = new()\n {\n AddShadow = true,\n BgColor = "bg_color",\n BgImageUrl = "bg_image_url",\n Semitransparency = true,\n },\n },\n new AutoTaggingExtension()\n {\n MaxTags = 10,\n MinConfidence = 80,\n Name = Name.GoogleAutoTagging,\n },\n new AutoTaggingExtension()\n {\n MaxTags = 10,\n MinConfidence = 80,\n Name = Name.AwsAutoTagging,\n },\n new AIAutoDescription(),\n new AITasks(\n\n [\n new SelectTags()\n {\n Instruction = "What types of clothing items are visible?",\n MaxSelections = 1,\n MinSelections = 0,\n Vocabulary =\n [\n "shirt", "dress", "jacket"\n ],\n },\n ]\n ),\n new SavedExtension("ext_abc123"),\n ],\n RemoveAITags = new(\n\n [\n "car", "vehicle", "motorsports"\n ]\n ),\n Tags =\n [\n "tag1", "tag2"\n ],\n WebhookUrl = "https://webhook.site/0d6b6c7a-8e5a-4b3a-8b7c-0d6b6c7a8e5a",\n },\n};\n\nvar file = await client.Files.Update(parameters);\n\nConsole.WriteLine(file);', + }, + go: { + method: 'client.Files.Update', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tfile, err := client.Files.Update(\n\t\tcontext.TODO(),\n\t\t"fileId",\n\t\timagekit.FileUpdateParams{\n\t\t\tUpdateFileRequest: imagekit.UpdateFileRequestUnionParam{\n\t\t\t\tOfUpdateFileDetails: &imagekit.UpdateFileRequestUpdateFileDetailsParam{},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", file)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID/details \\\n -X PATCH \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "extensions": [\n {\n "name": "remove-bg",\n "options": {\n "add_shadow": true\n }\n },\n {\n "maxTags": 5,\n "minConfidence": 95,\n "name": "google-auto-tagging"\n },\n {\n "name": "ai-auto-description"\n },\n {\n "name": "ai-tasks",\n "tasks": [\n {\n "instruction": "What types of clothing items are visible in this image?",\n "type": "select_tags",\n "vocabulary": [\n "shirt",\n "tshirt",\n "dress",\n "trousers",\n "jacket"\n ]\n },\n {\n "instruction": "Is this a luxury or high-end fashion item?",\n "type": "yes_no",\n "on_yes": {\n "add_tags": [\n "luxury",\n "premium"\n ]\n }\n }\n ]\n },\n {\n "id": "ext_abc123",\n "name": "saved-extension"\n }\n ],\n "tags": [\n "tag1",\n "tag2"\n ]\n }\'', + }, + java: { + method: 'files().update', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileUpdateParams;\nimport com.imagekit.api.models.files.FileUpdateResponse;\nimport com.imagekit.api.models.files.UpdateFileRequest;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FileUpdateParams params = FileUpdateParams.builder()\n .fileId("fileId")\n .updateFileRequest(UpdateFileRequest.UpdateFileDetails.builder().build())\n .build();\n FileUpdateResponse file = client.files().update(params);\n }\n}', + }, + php: { + method: 'files->update', + example: + "files->update(\n 'fileId',\n customCoordinates: 'customCoordinates',\n customMetadata: ['foo' => 'bar'],\n description: 'description',\n extensions: [\n [\n 'name' => 'remove-bg',\n 'options' => [\n 'addShadow' => true,\n 'bgColor' => 'bg_color',\n 'bgImageURL' => 'bg_image_url',\n 'semitransparency' => true,\n ],\n ],\n ['maxTags' => 5, 'minConfidence' => 95, 'name' => 'google-auto-tagging'],\n ['name' => 'ai-auto-description'],\n [\n 'name' => 'ai-tasks',\n 'tasks' => [\n [\n 'instruction' => 'What types of clothing items are visible in this image?',\n 'type' => 'select_tags',\n 'maxSelections' => 1,\n 'minSelections' => 0,\n 'vocabulary' => ['shirt', 'tshirt', 'dress', 'trousers', 'jacket'],\n ],\n [\n 'instruction' => 'Is this a luxury or high-end fashion item?',\n 'type' => 'yes_no',\n 'onNo' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n 'onUnknown' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n 'onYes' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n ],\n ],\n ],\n ['id' => 'ext_abc123', 'name' => 'saved-extension'],\n ],\n removeAITags: ['string'],\n tags: ['tag1', 'tag2'],\n webhookURL: 'https://example.com',\n publish: ['isPublished' => true, 'includeFileVersions' => true],\n);\n\nvar_dump($file);", + }, + python: { + method: 'files.update', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nfile = client.files.update(\n file_id="fileId",\n)\nprint(file)', + }, + ruby: { + method: 'files.update', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nfile = image_kit.files.update("fileId", update_file_request: {})\n\nputs(file)', + }, + typescript: { + method: 'client.files.update', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst file = await client.files.update('fileId');\n\nconsole.log(file);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/files/{fileId}', + httpMethod: 'delete', + summary: 'Delete file', + description: + 'This API deletes the file and all its file versions permanently.\n\nNote: If a file or specific transformation has been requested in the past, then the response is cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API.\n', + stainlessPath: '(resource) files > (method) delete', + qualified: 'client.files.delete', + params: ['fileId: string;'], + markdown: + "## delete\n\n`client.files.delete(fileId: string): void`\n\n**delete** `/v1/files/{fileId}`\n\nThis API deletes the file and all its file versions permanently.\n\nNote: If a file or specific transformation has been requested in the past, then the response is cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API.\n\n\n### Parameters\n\n- `fileId: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nawait client.files.delete('fileId')\n```", + perLanguage: { + cli: { + method: 'files delete', + example: + "imagekit files delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId", + }, + csharp: { + method: 'Files.Delete', + example: + 'FileDeleteParams parameters = new() { FileID = "fileId" };\n\nawait client.Files.Delete(parameters);', + }, + go: { + method: 'client.Files.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\terr := client.Files.Delete(context.TODO(), "fileId")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID \\\n -X DELETE \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n client.files().delete("fileId");\n }\n}', + }, + php: { + method: 'files->delete', + example: + "files->delete('fileId');\n\nvar_dump($result);", + }, + python: { + method: 'files.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nclient.files.delete(\n "fileId",\n)', + }, + ruby: { + method: 'files.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresult = image_kit.files.delete("fileId")\n\nputs(result)', + }, + typescript: { + method: 'client.files.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nawait client.files.delete('fileId');", + }, + }, + }, + { + name: 'copy', + endpoint: '/v1/files/copy', + httpMethod: 'post', + summary: 'Copy file', + description: + 'This will copy a file from one folder to another. \n\nNote: If any file at the destination has the same name as the source file, then the source file and its versions (if `includeFileVersions` is set to true) will be appended to the destination file version history.\n', + stainlessPath: '(resource) files > (method) copy', + qualified: 'client.files.copy', + params: ['destinationPath: string;', 'sourceFilePath: string;', 'includeFileVersions?: boolean;'], + response: '{ }', + markdown: + "## copy\n\n`client.files.copy(destinationPath: string, sourceFilePath: string, includeFileVersions?: boolean): { }`\n\n**post** `/v1/files/copy`\n\nThis will copy a file from one folder to another. \n\nNote: If any file at the destination has the same name as the source file, then the source file and its versions (if `includeFileVersions` is set to true) will be appended to the destination file version history.\n\n\n### Parameters\n\n- `destinationPath: string`\n Full path to the folder you want to copy the above file into.\n\n\n- `sourceFilePath: string`\n The full path of the file you want to copy.\n\n\n- `includeFileVersions?: boolean`\n Option to copy all versions of a file. By default, only the current version of the file is copied. When set to true, all versions of the file will be copied. Default value - `false`.\n\n\n### Returns\n\n- `{ }`\n\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.files.copy({ destinationPath: '/folder/to/copy/into/', sourceFilePath: '/path/to/file.jpg' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'files copy', + example: + "imagekit files copy \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --destination-path /folder/to/copy/into/ \\\n --source-file-path /path/to/file.jpg", + }, + csharp: { + method: 'Files.Copy', + example: + 'FileCopyParams parameters = new()\n{\n DestinationPath = "/folder/to/copy/into/",\n SourceFilePath = "/path/to/file.jpg",\n};\n\nvar response = await client.Files.Copy(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Files.Copy', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Files.Copy(context.TODO(), imagekit.FileCopyParams{\n\t\tDestinationPath: "/folder/to/copy/into/",\n\t\tSourceFilePath: "/path/to/file.jpg",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/copy \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "destinationPath": "/folder/to/copy/into/",\n "sourceFilePath": "/path/to/file.jpg"\n }\'', + }, + java: { + method: 'files().copy', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileCopyParams;\nimport com.imagekit.api.models.files.FileCopyResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FileCopyParams params = FileCopyParams.builder()\n .destinationPath("/folder/to/copy/into/")\n .sourceFilePath("/path/to/file.jpg")\n .build();\n FileCopyResponse response = client.files().copy(params);\n }\n}', + }, + php: { + method: 'files->copy', + example: + "files->copy(\n destinationPath: '/folder/to/copy/into/',\n sourceFilePath: '/path/to/file.jpg',\n includeFileVersions: false,\n);\n\nvar_dump($response);", + }, + python: { + method: 'files.copy', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.files.copy(\n destination_path="/folder/to/copy/into/",\n source_file_path="/path/to/file.jpg",\n)\nprint(response)', + }, + ruby: { + method: 'files.copy', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.files.copy(destination_path: "/folder/to/copy/into/", source_file_path: "/path/to/file.jpg")\n\nputs(response)', + }, + typescript: { + method: 'client.files.copy', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.copy({\n destinationPath: '/folder/to/copy/into/',\n sourceFilePath: '/path/to/file.jpg',\n});\n\nconsole.log(response);", + }, + }, + }, + { + name: 'move', + endpoint: '/v1/files/move', + httpMethod: 'post', + summary: 'Move file', + description: + 'This will move a file and all its versions from one folder to another. \n\nNote: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file.\n', + stainlessPath: '(resource) files > (method) move', + qualified: 'client.files.move', + params: ['destinationPath: string;', 'sourceFilePath: string;'], + response: '{ }', + markdown: + "## move\n\n`client.files.move(destinationPath: string, sourceFilePath: string): { }`\n\n**post** `/v1/files/move`\n\nThis will move a file and all its versions from one folder to another. \n\nNote: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file.\n\n\n### Parameters\n\n- `destinationPath: string`\n Full path to the folder you want to move the above file into.\n\n\n- `sourceFilePath: string`\n The full path of the file you want to move.\n\n\n### Returns\n\n- `{ }`\n\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.files.move({ destinationPath: '/folder/to/move/into/', sourceFilePath: '/path/to/file.jpg' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'files move', + example: + "imagekit files move \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --destination-path /folder/to/move/into/ \\\n --source-file-path /path/to/file.jpg", + }, + csharp: { + method: 'Files.Move', + example: + 'FileMoveParams parameters = new()\n{\n DestinationPath = "/folder/to/move/into/",\n SourceFilePath = "/path/to/file.jpg",\n};\n\nvar response = await client.Files.Move(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Files.Move', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Files.Move(context.TODO(), imagekit.FileMoveParams{\n\t\tDestinationPath: "/folder/to/move/into/",\n\t\tSourceFilePath: "/path/to/file.jpg",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/move \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "destinationPath": "/folder/to/move/into/",\n "sourceFilePath": "/path/to/file.jpg"\n }\'', + }, + java: { + method: 'files().move', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileMoveParams;\nimport com.imagekit.api.models.files.FileMoveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FileMoveParams params = FileMoveParams.builder()\n .destinationPath("/folder/to/move/into/")\n .sourceFilePath("/path/to/file.jpg")\n .build();\n FileMoveResponse response = client.files().move(params);\n }\n}', + }, + php: { + method: 'files->move', + example: + "files->move(\n destinationPath: '/folder/to/move/into/', sourceFilePath: '/path/to/file.jpg'\n);\n\nvar_dump($response);", + }, + python: { + method: 'files.move', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.files.move(\n destination_path="/folder/to/move/into/",\n source_file_path="/path/to/file.jpg",\n)\nprint(response)', + }, + ruby: { + method: 'files.move', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.files.move(destination_path: "/folder/to/move/into/", source_file_path: "/path/to/file.jpg")\n\nputs(response)', + }, + typescript: { + method: 'client.files.move', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.move({\n destinationPath: '/folder/to/move/into/',\n sourceFilePath: '/path/to/file.jpg',\n});\n\nconsole.log(response);", + }, + }, + }, + { + name: 'rename', + endpoint: '/v1/files/rename', + httpMethod: 'put', + summary: 'Rename file', + description: + 'You can rename an already existing file in the media library using rename file API. This operation would rename all file versions of the file. \n\nNote: The old URLs will stop working. The file/file version URLs cached on CDN will continue to work unless a purge is requested.\n', + stainlessPath: '(resource) files > (method) rename', + qualified: 'client.files.rename', + params: ['filePath: string;', 'newFileName: string;', 'purgeCache?: boolean;'], + response: '{ purgeRequestId?: string; }', + markdown: + "## rename\n\n`client.files.rename(filePath: string, newFileName: string, purgeCache?: boolean): { purgeRequestId?: string; }`\n\n**put** `/v1/files/rename`\n\nYou can rename an already existing file in the media library using rename file API. This operation would rename all file versions of the file. \n\nNote: The old URLs will stop working. The file/file version URLs cached on CDN will continue to work unless a purge is requested.\n\n\n### Parameters\n\n- `filePath: string`\n The full path of the file you want to rename.\n\n\n- `newFileName: string`\n The new name of the file. A filename can contain:\n\nAlphanumeric Characters: `a-z`, `A-Z`, `0-9` (including Unicode letters, marks, and numerals in other languages).\nSpecial Characters: `.`, `_`, and `-`.\n\nAny other character, including space, will be replaced by `_`.\n\n\n- `purgeCache?: boolean`\n Option to purge cache for the old file and its versions' URLs.\n\nWhen set to true, it will internally issue a purge cache request on CDN to remove cached content of old file and its versions. This purge request is counted against your monthly purge quota.\n\nNote: If the old file were accessible at `https://ik.imagekit.io/demo/old-filename.jpg`, a purge cache request would be issued against `https://ik.imagekit.io/demo/old-filename.jpg*` (with a wildcard at the end). It will remove the file and its versions' URLs and any transformations made using query parameters on this file or its versions. However, the cache for file transformations made using path parameters will persist. You can purge them using the purge API. For more details, refer to the purge API documentation.\n\n\n\nDefault value - `false`\n\n\n### Returns\n\n- `{ purgeRequestId?: string; }`\n\n - `purgeRequestId?: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.files.rename({ filePath: '/path/to/file.jpg', newFileName: 'newFileName.jpg' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'files rename', + example: + "imagekit files rename \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-path /path/to/file.jpg \\\n --new-file-name newFileName.jpg", + }, + csharp: { + method: 'Files.Rename', + example: + 'FileRenameParams parameters = new()\n{\n FilePath = "/path/to/file.jpg",\n NewFileName = "newFileName.jpg",\n};\n\nvar response = await client.Files.Rename(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Files.Rename', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Files.Rename(context.TODO(), imagekit.FileRenameParams{\n\t\tFilePath: "/path/to/file.jpg",\n\t\tNewFileName: "newFileName.jpg",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.PurgeRequestID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/rename \\\n -X PUT \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "filePath": "/path/to/file.jpg",\n "newFileName": "newFileName.jpg",\n "purgeCache": true\n }\'', + }, + java: { + method: 'files().rename', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileRenameParams;\nimport com.imagekit.api.models.files.FileRenameResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FileRenameParams params = FileRenameParams.builder()\n .filePath("/path/to/file.jpg")\n .newFileName("newFileName.jpg")\n .build();\n FileRenameResponse response = client.files().rename(params);\n }\n}', + }, + php: { + method: 'files->rename', + example: + "files->rename(\n filePath: '/path/to/file.jpg',\n newFileName: 'newFileName.jpg',\n purgeCache: true,\n);\n\nvar_dump($response);", + }, + python: { + method: 'files.rename', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.files.rename(\n file_path="/path/to/file.jpg",\n new_file_name="newFileName.jpg",\n)\nprint(response.purge_request_id)', + }, + ruby: { + method: 'files.rename', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.files.rename(file_path: "/path/to/file.jpg", new_file_name: "newFileName.jpg")\n\nputs(response)', + }, + typescript: { + method: 'client.files.rename', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.rename({\n filePath: '/path/to/file.jpg',\n newFileName: 'newFileName.jpg',\n});\n\nconsole.log(response.purgeRequestId);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/files/batch/deleteByFileIds', + httpMethod: 'post', + summary: 'Delete multiple files', + description: + 'This API deletes multiple files and all their file versions permanently.\n\nNote: If a file or specific transformation has been requested in the past, then the response is cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API.\n\nA maximum of 100 files can be deleted at a time.\n', + stainlessPath: '(resource) files.bulk > (method) delete', + qualified: 'client.files.bulk.delete', + params: ['fileIds: string[];'], + response: '{ successfullyDeletedFileIds?: string[]; }', + markdown: + "## delete\n\n`client.files.bulk.delete(fileIds: string[]): { successfullyDeletedFileIds?: string[]; }`\n\n**post** `/v1/files/batch/deleteByFileIds`\n\nThis API deletes multiple files and all their file versions permanently.\n\nNote: If a file or specific transformation has been requested in the past, then the response is cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API.\n\nA maximum of 100 files can be deleted at a time.\n\n\n### Parameters\n\n- `fileIds: string[]`\n An array of fileIds which you want to delete.\n\n\n### Returns\n\n- `{ successfullyDeletedFileIds?: string[]; }`\n\n - `successfullyDeletedFileIds?: string[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst bulk = await client.files.bulk.delete({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'] });\n\nconsole.log(bulk);\n```", + perLanguage: { + cli: { + method: 'bulk delete', + example: + "imagekit files:bulk delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id 598821f949c0a938d57563bd \\\n --file-id 598821f949c0a938d57563be", + }, + csharp: { + method: 'Files.Bulk.Delete', + example: + 'BulkDeleteParams parameters = new()\n{\n FileIds =\n [\n "598821f949c0a938d57563bd", "598821f949c0a938d57563be"\n ],\n};\n\nvar bulk = await client.Files.Bulk.Delete(parameters);\n\nConsole.WriteLine(bulk);', + }, + go: { + method: 'client.Files.Bulk.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tbulk, err := client.Files.Bulk.Delete(context.TODO(), imagekit.FileBulkDeleteParams{\n\t\tFileIDs: []string{"598821f949c0a938d57563bd", "598821f949c0a938d57563be"},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", bulk.SuccessfullyDeletedFileIDs)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/batch/deleteByFileIds \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "fileIds": [\n "598821f949c0a938d57563bd",\n "598821f949c0a938d57563be"\n ]\n }\'', + }, + java: { + method: 'files().bulk().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.bulk.BulkDeleteParams;\nimport com.imagekit.api.models.files.bulk.BulkDeleteResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n BulkDeleteParams params = BulkDeleteParams.builder()\n .addFileId("598821f949c0a938d57563bd")\n .addFileId("598821f949c0a938d57563be")\n .build();\n BulkDeleteResponse bulk = client.files().bulk().delete(params);\n }\n}', + }, + php: { + method: 'files->bulk->delete', + example: + "files->bulk->delete(\n fileIDs: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be']\n);\n\nvar_dump($bulk);", + }, + python: { + method: 'files.bulk.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nbulk = client.files.bulk.delete(\n file_ids=["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],\n)\nprint(bulk.successfully_deleted_file_ids)', + }, + ruby: { + method: 'files.bulk.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nbulk = image_kit.files.bulk.delete(file_ids: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"])\n\nputs(bulk)', + }, + typescript: { + method: 'client.files.bulk.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst bulk = await client.files.bulk.delete({\n fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'],\n});\n\nconsole.log(bulk.successfullyDeletedFileIds);", + }, + }, + }, + { + name: 'addTags', + endpoint: '/v1/files/addTags', + httpMethod: 'post', + summary: 'Add tags (bulk)', + description: + 'This API adds tags to multiple files in bulk. A maximum of 50 files can be specified at a time.\n', + stainlessPath: '(resource) files.bulk > (method) addTags', + qualified: 'client.files.bulk.addTags', + params: ['fileIds: string[];', 'tags: string[];'], + response: '{ successfullyUpdatedFileIds?: string[]; }', + markdown: + "## addTags\n\n`client.files.bulk.addTags(fileIds: string[], tags: string[]): { successfullyUpdatedFileIds?: string[]; }`\n\n**post** `/v1/files/addTags`\n\nThis API adds tags to multiple files in bulk. A maximum of 50 files can be specified at a time.\n\n\n### Parameters\n\n- `fileIds: string[]`\n An array of fileIds to which you want to add tags.\n\n\n- `tags: string[]`\n An array of tags that you want to add to the files.\n\n\n### Returns\n\n- `{ successfullyUpdatedFileIds?: string[]; }`\n\n - `successfullyUpdatedFileIds?: string[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.files.bulk.addTags({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], tags: ['t-shirt', 'round-neck', 'sale2019'] });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'bulk addTags', + example: + "imagekit files:bulk add-tags \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id 598821f949c0a938d57563bd \\\n --file-id 598821f949c0a938d57563be \\\n --tag t-shirt \\\n --tag round-neck \\\n --tag sale2019", + }, + csharp: { + method: 'Files.Bulk.AddTags', + example: + 'BulkAddTagsParams parameters = new()\n{\n FileIds =\n [\n "598821f949c0a938d57563bd", "598821f949c0a938d57563be"\n ],\n Tags =\n [\n "t-shirt", "round-neck", "sale2019"\n ],\n};\n\nvar response = await client.Files.Bulk.AddTags(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Files.Bulk.AddTags', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Files.Bulk.AddTags(context.TODO(), imagekit.FileBulkAddTagsParams{\n\t\tFileIDs: []string{"598821f949c0a938d57563bd", "598821f949c0a938d57563be"},\n\t\tTags: []string{"t-shirt", "round-neck", "sale2019"},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.SuccessfullyUpdatedFileIDs)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/addTags \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "fileIds": [\n "598821f949c0a938d57563bd",\n "598821f949c0a938d57563be"\n ],\n "tags": [\n "t-shirt",\n "round-neck",\n "sale2019"\n ]\n }\'', + }, + java: { + method: 'files().bulk().addTags', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.bulk.BulkAddTagsParams;\nimport com.imagekit.api.models.files.bulk.BulkAddTagsResponse;\nimport java.util.List;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n BulkAddTagsParams params = BulkAddTagsParams.builder()\n .addFileId("598821f949c0a938d57563bd")\n .addFileId("598821f949c0a938d57563be")\n .tags(List.of(\n "t-shirt",\n "round-neck",\n "sale2019"\n ))\n .build();\n BulkAddTagsResponse response = client.files().bulk().addTags(params);\n }\n}', + }, + php: { + method: 'files->bulk->addTags', + example: + "files->bulk->addTags(\n fileIDs: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'],\n tags: ['t-shirt', 'round-neck', 'sale2019'],\n);\n\nvar_dump($response);", + }, + python: { + method: 'files.bulk.add_tags', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.files.bulk.add_tags(\n file_ids=["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],\n tags=["t-shirt", "round-neck", "sale2019"],\n)\nprint(response.successfully_updated_file_ids)', + }, + ruby: { + method: 'files.bulk.add_tags', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.files.bulk.add_tags(\n file_ids: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],\n tags: ["t-shirt", "round-neck", "sale2019"]\n)\n\nputs(response)', + }, + typescript: { + method: 'client.files.bulk.addTags', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.bulk.addTags({\n fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'],\n tags: ['t-shirt', 'round-neck', 'sale2019'],\n});\n\nconsole.log(response.successfullyUpdatedFileIds);", + }, + }, + }, + { + name: 'removeTags', + endpoint: '/v1/files/removeTags', + httpMethod: 'post', + summary: 'Remove tags (bulk)', + description: + 'This API removes tags from multiple files in bulk. A maximum of 50 files can be specified at a time.\n', + stainlessPath: '(resource) files.bulk > (method) removeTags', + qualified: 'client.files.bulk.removeTags', + params: ['fileIds: string[];', 'tags: string[];'], + response: '{ successfullyUpdatedFileIds?: string[]; }', + markdown: + "## removeTags\n\n`client.files.bulk.removeTags(fileIds: string[], tags: string[]): { successfullyUpdatedFileIds?: string[]; }`\n\n**post** `/v1/files/removeTags`\n\nThis API removes tags from multiple files in bulk. A maximum of 50 files can be specified at a time.\n\n\n### Parameters\n\n- `fileIds: string[]`\n An array of fileIds from which you want to remove tags.\n\n\n- `tags: string[]`\n An array of tags that you want to remove from the files.\n\n\n### Returns\n\n- `{ successfullyUpdatedFileIds?: string[]; }`\n\n - `successfullyUpdatedFileIds?: string[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.files.bulk.removeTags({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], tags: ['t-shirt', 'round-neck', 'sale2019'] });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'bulk removeTags', + example: + "imagekit files:bulk remove-tags \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id 598821f949c0a938d57563bd \\\n --file-id 598821f949c0a938d57563be \\\n --tag t-shirt \\\n --tag round-neck \\\n --tag sale2019", + }, + csharp: { + method: 'Files.Bulk.RemoveTags', + example: + 'BulkRemoveTagsParams parameters = new()\n{\n FileIds =\n [\n "598821f949c0a938d57563bd", "598821f949c0a938d57563be"\n ],\n Tags =\n [\n "t-shirt", "round-neck", "sale2019"\n ],\n};\n\nvar response = await client.Files.Bulk.RemoveTags(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Files.Bulk.RemoveTags', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Files.Bulk.RemoveTags(context.TODO(), imagekit.FileBulkRemoveTagsParams{\n\t\tFileIDs: []string{"598821f949c0a938d57563bd", "598821f949c0a938d57563be"},\n\t\tTags: []string{"t-shirt", "round-neck", "sale2019"},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.SuccessfullyUpdatedFileIDs)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/removeTags \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "fileIds": [\n "598821f949c0a938d57563bd",\n "598821f949c0a938d57563be"\n ],\n "tags": [\n "t-shirt",\n "round-neck",\n "sale2019"\n ]\n }\'', + }, + java: { + method: 'files().bulk().removeTags', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.bulk.BulkRemoveTagsParams;\nimport com.imagekit.api.models.files.bulk.BulkRemoveTagsResponse;\nimport java.util.List;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n BulkRemoveTagsParams params = BulkRemoveTagsParams.builder()\n .addFileId("598821f949c0a938d57563bd")\n .addFileId("598821f949c0a938d57563be")\n .tags(List.of(\n "t-shirt",\n "round-neck",\n "sale2019"\n ))\n .build();\n BulkRemoveTagsResponse response = client.files().bulk().removeTags(params);\n }\n}', + }, + php: { + method: 'files->bulk->removeTags', + example: + "files->bulk->removeTags(\n fileIDs: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'],\n tags: ['t-shirt', 'round-neck', 'sale2019'],\n);\n\nvar_dump($response);", + }, + python: { + method: 'files.bulk.remove_tags', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.files.bulk.remove_tags(\n file_ids=["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],\n tags=["t-shirt", "round-neck", "sale2019"],\n)\nprint(response.successfully_updated_file_ids)', + }, + ruby: { + method: 'files.bulk.remove_tags', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.files.bulk.remove_tags(\n file_ids: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],\n tags: ["t-shirt", "round-neck", "sale2019"]\n)\n\nputs(response)', + }, + typescript: { + method: 'client.files.bulk.removeTags', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.bulk.removeTags({\n fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'],\n tags: ['t-shirt', 'round-neck', 'sale2019'],\n});\n\nconsole.log(response.successfullyUpdatedFileIds);", + }, + }, + }, + { + name: 'removeAiTags', + endpoint: '/v1/files/removeAITags', + httpMethod: 'post', + summary: 'Remove AI tags (bulk)', + description: + 'This API removes AITags from multiple files in bulk. A maximum of 50 files can be specified at a time.\n', + stainlessPath: '(resource) files.bulk > (method) removeAiTags', + qualified: 'client.files.bulk.removeAITags', + params: ['AITags: string[];', 'fileIds: string[];'], + response: '{ successfullyUpdatedFileIds?: string[]; }', + markdown: + "## removeAiTags\n\n`client.files.bulk.removeAITags(AITags: string[], fileIds: string[]): { successfullyUpdatedFileIds?: string[]; }`\n\n**post** `/v1/files/removeAITags`\n\nThis API removes AITags from multiple files in bulk. A maximum of 50 files can be specified at a time.\n\n\n### Parameters\n\n- `AITags: string[]`\n An array of AITags that you want to remove from the files.\n\n\n- `fileIds: string[]`\n An array of fileIds from which you want to remove AITags.\n\n\n### Returns\n\n- `{ successfullyUpdatedFileIds?: string[]; }`\n\n - `successfullyUpdatedFileIds?: string[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.files.bulk.removeAITags({ AITags: ['t-shirt', 'round-neck', 'sale2019'], fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'] });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'bulk removeAiTags', + example: + "imagekit files:bulk remove-ai-tags \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --ai-tag t-shirt \\\n --ai-tag round-neck \\\n --ai-tag sale2019 \\\n --file-id 598821f949c0a938d57563bd \\\n --file-id 598821f949c0a938d57563be", + }, + csharp: { + method: 'Files.Bulk.RemoveAITags', + example: + 'BulkRemoveAITagsParams parameters = new()\n{\n AITags =\n [\n "t-shirt", "round-neck", "sale2019"\n ],\n FileIds =\n [\n "598821f949c0a938d57563bd", "598821f949c0a938d57563be"\n ],\n};\n\nvar response = await client.Files.Bulk.RemoveAITags(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Files.Bulk.RemoveAITags', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Files.Bulk.RemoveAITags(context.TODO(), imagekit.FileBulkRemoveAITagsParams{\n\t\tAITags: []string{"t-shirt", "round-neck", "sale2019"},\n\t\tFileIDs: []string{"598821f949c0a938d57563bd", "598821f949c0a938d57563be"},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.SuccessfullyUpdatedFileIDs)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/removeAITags \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "AITags": [\n "t-shirt",\n "round-neck",\n "sale2019"\n ],\n "fileIds": [\n "598821f949c0a938d57563bd",\n "598821f949c0a938d57563be"\n ]\n }\'', + }, + java: { + method: 'files().bulk().removeAiTags', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.bulk.BulkRemoveAiTagsParams;\nimport com.imagekit.api.models.files.bulk.BulkRemoveAiTagsResponse;\nimport java.util.List;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n BulkRemoveAiTagsParams params = BulkRemoveAiTagsParams.builder()\n .aiTags(List.of(\n "t-shirt",\n "round-neck",\n "sale2019"\n ))\n .addFileId("598821f949c0a938d57563bd")\n .addFileId("598821f949c0a938d57563be")\n .build();\n BulkRemoveAiTagsResponse response = client.files().bulk().removeAiTags(params);\n }\n}', + }, + php: { + method: 'files->bulk->removeAITags', + example: + "files->bulk->removeAITags(\n aiTags: ['t-shirt', 'round-neck', 'sale2019'],\n fileIDs: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'],\n);\n\nvar_dump($response);", + }, + python: { + method: 'files.bulk.remove_ai_tags', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.files.bulk.remove_ai_tags(\n ai_tags=["t-shirt", "round-neck", "sale2019"],\n file_ids=["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],\n)\nprint(response.successfully_updated_file_ids)', + }, + ruby: { + method: 'files.bulk.remove_ai_tags', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.files.bulk.remove_ai_tags(\n ai_tags: ["t-shirt", "round-neck", "sale2019"],\n file_ids: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"]\n)\n\nputs(response)', + }, + typescript: { + method: 'client.files.bulk.removeAITags', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.bulk.removeAITags({\n AITags: ['t-shirt', 'round-neck', 'sale2019'],\n fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'],\n});\n\nconsole.log(response.successfullyUpdatedFileIds);", + }, + }, + }, + { + name: 'list', + endpoint: '/v1/files/{fileId}/versions', + httpMethod: 'get', + summary: 'List file versions', + description: 'This API returns details of all versions of a file.\n', + stainlessPath: '(resource) files.versions > (method) list', + qualified: 'client.files.versions.list', + params: ['fileId: string;'], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }[]", + markdown: + "## list\n\n`client.files.versions.list(fileId: string): object[]`\n\n**get** `/v1/files/{fileId}/versions`\n\nThis API returns details of all versions of a file.\n\n\n### Parameters\n\n- `fileId: string`\n\n### Returns\n\n- `{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst files = await client.files.versions.list('fileId');\n\nconsole.log(files);\n```", + perLanguage: { + cli: { + method: 'versions list', + example: + "imagekit files:versions list \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId", + }, + csharp: { + method: 'Files.Versions.List', + example: + 'VersionListParams parameters = new() { FileID = "fileId" };\n\nvar files = await client.Files.Versions.List(parameters);\n\nConsole.WriteLine(files);', + }, + go: { + method: 'client.Files.Versions.List', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tfiles, err := client.Files.Versions.List(context.TODO(), "fileId")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", files)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID/versions \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().versions().list', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.File;\nimport com.imagekit.api.models.files.versions.VersionListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n List files = client.files().versions().list("fileId");\n }\n}', + }, + php: { + method: 'files->versions->list', + example: + "files->versions->list('fileId');\n\nvar_dump($files);", + }, + python: { + method: 'files.versions.list', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nfiles = client.files.versions.list(\n "fileId",\n)\nprint(files)', + }, + ruby: { + method: 'files.versions.list', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nfiles = image_kit.files.versions.list("fileId")\n\nputs(files)', + }, + typescript: { + method: 'client.files.versions.list', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst files = await client.files.versions.list('fileId');\n\nconsole.log(files);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/files/{fileId}/versions/{versionId}', + httpMethod: 'get', + summary: 'Get file version details', + description: 'This API returns an object with details or attributes of a file version.', + stainlessPath: '(resource) files.versions > (method) get', + qualified: 'client.files.versions.get', + params: ['fileId: string;', 'versionId: string;'], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }", + markdown: + "## get\n\n`client.files.versions.get(fileId: string, versionId: string): { AITags?: object[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: object; videoCodec?: string; width?: number; }`\n\n**get** `/v1/files/{fileId}/versions/{versionId}`\n\nThis API returns an object with details or attributes of a file version.\n\n### Parameters\n\n- `fileId: string`\n\n- `versionId: string`\n\n### Returns\n\n- `{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }`\n Object containing details of a file or file version.\n\n - `AITags?: { confidence?: number; name?: string; source?: string; }[]`\n - `audioCodec?: string`\n - `bitRate?: number`\n - `createdAt?: string`\n - `customCoordinates?: string`\n - `customMetadata?: object`\n - `description?: string`\n - `duration?: number`\n - `embeddedMetadata?: object`\n - `fileId?: string`\n - `filePath?: string`\n - `fileType?: string`\n - `hasAlpha?: boolean`\n - `height?: number`\n - `isPrivateFile?: boolean`\n - `isPublished?: boolean`\n - `mime?: string`\n - `name?: string`\n - `selectedFieldsSchema?: object`\n - `size?: number`\n - `tags?: string[]`\n - `thumbnail?: string`\n - `type?: 'file' | 'file-version'`\n - `updatedAt?: string`\n - `url?: string`\n - `versionInfo?: { id?: string; name?: string; }`\n - `videoCodec?: string`\n - `width?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst file = await client.files.versions.get('versionId', { fileId: 'fileId' });\n\nconsole.log(file);\n```", + perLanguage: { + cli: { + method: 'versions get', + example: + "imagekit files:versions get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId \\\n --version-id versionId", + }, + csharp: { + method: 'Files.Versions.Get', + example: + 'VersionGetParams parameters = new()\n{\n FileID = "fileId",\n VersionID = "versionId",\n};\n\nvar file = await client.Files.Versions.Get(parameters);\n\nConsole.WriteLine(file);', + }, + go: { + method: 'client.Files.Versions.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tfile, err := client.Files.Versions.Get(\n\t\tcontext.TODO(),\n\t\t"versionId",\n\t\timagekit.FileVersionGetParams{\n\t\t\tFileID: "fileId",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", file.VideoCodec)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID/versions/$VERSION_ID \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().versions().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.File;\nimport com.imagekit.api.models.files.versions.VersionGetParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n VersionGetParams params = VersionGetParams.builder()\n .fileId("fileId")\n .versionId("versionId")\n .build();\n File file = client.files().versions().get(params);\n }\n}', + }, + php: { + method: 'files->versions->get', + example: + "files->versions->get('versionId', fileID: 'fileId');\n\nvar_dump($file);", + }, + python: { + method: 'files.versions.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nfile = client.files.versions.get(\n version_id="versionId",\n file_id="fileId",\n)\nprint(file.video_codec)', + }, + ruby: { + method: 'files.versions.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nfile = image_kit.files.versions.get("versionId", file_id: "fileId")\n\nputs(file)', + }, + typescript: { + method: 'client.files.versions.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst file = await client.files.versions.get('versionId', { fileId: 'fileId' });\n\nconsole.log(file.videoCodec);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/files/{fileId}/versions/{versionId}', + httpMethod: 'delete', + summary: 'Delete file version', + description: + 'This API deletes a non-current file version permanently. The API returns an empty response.\n\nNote: If you want to delete all versions of a file, use the delete file API.\n', + stainlessPath: '(resource) files.versions > (method) delete', + qualified: 'client.files.versions.delete', + params: ['fileId: string;', 'versionId: string;'], + response: '{ }', + markdown: + "## delete\n\n`client.files.versions.delete(fileId: string, versionId: string): { }`\n\n**delete** `/v1/files/{fileId}/versions/{versionId}`\n\nThis API deletes a non-current file version permanently. The API returns an empty response.\n\nNote: If you want to delete all versions of a file, use the delete file API.\n\n\n### Parameters\n\n- `fileId: string`\n\n- `versionId: string`\n\n### Returns\n\n- `{ }`\n\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst version = await client.files.versions.delete('versionId', { fileId: 'fileId' });\n\nconsole.log(version);\n```", + perLanguage: { + cli: { + method: 'versions delete', + example: + "imagekit files:versions delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId \\\n --version-id versionId", + }, + csharp: { + method: 'Files.Versions.Delete', + example: + 'VersionDeleteParams parameters = new()\n{\n FileID = "fileId",\n VersionID = "versionId",\n};\n\nvar version = await client.Files.Versions.Delete(parameters);\n\nConsole.WriteLine(version);', + }, + go: { + method: 'client.Files.Versions.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tversion, err := client.Files.Versions.Delete(\n\t\tcontext.TODO(),\n\t\t"versionId",\n\t\timagekit.FileVersionDeleteParams{\n\t\t\tFileID: "fileId",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", version)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID/versions/$VERSION_ID \\\n -X DELETE \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().versions().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.versions.VersionDeleteParams;\nimport com.imagekit.api.models.files.versions.VersionDeleteResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n VersionDeleteParams params = VersionDeleteParams.builder()\n .fileId("fileId")\n .versionId("versionId")\n .build();\n VersionDeleteResponse version = client.files().versions().delete(params);\n }\n}', + }, + php: { + method: 'files->versions->delete', + example: + "files->versions->delete('versionId', fileID: 'fileId');\n\nvar_dump($version);", + }, + python: { + method: 'files.versions.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nversion = client.files.versions.delete(\n version_id="versionId",\n file_id="fileId",\n)\nprint(version)', + }, + ruby: { + method: 'files.versions.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nversion = image_kit.files.versions.delete("versionId", file_id: "fileId")\n\nputs(version)', + }, + typescript: { + method: 'client.files.versions.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst version = await client.files.versions.delete('versionId', { fileId: 'fileId' });\n\nconsole.log(version);", + }, + }, + }, + { + name: 'restore', + endpoint: '/v1/files/{fileId}/versions/{versionId}/restore', + httpMethod: 'put', + summary: 'Restore file version', + description: 'This API restores a file version as the current file version.\n', + stainlessPath: '(resource) files.versions > (method) restore', + qualified: 'client.files.versions.restore', + params: ['fileId: string;', 'versionId: string;'], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }", + markdown: + "## restore\n\n`client.files.versions.restore(fileId: string, versionId: string): { AITags?: object[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: object; videoCodec?: string; width?: number; }`\n\n**put** `/v1/files/{fileId}/versions/{versionId}/restore`\n\nThis API restores a file version as the current file version.\n\n\n### Parameters\n\n- `fileId: string`\n\n- `versionId: string`\n\n### Returns\n\n- `{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }`\n Object containing details of a file or file version.\n\n - `AITags?: { confidence?: number; name?: string; source?: string; }[]`\n - `audioCodec?: string`\n - `bitRate?: number`\n - `createdAt?: string`\n - `customCoordinates?: string`\n - `customMetadata?: object`\n - `description?: string`\n - `duration?: number`\n - `embeddedMetadata?: object`\n - `fileId?: string`\n - `filePath?: string`\n - `fileType?: string`\n - `hasAlpha?: boolean`\n - `height?: number`\n - `isPrivateFile?: boolean`\n - `isPublished?: boolean`\n - `mime?: string`\n - `name?: string`\n - `selectedFieldsSchema?: object`\n - `size?: number`\n - `tags?: string[]`\n - `thumbnail?: string`\n - `type?: 'file' | 'file-version'`\n - `updatedAt?: string`\n - `url?: string`\n - `versionInfo?: { id?: string; name?: string; }`\n - `videoCodec?: string`\n - `width?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst file = await client.files.versions.restore('versionId', { fileId: 'fileId' });\n\nconsole.log(file);\n```", + perLanguage: { + cli: { + method: 'versions restore', + example: + "imagekit files:versions restore \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId \\\n --version-id versionId", + }, + csharp: { + method: 'Files.Versions.Restore', + example: + 'VersionRestoreParams parameters = new()\n{\n FileID = "fileId",\n VersionID = "versionId",\n};\n\nvar file = await client.Files.Versions.Restore(parameters);\n\nConsole.WriteLine(file);', + }, + go: { + method: 'client.Files.Versions.Restore', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tfile, err := client.Files.Versions.Restore(\n\t\tcontext.TODO(),\n\t\t"versionId",\n\t\timagekit.FileVersionRestoreParams{\n\t\t\tFileID: "fileId",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", file.VideoCodec)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID/versions/$VERSION_ID/restore \\\n -X PUT \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().versions().restore', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.File;\nimport com.imagekit.api.models.files.versions.VersionRestoreParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n VersionRestoreParams params = VersionRestoreParams.builder()\n .fileId("fileId")\n .versionId("versionId")\n .build();\n File file = client.files().versions().restore(params);\n }\n}', + }, + php: { + method: 'files->versions->restore', + example: + "files->versions->restore('versionId', fileID: 'fileId');\n\nvar_dump($file);", + }, + python: { + method: 'files.versions.restore', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nfile = client.files.versions.restore(\n version_id="versionId",\n file_id="fileId",\n)\nprint(file.video_codec)', + }, + ruby: { + method: 'files.versions.restore', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nfile = image_kit.files.versions.restore("versionId", file_id: "fileId")\n\nputs(file)', + }, + typescript: { + method: 'client.files.versions.restore', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst file = await client.files.versions.restore('versionId', { fileId: 'fileId' });\n\nconsole.log(file.videoCodec);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/files/{fileId}/metadata', + httpMethod: 'get', + summary: 'Get uploaded file metadata', + description: + 'You can programmatically get image EXIF, pHash, and other metadata for uploaded files in the ImageKit.io media library using this API.\n\nYou can also get the metadata in upload API response by passing `metadata` in `responseFields` parameter.\n', + stainlessPath: '(resource) files.metadata > (method) get', + qualified: 'client.files.metadata.get', + params: ['fileId: string;'], + response: + '{ audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: { exif?: object; gps?: object; image?: object; interoperability?: object; makernote?: object; thumbnail?: object; }; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }', + markdown: + "## get\n\n`client.files.metadata.get(fileId: string): { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: object; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }`\n\n**get** `/v1/files/{fileId}/metadata`\n\nYou can programmatically get image EXIF, pHash, and other metadata for uploaded files in the ImageKit.io media library using this API.\n\nYou can also get the metadata in upload API response by passing `metadata` in `responseFields` parameter.\n\n\n### Parameters\n\n- `fileId: string`\n\n### Returns\n\n- `{ audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: { exif?: { ApertureValue?: number; ColorSpace?: number; CreateDate?: string; CustomRendered?: number; DateTimeOriginal?: string; ExifImageHeight?: number; ExifImageWidth?: number; ExifVersion?: string; ExposureCompensation?: number; ExposureMode?: number; ExposureProgram?: number; ExposureTime?: number; Flash?: number; FlashpixVersion?: string; FNumber?: number; FocalLength?: number; FocalPlaneResolutionUnit?: number; FocalPlaneXResolution?: number; FocalPlaneYResolution?: number; InteropOffset?: number; ISO?: number; MeteringMode?: number; SceneCaptureType?: number; ShutterSpeedValue?: number; SubSecTime?: string; WhiteBalance?: number; }; gps?: { GPSVersionID?: number[]; }; image?: { ExifOffset?: number; GPSInfo?: number; Make?: string; Model?: string; ModifyDate?: string; Orientation?: number; ResolutionUnit?: number; Software?: string; XResolution?: number; YCbCrPositioning?: number; YResolution?: number; }; interoperability?: { InteropIndex?: string; InteropVersion?: string; }; makernote?: object; thumbnail?: { Compression?: number; ResolutionUnit?: number; ThumbnailLength?: number; ThumbnailOffset?: number; XResolution?: number; YResolution?: number; }; }; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }`\n JSON object containing metadata.\n\n - `audioCodec?: string`\n - `bitRate?: number`\n - `density?: number`\n - `duration?: number`\n - `exif?: { exif?: { ApertureValue?: number; ColorSpace?: number; CreateDate?: string; CustomRendered?: number; DateTimeOriginal?: string; ExifImageHeight?: number; ExifImageWidth?: number; ExifVersion?: string; ExposureCompensation?: number; ExposureMode?: number; ExposureProgram?: number; ExposureTime?: number; Flash?: number; FlashpixVersion?: string; FNumber?: number; FocalLength?: number; FocalPlaneResolutionUnit?: number; FocalPlaneXResolution?: number; FocalPlaneYResolution?: number; InteropOffset?: number; ISO?: number; MeteringMode?: number; SceneCaptureType?: number; ShutterSpeedValue?: number; SubSecTime?: string; WhiteBalance?: number; }; gps?: { GPSVersionID?: number[]; }; image?: { ExifOffset?: number; GPSInfo?: number; Make?: string; Model?: string; ModifyDate?: string; Orientation?: number; ResolutionUnit?: number; Software?: string; XResolution?: number; YCbCrPositioning?: number; YResolution?: number; }; interoperability?: { InteropIndex?: string; InteropVersion?: string; }; makernote?: object; thumbnail?: { Compression?: number; ResolutionUnit?: number; ThumbnailLength?: number; ThumbnailOffset?: number; XResolution?: number; YResolution?: number; }; }`\n - `format?: string`\n - `hasColorProfile?: boolean`\n - `hasTransparency?: boolean`\n - `height?: number`\n - `pHash?: string`\n - `quality?: number`\n - `size?: number`\n - `videoCodec?: string`\n - `width?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst metadata = await client.files.metadata.get('fileId');\n\nconsole.log(metadata);\n```", + perLanguage: { + cli: { + method: 'metadata get', + example: + "imagekit files:metadata get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file-id fileId", + }, + csharp: { + method: 'Files.Metadata.Get', + example: + 'MetadataGetParams parameters = new() { FileID = "fileId" };\n\nvar metadata = await client.Files.Metadata.Get(parameters);\n\nConsole.WriteLine(metadata);', + }, + go: { + method: 'client.Files.Metadata.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tmetadata, err := client.Files.Metadata.Get(context.TODO(), "fileId")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", metadata.VideoCodec)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/$FILE_ID/metadata \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().metadata().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.Metadata;\nimport com.imagekit.api.models.files.metadata.MetadataGetParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n Metadata metadata = client.files().metadata().get("fileId");\n }\n}', + }, + php: { + method: 'files->metadata->get', + example: + "files->metadata->get('fileId');\n\nvar_dump($metadata);", + }, + python: { + method: 'files.metadata.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nmetadata = client.files.metadata.get(\n "fileId",\n)\nprint(metadata.video_codec)', + }, + ruby: { + method: 'files.metadata.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nmetadata = image_kit.files.metadata.get("fileId")\n\nputs(metadata)', + }, + typescript: { + method: 'client.files.metadata.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst metadata = await client.files.metadata.get('fileId');\n\nconsole.log(metadata.videoCodec);", + }, + }, + }, + { + name: 'getFromURL', + endpoint: '/v1/metadata', + httpMethod: 'get', + summary: 'Get metadata from remote URL', + description: + 'Get image EXIF, pHash, and other metadata from ImageKit.io powered remote URL using this API.\n', + stainlessPath: '(resource) files.metadata > (method) getFromURL', + qualified: 'client.files.metadata.getFromURL', + params: ['url: string;'], + response: + '{ audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: { exif?: object; gps?: object; image?: object; interoperability?: object; makernote?: object; thumbnail?: object; }; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }', + markdown: + "## getFromURL\n\n`client.files.metadata.getFromURL(url: string): { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: object; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }`\n\n**get** `/v1/metadata`\n\nGet image EXIF, pHash, and other metadata from ImageKit.io powered remote URL using this API.\n\n\n### Parameters\n\n- `url: string`\n Should be a valid file URL. It should be accessible using your ImageKit.io account.\n\n\n### Returns\n\n- `{ audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: { exif?: { ApertureValue?: number; ColorSpace?: number; CreateDate?: string; CustomRendered?: number; DateTimeOriginal?: string; ExifImageHeight?: number; ExifImageWidth?: number; ExifVersion?: string; ExposureCompensation?: number; ExposureMode?: number; ExposureProgram?: number; ExposureTime?: number; Flash?: number; FlashpixVersion?: string; FNumber?: number; FocalLength?: number; FocalPlaneResolutionUnit?: number; FocalPlaneXResolution?: number; FocalPlaneYResolution?: number; InteropOffset?: number; ISO?: number; MeteringMode?: number; SceneCaptureType?: number; ShutterSpeedValue?: number; SubSecTime?: string; WhiteBalance?: number; }; gps?: { GPSVersionID?: number[]; }; image?: { ExifOffset?: number; GPSInfo?: number; Make?: string; Model?: string; ModifyDate?: string; Orientation?: number; ResolutionUnit?: number; Software?: string; XResolution?: number; YCbCrPositioning?: number; YResolution?: number; }; interoperability?: { InteropIndex?: string; InteropVersion?: string; }; makernote?: object; thumbnail?: { Compression?: number; ResolutionUnit?: number; ThumbnailLength?: number; ThumbnailOffset?: number; XResolution?: number; YResolution?: number; }; }; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }`\n JSON object containing metadata.\n\n - `audioCodec?: string`\n - `bitRate?: number`\n - `density?: number`\n - `duration?: number`\n - `exif?: { exif?: { ApertureValue?: number; ColorSpace?: number; CreateDate?: string; CustomRendered?: number; DateTimeOriginal?: string; ExifImageHeight?: number; ExifImageWidth?: number; ExifVersion?: string; ExposureCompensation?: number; ExposureMode?: number; ExposureProgram?: number; ExposureTime?: number; Flash?: number; FlashpixVersion?: string; FNumber?: number; FocalLength?: number; FocalPlaneResolutionUnit?: number; FocalPlaneXResolution?: number; FocalPlaneYResolution?: number; InteropOffset?: number; ISO?: number; MeteringMode?: number; SceneCaptureType?: number; ShutterSpeedValue?: number; SubSecTime?: string; WhiteBalance?: number; }; gps?: { GPSVersionID?: number[]; }; image?: { ExifOffset?: number; GPSInfo?: number; Make?: string; Model?: string; ModifyDate?: string; Orientation?: number; ResolutionUnit?: number; Software?: string; XResolution?: number; YCbCrPositioning?: number; YResolution?: number; }; interoperability?: { InteropIndex?: string; InteropVersion?: string; }; makernote?: object; thumbnail?: { Compression?: number; ResolutionUnit?: number; ThumbnailLength?: number; ThumbnailOffset?: number; XResolution?: number; YResolution?: number; }; }`\n - `format?: string`\n - `hasColorProfile?: boolean`\n - `hasTransparency?: boolean`\n - `height?: number`\n - `pHash?: string`\n - `quality?: number`\n - `size?: number`\n - `videoCodec?: string`\n - `width?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst metadata = await client.files.metadata.getFromURL({ url: 'https://example.com' });\n\nconsole.log(metadata);\n```", + perLanguage: { + cli: { + method: 'metadata getFromURL', + example: + "imagekit files:metadata get-from-url \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --url https://example.com", + }, + csharp: { + method: 'Files.Metadata.GetFromUrl', + example: + 'MetadataGetFromUrlParams parameters = new() { Url = "https://example.com" };\n\nvar metadata = await client.Files.Metadata.GetFromUrl(parameters);\n\nConsole.WriteLine(metadata);', + }, + go: { + method: 'client.Files.Metadata.GetFromURL', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tmetadata, err := client.Files.Metadata.GetFromURL(context.TODO(), imagekit.FileMetadataGetFromURLParams{\n\t\tURL: "https://example.com",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", metadata.VideoCodec)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/metadata \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'files().metadata().getFromUrl', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.Metadata;\nimport com.imagekit.api.models.files.metadata.MetadataGetFromUrlParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n MetadataGetFromUrlParams params = MetadataGetFromUrlParams.builder()\n .url("https://example.com")\n .build();\n Metadata metadata = client.files().metadata().getFromUrl(params);\n }\n}', + }, + php: { + method: 'files->metadata->getFromURL', + example: + "files->metadata->getFromURL(url: 'https://example.com');\n\nvar_dump($metadata);", + }, + python: { + method: 'files.metadata.get_from_url', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nmetadata = client.files.metadata.get_from_url(\n url="https://example.com",\n)\nprint(metadata.video_codec)', + }, + ruby: { + method: 'files.metadata.get_from_url', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nmetadata = image_kit.files.metadata.get_from_url(url: "https://example.com")\n\nputs(metadata)', + }, + typescript: { + method: 'client.files.metadata.getFromURL', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst metadata = await client.files.metadata.getFromURL({ url: 'https://example.com' });\n\nconsole.log(metadata.videoCodec);", + }, + }, + }, + { + name: 'list', + endpoint: '/v1/saved-extensions', + httpMethod: 'get', + summary: 'List all saved extensions', + description: + 'This API returns an array of all saved extensions for your account. Saved extensions allow you to save complex extension configurations and reuse them by referencing them by ID in upload or update file APIs.\n', + stainlessPath: '(resource) savedExtensions > (method) list', + qualified: 'client.savedExtensions.list', + response: + '{ id?: string; config?: object | object | object | object; createdAt?: string; description?: string; name?: string; updatedAt?: string; }[]', + markdown: + "## list\n\n`client.savedExtensions.list(): object[]`\n\n**get** `/v1/saved-extensions`\n\nThis API returns an array of all saved extensions for your account. Saved extensions allow you to save complex extension configurations and reuse them by referencing them by ID in upload or update file APIs.\n\n\n### Returns\n\n- `{ id?: string; config?: object | object | object | object; createdAt?: string; description?: string; name?: string; updatedAt?: string; }[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst savedExtensions = await client.savedExtensions.list();\n\nconsole.log(savedExtensions);\n```", + perLanguage: { + cli: { + method: 'savedExtensions list', + example: + "imagekit saved-extensions list \\\n --private-key 'My Private Key' \\\n --password 'My Password'", + }, + csharp: { + method: 'SavedExtensions.List', + example: + 'SavedExtensionListParams parameters = new();\n\nvar savedExtensions = await client.SavedExtensions.List(parameters);\n\nConsole.WriteLine(savedExtensions);', + }, + go: { + method: 'client.SavedExtensions.List', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tsavedExtensions, err := client.SavedExtensions.List(context.TODO())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", savedExtensions)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/saved-extensions \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'savedExtensions().list', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.SavedExtension;\nimport com.imagekit.api.models.savedextensions.SavedExtensionListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n List savedExtensions = client.savedExtensions().list();\n }\n}', + }, + php: { + method: 'savedExtensions->list', + example: + "savedExtensions->list();\n\nvar_dump($savedExtensions);", + }, + python: { + method: 'saved_extensions.list', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nsaved_extensions = client.saved_extensions.list()\nprint(saved_extensions)', + }, + ruby: { + method: 'saved_extensions.list', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nsaved_extensions = image_kit.saved_extensions.list\n\nputs(saved_extensions)', + }, + typescript: { + method: 'client.savedExtensions.list', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst savedExtensions = await client.savedExtensions.list();\n\nconsole.log(savedExtensions);", + }, + }, + }, + { + name: 'create', + endpoint: '/v1/saved-extensions', + httpMethod: 'post', + summary: 'Create saved extension', + description: + 'This API creates a new saved extension. Saved extensions allow you to save complex extension configurations (like AI tasks) and reuse them by referencing the ID in upload or update file APIs.\n\n**Saved extension limit** \\\nYou can create a maximum of 100 saved extensions per account.\n', + stainlessPath: '(resource) savedExtensions > (method) create', + qualified: 'client.savedExtensions.create', + params: [ + "config: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; };", + 'description: string;', + 'name: string;', + ], + response: + "{ id?: string; config?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }; createdAt?: string; description?: string; name?: string; updatedAt?: string; }", + markdown: + "## create\n\n`client.savedExtensions.create(config: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }, description: string, name: string): { id?: string; config?: extension_config; createdAt?: string; description?: string; name?: string; updatedAt?: string; }`\n\n**post** `/v1/saved-extensions`\n\nThis API creates a new saved extension. Saved extensions allow you to save complex extension configurations (like AI tasks) and reuse them by referencing the ID in upload or update file APIs.\n\n**Saved extension limit** \\\nYou can create a maximum of 100 saved extensions per account.\n\n\n### Parameters\n\n- `config: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; }`\n Configuration object for an extension (base extensions only, not saved extension references).\n\n- `description: string`\n Description of what the saved extension does.\n\n- `name: string`\n Name of the saved extension.\n\n### Returns\n\n- `{ id?: string; config?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }; createdAt?: string; description?: string; name?: string; updatedAt?: string; }`\n Saved extension object containing extension configuration.\n\n - `id?: string`\n - `config?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; }`\n - `createdAt?: string`\n - `description?: string`\n - `name?: string`\n - `updatedAt?: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst savedExtension = await client.savedExtensions.create({\n config: { name: 'remove-bg' },\n description: 'Analyzes vehicle images for type, condition, and quality assessment',\n name: 'Car Quality Analysis',\n});\n\nconsole.log(savedExtension);\n```", + perLanguage: { + cli: { + method: 'savedExtensions create', + example: + "imagekit saved-extensions create \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --config '{name: remove-bg}' \\\n --description 'Analyzes vehicle images for type, condition, and quality assessment' \\\n --name 'Car Quality Analysis'", + }, + csharp: { + method: 'SavedExtensions.Create', + example: + 'SavedExtensionCreateParams parameters = new()\n{\n Config = new RemoveBg()\n {\n Options = new()\n {\n AddShadow = true,\n BgColor = "bg_color",\n BgImageUrl = "bg_image_url",\n Semitransparency = true,\n },\n },\n Description = "Analyzes vehicle images for type, condition, and quality assessment",\n Name = "Car Quality Analysis",\n};\n\nvar savedExtension = await client.SavedExtensions.Create(parameters);\n\nConsole.WriteLine(savedExtension);', + }, + go: { + method: 'client.SavedExtensions.New', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n\t"github.com/imagekit-developer/imagekit-go/shared"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tsavedExtension, err := client.SavedExtensions.New(context.TODO(), imagekit.SavedExtensionNewParams{\n\t\tConfig: shared.ExtensionConfigUnionParam{\n\t\t\tOfRemoveBg: &shared.ExtensionConfigRemoveBgParam{},\n\t\t},\n\t\tDescription: "Analyzes vehicle images for type, condition, and quality assessment",\n\t\tName: "Car Quality Analysis",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", savedExtension.ID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/saved-extensions \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "config": {\n "name": "remove-bg"\n },\n "description": "Analyzes vehicle images for type, condition, and quality assessment",\n "name": "Car Quality Analysis"\n }\'', + }, + java: { + method: 'savedExtensions().create', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.ExtensionConfig;\nimport com.imagekit.api.models.SavedExtension;\nimport com.imagekit.api.models.savedextensions.SavedExtensionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n SavedExtensionCreateParams params = SavedExtensionCreateParams.builder()\n .config(ExtensionConfig.RemoveBg.builder().build())\n .description("Analyzes vehicle images for type, condition, and quality assessment")\n .name("Car Quality Analysis")\n .build();\n SavedExtension savedExtension = client.savedExtensions().create(params);\n }\n}', + }, + php: { + method: 'savedExtensions->create', + example: + "savedExtensions->create(\n config: [\n 'name' => 'remove-bg',\n 'options' => [\n 'addShadow' => true,\n 'bgColor' => 'bg_color',\n 'bgImageURL' => 'bg_image_url',\n 'semitransparency' => true,\n ],\n ],\n description: 'Analyzes vehicle images for type, condition, and quality assessment',\n name: 'Car Quality Analysis',\n);\n\nvar_dump($savedExtension);", + }, + python: { + method: 'saved_extensions.create', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nsaved_extension = client.saved_extensions.create(\n config={\n "name": "remove-bg"\n },\n description="Analyzes vehicle images for type, condition, and quality assessment",\n name="Car Quality Analysis",\n)\nprint(saved_extension.id)', + }, + ruby: { + method: 'saved_extensions.create', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nsaved_extension = image_kit.saved_extensions.create(\n config: {name: :"remove-bg"},\n description: "Analyzes vehicle images for type, condition, and quality assessment",\n name: "Car Quality Analysis"\n)\n\nputs(saved_extension)', + }, + typescript: { + method: 'client.savedExtensions.create', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst savedExtension = await client.savedExtensions.create({\n config: { name: 'remove-bg' },\n description: 'Analyzes vehicle images for type, condition, and quality assessment',\n name: 'Car Quality Analysis',\n});\n\nconsole.log(savedExtension.id);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/saved-extensions/{id}', + httpMethod: 'get', + summary: 'Get saved extension details', + description: 'This API returns details of a specific saved extension by ID.\n', + stainlessPath: '(resource) savedExtensions > (method) get', + qualified: 'client.savedExtensions.get', + params: ['id: string;'], + response: + "{ id?: string; config?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }; createdAt?: string; description?: string; name?: string; updatedAt?: string; }", + markdown: + "## get\n\n`client.savedExtensions.get(id: string): { id?: string; config?: extension_config; createdAt?: string; description?: string; name?: string; updatedAt?: string; }`\n\n**get** `/v1/saved-extensions/{id}`\n\nThis API returns details of a specific saved extension by ID.\n\n\n### Parameters\n\n- `id: string`\n\n### Returns\n\n- `{ id?: string; config?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }; createdAt?: string; description?: string; name?: string; updatedAt?: string; }`\n Saved extension object containing extension configuration.\n\n - `id?: string`\n - `config?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; }`\n - `createdAt?: string`\n - `description?: string`\n - `name?: string`\n - `updatedAt?: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst savedExtension = await client.savedExtensions.get('id');\n\nconsole.log(savedExtension);\n```", + perLanguage: { + cli: { + method: 'savedExtensions get', + example: + "imagekit saved-extensions get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'SavedExtensions.Get', + example: + 'SavedExtensionGetParams parameters = new() { ID = "id" };\n\nvar savedExtension = await client.SavedExtensions.Get(parameters);\n\nConsole.WriteLine(savedExtension);', + }, + go: { + method: 'client.SavedExtensions.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tsavedExtension, err := client.SavedExtensions.Get(context.TODO(), "id")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", savedExtension.ID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/saved-extensions/$ID \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'savedExtensions().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.SavedExtension;\nimport com.imagekit.api.models.savedextensions.SavedExtensionGetParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n SavedExtension savedExtension = client.savedExtensions().get("id");\n }\n}', + }, + php: { + method: 'savedExtensions->get', + example: + "savedExtensions->get('id');\n\nvar_dump($savedExtension);", + }, + python: { + method: 'saved_extensions.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nsaved_extension = client.saved_extensions.get(\n "id",\n)\nprint(saved_extension.id)', + }, + ruby: { + method: 'saved_extensions.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nsaved_extension = image_kit.saved_extensions.get("id")\n\nputs(saved_extension)', + }, + typescript: { + method: 'client.savedExtensions.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst savedExtension = await client.savedExtensions.get('id');\n\nconsole.log(savedExtension.id);", + }, + }, + }, + { + name: 'update', + endpoint: '/v1/saved-extensions/{id}', + httpMethod: 'patch', + summary: 'Update saved extension', + description: + 'This API updates an existing saved extension. You can update the name, description, or config.\n', + stainlessPath: '(resource) savedExtensions > (method) update', + qualified: 'client.savedExtensions.update', + params: [ + 'id: string;', + "config?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; };", + 'description?: string;', + 'name?: string;', + ], + response: + "{ id?: string; config?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }; createdAt?: string; description?: string; name?: string; updatedAt?: string; }", + markdown: + "## update\n\n`client.savedExtensions.update(id: string, config?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }, description?: string, name?: string): { id?: string; config?: extension_config; createdAt?: string; description?: string; name?: string; updatedAt?: string; }`\n\n**patch** `/v1/saved-extensions/{id}`\n\nThis API updates an existing saved extension. You can update the name, description, or config.\n\n\n### Parameters\n\n- `id: string`\n\n- `config?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; }`\n Configuration object for an extension (base extensions only, not saved extension references).\n\n- `description?: string`\n Updated description of the saved extension.\n\n- `name?: string`\n Updated name of the saved extension.\n\n### Returns\n\n- `{ id?: string; config?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; }; createdAt?: string; description?: string; name?: string; updatedAt?: string; }`\n Saved extension object containing extension configuration.\n\n - `id?: string`\n - `config?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; }`\n - `createdAt?: string`\n - `description?: string`\n - `name?: string`\n - `updatedAt?: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst savedExtension = await client.savedExtensions.update('id');\n\nconsole.log(savedExtension);\n```", + perLanguage: { + cli: { + method: 'savedExtensions update', + example: + "imagekit saved-extensions update \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'SavedExtensions.Update', + example: + 'SavedExtensionUpdateParams parameters = new() { ID = "id" };\n\nvar savedExtension = await client.SavedExtensions.Update(parameters);\n\nConsole.WriteLine(savedExtension);', + }, + go: { + method: 'client.SavedExtensions.Update', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tsavedExtension, err := client.SavedExtensions.Update(\n\t\tcontext.TODO(),\n\t\t"id",\n\t\timagekit.SavedExtensionUpdateParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", savedExtension.ID)\n}\n', + }, + http: { + example: + "curl https://api.imagekit.io/v1/saved-extensions/$ID \\\n -X PATCH \\\n -H 'Content-Type: application/json' \\\n -u \"$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS\" \\\n -d '{}'", + }, + java: { + method: 'savedExtensions().update', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.SavedExtension;\nimport com.imagekit.api.models.savedextensions.SavedExtensionUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n SavedExtension savedExtension = client.savedExtensions().update("id");\n }\n}', + }, + php: { + method: 'savedExtensions->update', + example: + "savedExtensions->update(\n 'id',\n config: [\n 'name' => 'remove-bg',\n 'options' => [\n 'addShadow' => true,\n 'bgColor' => 'bg_color',\n 'bgImageURL' => 'bg_image_url',\n 'semitransparency' => true,\n ],\n ],\n description: 'x',\n name: 'x',\n);\n\nvar_dump($savedExtension);", + }, + python: { + method: 'saved_extensions.update', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nsaved_extension = client.saved_extensions.update(\n id="id",\n)\nprint(saved_extension.id)', + }, + ruby: { + method: 'saved_extensions.update', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nsaved_extension = image_kit.saved_extensions.update("id")\n\nputs(saved_extension)', + }, + typescript: { + method: 'client.savedExtensions.update', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst savedExtension = await client.savedExtensions.update('id');\n\nconsole.log(savedExtension.id);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/saved-extensions/{id}', + httpMethod: 'delete', + summary: 'Delete saved extension', + description: 'This API deletes a saved extension permanently.\n', + stainlessPath: '(resource) savedExtensions > (method) delete', + qualified: 'client.savedExtensions.delete', + params: ['id: string;'], + markdown: + "## delete\n\n`client.savedExtensions.delete(id: string): void`\n\n**delete** `/v1/saved-extensions/{id}`\n\nThis API deletes a saved extension permanently.\n\n\n### Parameters\n\n- `id: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nawait client.savedExtensions.delete('id')\n```", + perLanguage: { + cli: { + method: 'savedExtensions delete', + example: + "imagekit saved-extensions delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'SavedExtensions.Delete', + example: + 'SavedExtensionDeleteParams parameters = new() { ID = "id" };\n\nawait client.SavedExtensions.Delete(parameters);', + }, + go: { + method: 'client.SavedExtensions.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\terr := client.SavedExtensions.Delete(context.TODO(), "id")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/saved-extensions/$ID \\\n -X DELETE \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'savedExtensions().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.savedextensions.SavedExtensionDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n client.savedExtensions().delete("id");\n }\n}', + }, + php: { + method: 'savedExtensions->delete', + example: + "savedExtensions->delete('id');\n\nvar_dump($result);", + }, + python: { + method: 'saved_extensions.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nclient.saved_extensions.delete(\n "id",\n)', + }, + ruby: { + method: 'saved_extensions.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresult = image_kit.saved_extensions.delete("id")\n\nputs(result)', + }, + typescript: { + method: 'client.savedExtensions.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nawait client.savedExtensions.delete('id');", + }, + }, + }, + { + name: 'list', + endpoint: '/v1/files', + httpMethod: 'get', + summary: 'List and search assets', + description: + 'This API can list all the uploaded files and folders in your ImageKit.io media library. In addition, you can fine-tune your query by specifying various filters by generating a query string in a Lucene-like syntax and provide this generated string as the value of the `searchQuery`.\n', + stainlessPath: '(resource) assets > (method) list', + qualified: 'client.assets.list', + params: [ + "fileType?: 'all' | 'image' | 'non-image';", + 'limit?: number;', + 'path?: string;', + 'searchQuery?: string;', + 'skip?: number;', + 'sort?: string;', + "type?: 'file' | 'file-version' | 'folder' | 'all';", + ], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; } | { createdAt?: string; customMetadata?: object; folderId?: string; folderPath?: string; name?: string; type?: 'folder'; updatedAt?: string; }[]", + markdown: + "## list\n\n`client.assets.list(fileType?: 'all' | 'image' | 'non-image', limit?: number, path?: string, searchQuery?: string, skip?: number, sort?: string, type?: 'file' | 'file-version' | 'folder' | 'all'): object | object[]`\n\n**get** `/v1/files`\n\nThis API can list all the uploaded files and folders in your ImageKit.io media library. In addition, you can fine-tune your query by specifying various filters by generating a query string in a Lucene-like syntax and provide this generated string as the value of the `searchQuery`.\n\n\n### Parameters\n\n- `fileType?: 'all' | 'image' | 'non-image'`\n Filter results by file type.\n\n- `all` — include all file types \n- `image` — include only image files \n- `non-image` — include only non-image files (e.g., JS, CSS, video)\n\n- `limit?: number`\n The maximum number of results to return in response.\n\n\n- `path?: string`\n Folder path if you want to limit the search within a specific folder. For example, `/sales-banner/` will only search in folder sales-banner.\n\nNote : If your use case involves searching within a folder as well as its subfolders, you can use `path` parameter in `searchQuery` with appropriate operator.\nCheckout [Supported parameters](/docs/api-reference/digital-asset-management-dam/list-and-search-assets#supported-parameters) for more information.\n\n\n- `searchQuery?: string`\n Query string in a Lucene-like query language e.g. `createdAt > \"7d\"`.\n\nNote : When the searchQuery parameter is present, the following query parameters will have no effect on the result:\n\n1. `tags`\n2. `type`\n3. `name`\n\n[Learn more](/docs/api-reference/digital-asset-management-dam/list-and-search-assets#advanced-search-queries) from examples.\n\n\n- `skip?: number`\n The number of results to skip before returning results.\n\n\n- `sort?: string`\n Sort the results by one of the supported fields in ascending or descending order.\n\n- `type?: 'file' | 'file-version' | 'folder' | 'all'`\n Filter results by asset type.\n\n- `file` — returns only files \n- `file-version` — returns specific file versions \n- `folder` — returns only folders \n- `all` — returns both files and folders (excludes `file-version`)\n\n### Returns\n\n- `{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; createdAt?: string; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; fileId?: string; filePath?: string; fileType?: string; hasAlpha?: boolean; height?: number; isPrivateFile?: boolean; isPublished?: boolean; mime?: string; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnail?: string; type?: 'file' | 'file-version'; updatedAt?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; } | { createdAt?: string; customMetadata?: object; folderId?: string; folderPath?: string; name?: string; type?: 'folder'; updatedAt?: string; }[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst assets = await client.assets.list();\n\nconsole.log(assets);\n```", + perLanguage: { + cli: { + method: 'assets list', + example: "imagekit assets list \\\n --private-key 'My Private Key' \\\n --password 'My Password'", + }, + csharp: { + method: 'Assets.List', + example: + 'AssetListParams parameters = new();\n\nvar assets = await client.Assets.List(parameters);\n\nConsole.WriteLine(assets);', + }, + go: { + method: 'client.Assets.List', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tassets, err := client.Assets.List(context.TODO(), imagekit.AssetListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", assets)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'assets().list', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.assets.AssetListParams;\nimport com.imagekit.api.models.assets.AssetListResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n List assets = client.assets().list();\n }\n}', + }, + php: { + method: 'assets->list', + example: + "assets->list(\n fileType: 'all',\n limit: 1,\n path: 'path',\n searchQuery: 'searchQuery',\n skip: 0,\n sort: 'ASC_NAME',\n type: 'file',\n);\n\nvar_dump($assets);", + }, + python: { + method: 'assets.list', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nassets = client.assets.list()\nprint(assets)', + }, + ruby: { + method: 'assets.list', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nassets = image_kit.assets.list\n\nputs(assets)', + }, + typescript: { + method: 'client.assets.list', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst assets = await client.assets.list();\n\nconsole.log(assets);", + }, + }, + }, + { + name: 'create', + endpoint: '/v1/files/purge', + httpMethod: 'post', + summary: 'Purge cache', + description: + "This API will purge CDN cache and ImageKit.io's internal cache for a file. Note: Purge cache is an asynchronous process and it may take some time to reflect the changes.\n", + stainlessPath: '(resource) cache.invalidation > (method) create', + qualified: 'client.cache.invalidation.create', + params: ['url: string;'], + response: '{ requestId?: string; }', + markdown: + "## create\n\n`client.cache.invalidation.create(url: string): { requestId?: string; }`\n\n**post** `/v1/files/purge`\n\nThis API will purge CDN cache and ImageKit.io's internal cache for a file. Note: Purge cache is an asynchronous process and it may take some time to reflect the changes.\n\n\n### Parameters\n\n- `url: string`\n The full URL of the file to be purged.\n\n\n### Returns\n\n- `{ requestId?: string; }`\n\n - `requestId?: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst invalidation = await client.cache.invalidation.create({ url: 'https://ik.imagekit.io/your_imagekit_id/default-image.jpg' });\n\nconsole.log(invalidation);\n```", + perLanguage: { + cli: { + method: 'invalidation create', + example: + "imagekit cache:invalidation create \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --url https://ik.imagekit.io/your_imagekit_id/default-image.jpg", + }, + csharp: { + method: 'Cache.Invalidation.Create', + example: + 'InvalidationCreateParams parameters = new()\n{\n Url = "https://ik.imagekit.io/your_imagekit_id/default-image.jpg"\n};\n\nvar invalidation = await client.Cache.Invalidation.Create(parameters);\n\nConsole.WriteLine(invalidation);', + }, + go: { + method: 'client.Cache.Invalidation.New', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tinvalidation, err := client.Cache.Invalidation.New(context.TODO(), imagekit.CacheInvalidationNewParams{\n\t\tURL: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", invalidation.RequestID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/purge \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "url": "https://ik.imagekit.io/your_imagekit_id/default-image.jpg"\n }\'', + }, + java: { + method: 'cache().invalidation().create', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.cache.invalidation.InvalidationCreateParams;\nimport com.imagekit.api.models.cache.invalidation.InvalidationCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n InvalidationCreateParams params = InvalidationCreateParams.builder()\n .url("https://ik.imagekit.io/your_imagekit_id/default-image.jpg")\n .build();\n InvalidationCreateResponse invalidation = client.cache().invalidation().create(params);\n }\n}', + }, + php: { + method: 'cache->invalidation->create', + example: + "cache->invalidation->create(\n url: 'https://ik.imagekit.io/your_imagekit_id/default-image.jpg'\n);\n\nvar_dump($invalidation);", + }, + python: { + method: 'cache.invalidation.create', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\ninvalidation = client.cache.invalidation.create(\n url="https://ik.imagekit.io/your_imagekit_id/default-image.jpg",\n)\nprint(invalidation.request_id)', + }, + ruby: { + method: 'cache.invalidation.create', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\ninvalidation = image_kit.cache.invalidation.create(url: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg")\n\nputs(invalidation)', + }, + typescript: { + method: 'client.cache.invalidation.create', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst invalidation = await client.cache.invalidation.create({\n url: 'https://ik.imagekit.io/your_imagekit_id/default-image.jpg',\n});\n\nconsole.log(invalidation.requestId);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/files/purge/{requestId}', + httpMethod: 'get', + summary: 'Get purge status', + description: 'This API returns the status of a purge cache request.\n', + stainlessPath: '(resource) cache.invalidation > (method) get', + qualified: 'client.cache.invalidation.get', + params: ['requestId: string;'], + response: "{ status?: 'Pending' | 'Completed'; }", + markdown: + "## get\n\n`client.cache.invalidation.get(requestId: string): { status?: 'Pending' | 'Completed'; }`\n\n**get** `/v1/files/purge/{requestId}`\n\nThis API returns the status of a purge cache request.\n\n\n### Parameters\n\n- `requestId: string`\n\n### Returns\n\n- `{ status?: 'Pending' | 'Completed'; }`\n\n - `status?: 'Pending' | 'Completed'`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst invalidation = await client.cache.invalidation.get('requestId');\n\nconsole.log(invalidation);\n```", + perLanguage: { + cli: { + method: 'invalidation get', + example: + "imagekit cache:invalidation get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --request-id requestId", + }, + csharp: { + method: 'Cache.Invalidation.Get', + example: + 'InvalidationGetParams parameters = new() { RequestID = "requestId" };\n\nvar invalidation = await client.Cache.Invalidation.Get(parameters);\n\nConsole.WriteLine(invalidation);', + }, + go: { + method: 'client.Cache.Invalidation.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tinvalidation, err := client.Cache.Invalidation.Get(context.TODO(), "requestId")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", invalidation.Status)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/files/purge/$REQUEST_ID \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'cache().invalidation().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.cache.invalidation.InvalidationGetParams;\nimport com.imagekit.api.models.cache.invalidation.InvalidationGetResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n InvalidationGetResponse invalidation = client.cache().invalidation().get("requestId");\n }\n}', + }, + php: { + method: 'cache->invalidation->get', + example: + "cache->invalidation->get('requestId');\n\nvar_dump($invalidation);", + }, + python: { + method: 'cache.invalidation.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\ninvalidation = client.cache.invalidation.get(\n "requestId",\n)\nprint(invalidation.status)', + }, + ruby: { + method: 'cache.invalidation.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\ninvalidation = image_kit.cache.invalidation.get("requestId")\n\nputs(invalidation)', + }, + typescript: { + method: 'client.cache.invalidation.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst invalidation = await client.cache.invalidation.get('requestId');\n\nconsole.log(invalidation.status);", + }, + }, + }, + { + name: 'create', + endpoint: '/v1/folder', + httpMethod: 'post', + summary: 'Create folder', + description: + 'This will create a new folder. You can specify the folder name and location of the parent folder where this new folder should be created.\n', + stainlessPath: '(resource) folders > (method) create', + qualified: 'client.folders.create', + params: ['folderName: string;', 'parentFolderPath: string;'], + response: '{ }', + markdown: + "## create\n\n`client.folders.create(folderName: string, parentFolderPath: string): { }`\n\n**post** `/v1/folder`\n\nThis will create a new folder. You can specify the folder name and location of the parent folder where this new folder should be created.\n\n\n### Parameters\n\n- `folderName: string`\n The folder will be created with this name. \n\nAll characters except alphabets and numbers (inclusive of unicode letters, marks, and numerals in other languages) will be replaced by an underscore i.e. `_`.\n\n\n- `parentFolderPath: string`\n The folder where the new folder should be created, for root use `/` else the path e.g. `containing/folder/`.\n\nNote: If any folder(s) is not present in the parentFolderPath parameter, it will be automatically created. For example, if you pass `/product/images/summer`, then `product`, `images`, and `summer` folders will be created if they don't already exist.\n\n\n### Returns\n\n- `{ }`\n\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst folder = await client.folders.create({ folderName: 'summer', parentFolderPath: '/product/images/' });\n\nconsole.log(folder);\n```", + perLanguage: { + cli: { + method: 'folders create', + example: + "imagekit folders create \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --folder-name summer \\\n --parent-folder-path /product/images/", + }, + csharp: { + method: 'Folders.Create', + example: + 'FolderCreateParams parameters = new()\n{\n FolderName = "summer",\n ParentFolderPath = "/product/images/",\n};\n\nvar folder = await client.Folders.Create(parameters);\n\nConsole.WriteLine(folder);', + }, + go: { + method: 'client.Folders.New', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tfolder, err := client.Folders.New(context.TODO(), imagekit.FolderNewParams{\n\t\tFolderName: "summer",\n\t\tParentFolderPath: "/product/images/",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", folder)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/folder \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "folderName": "summer",\n "parentFolderPath": "/product/images/"\n }\'', + }, + java: { + method: 'folders().create', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.folders.FolderCreateParams;\nimport com.imagekit.api.models.folders.FolderCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FolderCreateParams params = FolderCreateParams.builder()\n .folderName("summer")\n .parentFolderPath("/product/images/")\n .build();\n FolderCreateResponse folder = client.folders().create(params);\n }\n}', + }, + php: { + method: 'folders->create', + example: + "folders->create(\n folderName: 'summer', parentFolderPath: '/product/images/'\n);\n\nvar_dump($folder);", + }, + python: { + method: 'folders.create', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nfolder = client.folders.create(\n folder_name="summer",\n parent_folder_path="/product/images/",\n)\nprint(folder)', + }, + ruby: { + method: 'folders.create', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nfolder = image_kit.folders.create(folder_name: "summer", parent_folder_path: "/product/images/")\n\nputs(folder)', + }, + typescript: { + method: 'client.folders.create', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst folder = await client.folders.create({\n folderName: 'summer',\n parentFolderPath: '/product/images/',\n});\n\nconsole.log(folder);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/folder', + httpMethod: 'delete', + summary: 'Delete folder', + description: + 'This will delete a folder and all its contents permanently. The API returns an empty response.\n', + stainlessPath: '(resource) folders > (method) delete', + qualified: 'client.folders.delete', + params: ['folderPath: string;'], + response: '{ }', + markdown: + "## delete\n\n`client.folders.delete(folderPath: string): { }`\n\n**delete** `/v1/folder`\n\nThis will delete a folder and all its contents permanently. The API returns an empty response.\n\n\n### Parameters\n\n- `folderPath: string`\n Full path to the folder you want to delete. For example `/folder/to/delete/`.\n\n\n### Returns\n\n- `{ }`\n\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst folder = await client.folders.delete({ folderPath: '/folder/to/delete/' });\n\nconsole.log(folder);\n```", + perLanguage: { + cli: { + method: 'folders delete', + example: + "imagekit folders delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --folder-path /folder/to/delete/", + }, + csharp: { + method: 'Folders.Delete', + example: + 'FolderDeleteParams parameters = new() { FolderPath = "/folder/to/delete/" };\n\nvar folder = await client.Folders.Delete(parameters);\n\nConsole.WriteLine(folder);', + }, + go: { + method: 'client.Folders.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tfolder, err := client.Folders.Delete(context.TODO(), imagekit.FolderDeleteParams{\n\t\tFolderPath: "/folder/to/delete/",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", folder)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/folder \\\n -X DELETE \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'folders().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.folders.FolderDeleteParams;\nimport com.imagekit.api.models.folders.FolderDeleteResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FolderDeleteParams params = FolderDeleteParams.builder()\n .folderPath("/folder/to/delete/")\n .build();\n FolderDeleteResponse folder = client.folders().delete(params);\n }\n}', + }, + php: { + method: 'folders->delete', + example: + "folders->delete(folderPath: '/folder/to/delete/');\n\nvar_dump($folder);", + }, + python: { + method: 'folders.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nfolder = client.folders.delete(\n folder_path="/folder/to/delete/",\n)\nprint(folder)', + }, + ruby: { + method: 'folders.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nfolder = image_kit.folders.delete(folder_path: "/folder/to/delete/")\n\nputs(folder)', + }, + typescript: { + method: 'client.folders.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst folder = await client.folders.delete({ folderPath: '/folder/to/delete/' });\n\nconsole.log(folder);", + }, + }, + }, + { + name: 'copy', + endpoint: '/v1/bulkJobs/copyFolder', + httpMethod: 'post', + summary: 'Copy folder', + description: + 'This will copy one folder into another. The selected folder, its nested folders, files, and their versions (in `includeVersions` is set to true) are copied in this operation. Note: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file version history.\n', + stainlessPath: '(resource) folders > (method) copy', + qualified: 'client.folders.copy', + params: ['destinationPath: string;', 'sourceFolderPath: string;', 'includeVersions?: boolean;'], + response: '{ jobId: string; }', + markdown: + "## copy\n\n`client.folders.copy(destinationPath: string, sourceFolderPath: string, includeVersions?: boolean): { jobId: string; }`\n\n**post** `/v1/bulkJobs/copyFolder`\n\nThis will copy one folder into another. The selected folder, its nested folders, files, and their versions (in `includeVersions` is set to true) are copied in this operation. Note: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file version history.\n\n\n### Parameters\n\n- `destinationPath: string`\n Full path to the destination folder where you want to copy the source folder into.\n\n\n- `sourceFolderPath: string`\n The full path to the source folder you want to copy.\n\n\n- `includeVersions?: boolean`\n Option to copy all versions of files that are nested inside the selected folder. By default, only the current version of each file will be copied. When set to true, all versions of each file will be copied. Default value - `false`.\n\n\n### Returns\n\n- `{ jobId: string; }`\n Job submitted successfully. A `jobId` will be returned.\n\n - `jobId: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.folders.copy({ destinationPath: '/path/of/destination/folder', sourceFolderPath: '/path/of/source/folder' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'folders copy', + example: + "imagekit folders copy \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --destination-path /path/of/destination/folder \\\n --source-folder-path /path/of/source/folder", + }, + csharp: { + method: 'Folders.Copy', + example: + 'FolderCopyParams parameters = new()\n{\n DestinationPath = "/path/of/destination/folder",\n SourceFolderPath = "/path/of/source/folder",\n};\n\nvar response = await client.Folders.Copy(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Folders.Copy', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Folders.Copy(context.TODO(), imagekit.FolderCopyParams{\n\t\tDestinationPath: "/path/of/destination/folder",\n\t\tSourceFolderPath: "/path/of/source/folder",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.JobID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/bulkJobs/copyFolder \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "destinationPath": "/path/of/destination/folder",\n "sourceFolderPath": "/path/of/source/folder",\n "includeVersions": true\n }\'', + }, + java: { + method: 'folders().copy', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.folders.FolderCopyParams;\nimport com.imagekit.api.models.folders.FolderCopyResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FolderCopyParams params = FolderCopyParams.builder()\n .destinationPath("/path/of/destination/folder")\n .sourceFolderPath("/path/of/source/folder")\n .build();\n FolderCopyResponse response = client.folders().copy(params);\n }\n}', + }, + php: { + method: 'folders->copy', + example: + "folders->copy(\n destinationPath: '/path/of/destination/folder',\n sourceFolderPath: '/path/of/source/folder',\n includeVersions: true,\n);\n\nvar_dump($response);", + }, + python: { + method: 'folders.copy', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.folders.copy(\n destination_path="/path/of/destination/folder",\n source_folder_path="/path/of/source/folder",\n)\nprint(response.job_id)', + }, + ruby: { + method: 'folders.copy', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.folders.copy(\n destination_path: "/path/of/destination/folder",\n source_folder_path: "/path/of/source/folder"\n)\n\nputs(response)', + }, + typescript: { + method: 'client.folders.copy', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.folders.copy({\n destinationPath: '/path/of/destination/folder',\n sourceFolderPath: '/path/of/source/folder',\n});\n\nconsole.log(response.jobId);", + }, + }, + }, + { + name: 'move', + endpoint: '/v1/bulkJobs/moveFolder', + httpMethod: 'post', + summary: 'Move folder', + description: + 'This will move one folder into another. The selected folder, its nested folders, files, and their versions are moved in this operation. Note: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file version history.\n', + stainlessPath: '(resource) folders > (method) move', + qualified: 'client.folders.move', + params: ['destinationPath: string;', 'sourceFolderPath: string;'], + response: '{ jobId: string; }', + markdown: + "## move\n\n`client.folders.move(destinationPath: string, sourceFolderPath: string): { jobId: string; }`\n\n**post** `/v1/bulkJobs/moveFolder`\n\nThis will move one folder into another. The selected folder, its nested folders, files, and their versions are moved in this operation. Note: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file version history.\n\n\n### Parameters\n\n- `destinationPath: string`\n Full path to the destination folder where you want to move the source folder into.\n\n\n- `sourceFolderPath: string`\n The full path to the source folder you want to move.\n\n\n### Returns\n\n- `{ jobId: string; }`\n Job submitted successfully. A `jobId` will be returned.\n\n - `jobId: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.folders.move({ destinationPath: '/path/of/destination/folder', sourceFolderPath: '/path/of/source/folder' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'folders move', + example: + "imagekit folders move \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --destination-path /path/of/destination/folder \\\n --source-folder-path /path/of/source/folder", + }, + csharp: { + method: 'Folders.Move', + example: + 'FolderMoveParams parameters = new()\n{\n DestinationPath = "/path/of/destination/folder",\n SourceFolderPath = "/path/of/source/folder",\n};\n\nvar response = await client.Folders.Move(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Folders.Move', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Folders.Move(context.TODO(), imagekit.FolderMoveParams{\n\t\tDestinationPath: "/path/of/destination/folder",\n\t\tSourceFolderPath: "/path/of/source/folder",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.JobID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/bulkJobs/moveFolder \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "destinationPath": "/path/of/destination/folder",\n "sourceFolderPath": "/path/of/source/folder"\n }\'', + }, + java: { + method: 'folders().move', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.folders.FolderMoveParams;\nimport com.imagekit.api.models.folders.FolderMoveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FolderMoveParams params = FolderMoveParams.builder()\n .destinationPath("/path/of/destination/folder")\n .sourceFolderPath("/path/of/source/folder")\n .build();\n FolderMoveResponse response = client.folders().move(params);\n }\n}', + }, + php: { + method: 'folders->move', + example: + "folders->move(\n destinationPath: '/path/of/destination/folder',\n sourceFolderPath: '/path/of/source/folder',\n);\n\nvar_dump($response);", + }, + python: { + method: 'folders.move', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.folders.move(\n destination_path="/path/of/destination/folder",\n source_folder_path="/path/of/source/folder",\n)\nprint(response.job_id)', + }, + ruby: { + method: 'folders.move', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.folders.move(\n destination_path: "/path/of/destination/folder",\n source_folder_path: "/path/of/source/folder"\n)\n\nputs(response)', + }, + typescript: { + method: 'client.folders.move', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.folders.move({\n destinationPath: '/path/of/destination/folder',\n sourceFolderPath: '/path/of/source/folder',\n});\n\nconsole.log(response.jobId);", + }, + }, + }, + { + name: 'rename', + endpoint: '/v1/bulkJobs/renameFolder', + httpMethod: 'post', + summary: 'Rename folder', + description: + 'This API allows you to rename an existing folder. The folder and all its nested assets and sub-folders will remain unchanged, but their paths will be updated to reflect the new folder name.\n', + stainlessPath: '(resource) folders > (method) rename', + qualified: 'client.folders.rename', + params: ['folderPath: string;', 'newFolderName: string;', 'purgeCache?: boolean;'], + response: '{ jobId: string; }', + markdown: + "## rename\n\n`client.folders.rename(folderPath: string, newFolderName: string, purgeCache?: boolean): { jobId: string; }`\n\n**post** `/v1/bulkJobs/renameFolder`\n\nThis API allows you to rename an existing folder. The folder and all its nested assets and sub-folders will remain unchanged, but their paths will be updated to reflect the new folder name.\n\n\n### Parameters\n\n- `folderPath: string`\n The full path to the folder you want to rename.\n\n\n- `newFolderName: string`\n The new name for the folder.\n\nAll characters except alphabets and numbers (inclusive of unicode letters, marks, and numerals in other languages) and `-` will be replaced by an underscore i.e. `_`.\n\n\n- `purgeCache?: boolean`\n Option to purge cache for the old nested files and their versions' URLs.\n\nWhen set to true, it will internally issue a purge cache request on CDN to remove the cached content of the old nested files and their versions. There will only be one purge request for all the nested files, which will be counted against your monthly purge quota.\n\nNote: A purge cache request will be issued against `https://ik.imagekit.io/old/folder/path*` (with a wildcard at the end). This will remove all nested files, their versions' URLs, and any transformations made using query parameters on these files or their versions. However, the cache for file transformations made using path parameters will persist. You can purge them using the purge API. For more details, refer to the purge API documentation.\n\nDefault value - `false`\n\n\n### Returns\n\n- `{ jobId: string; }`\n Job submitted successfully. A `jobId` will be returned.\n\n - `jobId: string`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.folders.rename({ folderPath: '/path/of/folder', newFolderName: 'new-folder-name' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'folders rename', + example: + "imagekit folders rename \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --folder-path /path/of/folder \\\n --new-folder-name new-folder-name", + }, + csharp: { + method: 'Folders.Rename', + example: + 'FolderRenameParams parameters = new()\n{\n FolderPath = "/path/of/folder",\n NewFolderName = "new-folder-name",\n};\n\nvar response = await client.Folders.Rename(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Folders.Rename', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Folders.Rename(context.TODO(), imagekit.FolderRenameParams{\n\t\tFolderPath: "/path/of/folder",\n\t\tNewFolderName: "new-folder-name",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.JobID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/bulkJobs/renameFolder \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "folderPath": "/path/of/folder",\n "newFolderName": "new-folder-name",\n "purgeCache": true\n }\'', + }, + java: { + method: 'folders().rename', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.folders.FolderRenameParams;\nimport com.imagekit.api.models.folders.FolderRenameResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FolderRenameParams params = FolderRenameParams.builder()\n .folderPath("/path/of/folder")\n .newFolderName("new-folder-name")\n .build();\n FolderRenameResponse response = client.folders().rename(params);\n }\n}', + }, + php: { + method: 'folders->rename', + example: + "folders->rename(\n folderPath: '/path/of/folder',\n newFolderName: 'new-folder-name',\n purgeCache: true,\n);\n\nvar_dump($response);", + }, + python: { + method: 'folders.rename', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.folders.rename(\n folder_path="/path/of/folder",\n new_folder_name="new-folder-name",\n)\nprint(response.job_id)', + }, + ruby: { + method: 'folders.rename', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.folders.rename(folder_path: "/path/of/folder", new_folder_name: "new-folder-name")\n\nputs(response)', + }, + typescript: { + method: 'client.folders.rename', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.folders.rename({\n folderPath: '/path/of/folder',\n newFolderName: 'new-folder-name',\n});\n\nconsole.log(response.jobId);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/bulkJobs/{jobId}', + httpMethod: 'get', + summary: 'Bulk job status', + description: 'This API returns the status of a bulk job like copy and move folder operations.\n', + stainlessPath: '(resource) folders.job > (method) get', + qualified: 'client.folders.job.get', + params: ['jobId: string;'], + response: + "{ jobId?: string; purgeRequestId?: string; status?: 'Pending' | 'Completed'; type?: 'COPY_FOLDER' | 'MOVE_FOLDER' | 'RENAME_FOLDER'; }", + markdown: + "## get\n\n`client.folders.job.get(jobId: string): { jobId?: string; purgeRequestId?: string; status?: 'Pending' | 'Completed'; type?: 'COPY_FOLDER' | 'MOVE_FOLDER' | 'RENAME_FOLDER'; }`\n\n**get** `/v1/bulkJobs/{jobId}`\n\nThis API returns the status of a bulk job like copy and move folder operations.\n\n\n### Parameters\n\n- `jobId: string`\n\n### Returns\n\n- `{ jobId?: string; purgeRequestId?: string; status?: 'Pending' | 'Completed'; type?: 'COPY_FOLDER' | 'MOVE_FOLDER' | 'RENAME_FOLDER'; }`\n\n - `jobId?: string`\n - `purgeRequestId?: string`\n - `status?: 'Pending' | 'Completed'`\n - `type?: 'COPY_FOLDER' | 'MOVE_FOLDER' | 'RENAME_FOLDER'`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst job = await client.folders.job.get('jobId');\n\nconsole.log(job);\n```", + perLanguage: { + cli: { + method: 'job get', + example: + "imagekit folders:job get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --job-id jobId", + }, + csharp: { + method: 'Folders.Job.Get', + example: + 'JobGetParams parameters = new() { JobID = "jobId" };\n\nvar job = await client.Folders.Job.Get(parameters);\n\nConsole.WriteLine(job);', + }, + go: { + method: 'client.Folders.Job.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tjob, err := client.Folders.Job.Get(context.TODO(), "jobId")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", job.JobID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/bulkJobs/$JOB_ID \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'folders().job().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.folders.job.JobGetParams;\nimport com.imagekit.api.models.folders.job.JobGetResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n JobGetResponse job = client.folders().job().get("jobId");\n }\n}', + }, + php: { + method: 'folders->job->get', + example: + "folders->job->get('jobId');\n\nvar_dump($job);", + }, + python: { + method: 'folders.job.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\njob = client.folders.job.get(\n "jobId",\n)\nprint(job.job_id)', + }, + ruby: { + method: 'folders.job.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\njob = image_kit.folders.job.get("jobId")\n\nputs(job)', + }, + typescript: { + method: 'client.folders.job.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst job = await client.folders.job.get('jobId');\n\nconsole.log(job.jobId);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/accounts/usage', + httpMethod: 'get', + summary: 'Get account usage information', + description: + 'Get the account usage information between two dates. Note that the API response includes data from the start date while excluding data from the end date. In other words, the data covers the period starting from the specified start date up to, but not including, the end date.\n', + stainlessPath: '(resource) accounts.usage > (method) get', + qualified: 'client.accounts.usage.get', + params: ['endDate: string;', 'startDate: string;'], + response: + '{ bandwidthBytes?: number; extensionUnitsCount?: number; mediaLibraryStorageBytes?: number; originalCacheStorageBytes?: number; videoProcessingUnitsCount?: number; }', + markdown: + "## get\n\n`client.accounts.usage.get(endDate: string, startDate: string): { bandwidthBytes?: number; extensionUnitsCount?: number; mediaLibraryStorageBytes?: number; originalCacheStorageBytes?: number; videoProcessingUnitsCount?: number; }`\n\n**get** `/v1/accounts/usage`\n\nGet the account usage information between two dates. Note that the API response includes data from the start date while excluding data from the end date. In other words, the data covers the period starting from the specified start date up to, but not including, the end date.\n\n\n### Parameters\n\n- `endDate: string`\n Specify a `endDate` in `YYYY-MM-DD` format. It should be after the `startDate`. The difference between `startDate` and `endDate` should be less than 90 days.\n\n- `startDate: string`\n Specify a `startDate` in `YYYY-MM-DD` format. It should be before the `endDate`. The difference between `startDate` and `endDate` should be less than 90 days.\n\n### Returns\n\n- `{ bandwidthBytes?: number; extensionUnitsCount?: number; mediaLibraryStorageBytes?: number; originalCacheStorageBytes?: number; videoProcessingUnitsCount?: number; }`\n\n - `bandwidthBytes?: number`\n - `extensionUnitsCount?: number`\n - `mediaLibraryStorageBytes?: number`\n - `originalCacheStorageBytes?: number`\n - `videoProcessingUnitsCount?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst usage = await client.accounts.usage.get({ endDate: '2019-12-27', startDate: '2019-12-27' });\n\nconsole.log(usage);\n```", + perLanguage: { + cli: { + method: 'usage get', + example: + "imagekit accounts:usage get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --end-date \"'2019-12-27'\" \\\n --start-date \"'2019-12-27'\"", + }, + csharp: { + method: 'Accounts.Usage.Get', + example: + 'UsageGetParams parameters = new()\n{\n EndDate = "2019-12-27",\n StartDate = "2019-12-27",\n};\n\nvar usage = await client.Accounts.Usage.Get(parameters);\n\nConsole.WriteLine(usage);', + }, + go: { + method: 'client.Accounts.Usage.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\t"time"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tusage, err := client.Accounts.Usage.Get(context.TODO(), imagekit.AccountUsageGetParams{\n\t\tEndDate: time.Now(),\n\t\tStartDate: time.Now(),\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", usage.BandwidthBytes)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/usage \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'accounts().usage().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.usage.UsageGetParams;\nimport com.imagekit.api.models.accounts.usage.UsageGetResponse;\nimport java.time.LocalDate;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n UsageGetParams params = UsageGetParams.builder()\n .endDate(LocalDate.parse("2019-12-27"))\n .startDate(LocalDate.parse("2019-12-27"))\n .build();\n UsageGetResponse usage = client.accounts().usage().get(params);\n }\n}', + }, + php: { + method: 'accounts->usage->get', + example: + "accounts->usage->get(\n endDate: '2019-12-27', startDate: '2019-12-27'\n);\n\nvar_dump($usage);", + }, + python: { + method: 'accounts.usage.get', + example: + 'import os\nfrom datetime import date\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nusage = client.accounts.usage.get(\n end_date=date.fromisoformat("2019-12-27"),\n start_date=date.fromisoformat("2019-12-27"),\n)\nprint(usage.bandwidth_bytes)', + }, + ruby: { + method: 'accounts.usage.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nusage = image_kit.accounts.usage.get(end_date: "2019-12-27", start_date: "2019-12-27")\n\nputs(usage)', + }, + typescript: { + method: 'client.accounts.usage.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst usage = await client.accounts.usage.get({ endDate: '2019-12-27', startDate: '2019-12-27' });\n\nconsole.log(usage.bandwidthBytes);", + }, + }, + }, + { + name: 'list', + endpoint: '/v1/accounts/origins', + httpMethod: 'get', + summary: 'List origins', + description: + '**Note:** This API is currently in beta. \nReturns an array of all configured origins for the current account.\n', + stainlessPath: '(resource) accounts.origins > (method) list', + qualified: 'client.accounts.origins.list', + response: 'object | object | object | object | object | object | object | object[]', + markdown: + "## list\n\n`client.accounts.origins.list(): object | object | object | object | object | object | object | object[]`\n\n**get** `/v1/accounts/origins`\n\n**Note:** This API is currently in beta. \nReturns an array of all configured origins for the current account.\n\n\n### Returns\n\n- `{ id: string; bucket: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'S3'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; endpoint: string; includeCanonicalHeader: boolean; name: string; prefix: string; s3ForcePathStyle: boolean; type: 'S3_COMPATIBLE'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'CLOUDINARY_BACKUP'; baseUrlForCanonicalHeader?: string; } | { id: string; baseUrl: string; forwardHostHeaderToOrigin: boolean; includeCanonicalHeader: boolean; name: string; type: 'WEB_FOLDER'; baseUrlForCanonicalHeader?: string; } | { id: string; includeCanonicalHeader: boolean; name: string; type: 'WEB_PROXY'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; clientEmail: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'GCS'; baseUrlForCanonicalHeader?: string; } | { id: string; accountName: string; container: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'AZURE_BLOB'; baseUrlForCanonicalHeader?: string; } | { id: string; baseUrl: string; includeCanonicalHeader: boolean; name: string; type: 'AKENEO_PIM'; baseUrlForCanonicalHeader?: string; }[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst originResponses = await client.accounts.origins.list();\n\nconsole.log(originResponses);\n```", + perLanguage: { + cli: { + method: 'origins list', + example: + "imagekit accounts:origins list \\\n --private-key 'My Private Key' \\\n --password 'My Password'", + }, + csharp: { + method: 'Accounts.Origins.List', + example: + 'OriginListParams parameters = new();\n\nvar originResponses = await client.Accounts.Origins.List(parameters);\n\nConsole.WriteLine(originResponses);', + }, + go: { + method: 'client.Accounts.Origins.List', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\toriginResponses, err := client.Accounts.Origins.List(context.TODO())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", originResponses)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/origins \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'accounts().origins().list', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.origins.OriginListParams;\nimport com.imagekit.api.models.accounts.origins.OriginResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n List originResponses = client.accounts().origins().list();\n }\n}', + }, + php: { + method: 'accounts->origins->list', + example: + "accounts->origins->list();\n\nvar_dump($originResponses);", + }, + python: { + method: 'accounts.origins.list', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\norigin_responses = client.accounts.origins.list()\nprint(origin_responses)', + }, + ruby: { + method: 'accounts.origins.list', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\norigin_responses = image_kit.accounts.origins.list\n\nputs(origin_responses)', + }, + typescript: { + method: 'client.accounts.origins.list', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst originResponses = await client.accounts.origins.list();\n\nconsole.log(originResponses);", + }, + }, + }, + { + name: 'create', + endpoint: '/v1/accounts/origins', + httpMethod: 'post', + summary: 'Create origin', + description: + '**Note:** This API is currently in beta. \nCreates a new origin and returns the origin object.\n', + stainlessPath: '(resource) accounts.origins > (method) create', + qualified: 'client.accounts.origins.create', + params: [ + "OriginRequest: { accessKey: string; bucket: string; name: string; secretKey: string; type: 'S3'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { accessKey: string; bucket: string; endpoint: string; name: string; secretKey: string; type: 'S3_COMPATIBLE'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; s3ForcePathStyle?: boolean; } | { accessKey: string; bucket: string; name: string; secretKey: string; type: 'CLOUDINARY_BACKUP'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { baseUrl: string; name: string; type: 'WEB_FOLDER'; baseUrlForCanonicalHeader?: string; forwardHostHeaderToOrigin?: boolean; includeCanonicalHeader?: boolean; } | { name: string; type: 'WEB_PROXY'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; } | { bucket: string; clientEmail: string; name: string; privateKey: string; type: 'GCS'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { accountName: string; container: string; name: string; sasToken: string; type: 'AZURE_BLOB'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { baseUrl: string; clientId: string; clientSecret: string; name: string; password: string; type: 'AKENEO_PIM'; username: string; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; };", + ], + response: 'object | object | object | object | object | object | object | object', + perLanguage: { + cli: { + method: 'origins create', + example: + "imagekit accounts:origins create \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --access-key AKIAIOSFODNN7EXAMPLE \\\n --bucket product-images \\\n --name 'US S3 Storage' \\\n --secret-key wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY \\\n --type S3 \\\n --endpoint https://s3.eu-central-1.wasabisys.com \\\n --base-url https://images.example.com/assets \\\n --client-email service-account@project.iam.gserviceaccount.com \\\n --private-key '-----BEGIN PRIVATE KEY-----\\\\nMIIEv...' \\\n --account-name account123 \\\n --container images \\\n --sas-token '?sv=2023-01-03&sr=c&sig=abc123' \\\n --client-id akeneo-client-id \\\n --client-secret akeneo-client-secret \\\n --password strongpassword123 \\\n --username integration-user", + }, + csharp: { + method: 'Accounts.Origins.Create', + example: + 'OriginCreateParams parameters = new()\n{\n OriginRequest = new S3()\n {\n AccessKey = "AKIATEST123",\n Bucket = "test-bucket",\n Name = "My S3 Origin",\n SecretKey = "secrettest123",\n BaseUrlForCanonicalHeader = "https://cdn.example.com",\n IncludeCanonicalHeader = false,\n Prefix = "images",\n },\n};\n\nvar originResponse = await client.Accounts.Origins.Create(parameters);\n\nConsole.WriteLine(originResponse);', + }, + go: { + method: 'client.Accounts.Origins.New', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\toriginResponse, err := client.Accounts.Origins.New(context.TODO(), imagekit.AccountOriginNewParams{\n\t\tOriginRequest: imagekit.OriginRequestUnionParam{\n\t\t\tOfS3: &imagekit.OriginRequestS3Param{\n\t\t\t\tAccessKey: "AKIATEST123",\n\t\t\t\tBucket: "test-bucket",\n\t\t\t\tName: "My S3 Origin",\n\t\t\t\tSecretKey: "secrettest123",\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", originResponse)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/origins \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "accessKey": "AKIAIOSFODNN7EXAMPLE",\n "bucket": "product-images",\n "name": "US S3 Storage",\n "secretKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",\n "type": "S3",\n "baseUrlForCanonicalHeader": "https://cdn.example.com",\n "prefix": "raw-assets"\n }\'', + }, + java: { + method: 'accounts().origins().create', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.origins.OriginCreateParams;\nimport com.imagekit.api.models.accounts.origins.OriginRequest;\nimport com.imagekit.api.models.accounts.origins.OriginResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n OriginRequest.S3 params = OriginRequest.S3.builder()\n .accessKey("AKIATEST123")\n .bucket("test-bucket")\n .name("My S3 Origin")\n .secretKey("secrettest123")\n .build();\n OriginResponse originResponse = client.accounts().origins().create(params);\n }\n}', + }, + php: { + method: 'accounts->origins->create', + example: + "accounts->origins->create(\n accessKey: 'AKIAIOSFODNN7EXAMPLE',\n bucket: 'gcs-media',\n name: 'US S3 Storage',\n secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n type: 'AKENEO_PIM',\n baseURLForCanonicalHeader: 'https://cdn.example.com',\n includeCanonicalHeader: false,\n prefix: 'uploads',\n endpoint: 'https://s3.eu-central-1.wasabisys.com',\n s3ForcePathStyle: true,\n baseURL: 'https://akeneo.company.com',\n forwardHostHeaderToOrigin: false,\n clientEmail: 'service-account@project.iam.gserviceaccount.com',\n privateKey: '-----BEGIN PRIVATE KEY-----\\\\nMIIEv...',\n accountName: 'account123',\n container: 'images',\n sasToken: '?sv=2023-01-03&sr=c&sig=abc123',\n clientID: 'akeneo-client-id',\n clientSecret: 'akeneo-client-secret',\n password: 'strongpassword123',\n username: 'integration-user',\n);\n\nvar_dump($originResponse);", + }, + python: { + method: 'accounts.origins.create', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\norigin_response = client.accounts.origins.create(\n access_key="AKIAIOSFODNN7EXAMPLE",\n bucket="product-images",\n name="US S3 Storage",\n secret_key="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",\n type="S3",\n)\nprint(origin_response)', + }, + ruby: { + method: 'accounts.origins.create', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\norigin_response = image_kit.accounts.origins.create(\n origin_request: {accessKey: "AKIATEST123", bucket: "test-bucket", name: "My S3 Origin", secretKey: "secrettest123", type: :S3}\n)\n\nputs(origin_response)', + }, + typescript: { + method: 'client.accounts.origins.create', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst originResponse = await client.accounts.origins.create({\n accessKey: 'AKIAIOSFODNN7EXAMPLE',\n bucket: 'product-images',\n name: 'US S3 Storage',\n secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n type: 'S3',\n});\n\nconsole.log(originResponse);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/accounts/origins/{id}', + httpMethod: 'get', + summary: 'Get origin', + description: '**Note:** This API is currently in beta. \nRetrieves the origin identified by `id`.\n', + stainlessPath: '(resource) accounts.origins > (method) get', + qualified: 'client.accounts.origins.get', + params: ['id: string;'], + response: 'object | object | object | object | object | object | object | object', + markdown: + "## get\n\n`client.accounts.origins.get(id: string): { id: string; bucket: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'S3'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; endpoint: string; includeCanonicalHeader: boolean; name: string; prefix: string; s3ForcePathStyle: boolean; type: 'S3_COMPATIBLE'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'CLOUDINARY_BACKUP'; baseUrlForCanonicalHeader?: string; } | { id: string; baseUrl: string; forwardHostHeaderToOrigin: boolean; includeCanonicalHeader: boolean; name: string; type: 'WEB_FOLDER'; baseUrlForCanonicalHeader?: string; } | { id: string; includeCanonicalHeader: boolean; name: string; type: 'WEB_PROXY'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; clientEmail: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'GCS'; baseUrlForCanonicalHeader?: string; } | { id: string; accountName: string; container: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'AZURE_BLOB'; baseUrlForCanonicalHeader?: string; } | { id: string; baseUrl: string; includeCanonicalHeader: boolean; name: string; type: 'AKENEO_PIM'; baseUrlForCanonicalHeader?: string; }`\n\n**get** `/v1/accounts/origins/{id}`\n\n**Note:** This API is currently in beta. \nRetrieves the origin identified by `id`.\n\n\n### Parameters\n\n- `id: string`\n Unique identifier for the origin. This is generated by ImageKit when you create a new origin.\n\n### Returns\n\n- `{ id: string; bucket: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'S3'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; endpoint: string; includeCanonicalHeader: boolean; name: string; prefix: string; s3ForcePathStyle: boolean; type: 'S3_COMPATIBLE'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'CLOUDINARY_BACKUP'; baseUrlForCanonicalHeader?: string; } | { id: string; baseUrl: string; forwardHostHeaderToOrigin: boolean; includeCanonicalHeader: boolean; name: string; type: 'WEB_FOLDER'; baseUrlForCanonicalHeader?: string; } | { id: string; includeCanonicalHeader: boolean; name: string; type: 'WEB_PROXY'; baseUrlForCanonicalHeader?: string; } | { id: string; bucket: string; clientEmail: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'GCS'; baseUrlForCanonicalHeader?: string; } | { id: string; accountName: string; container: string; includeCanonicalHeader: boolean; name: string; prefix: string; type: 'AZURE_BLOB'; baseUrlForCanonicalHeader?: string; } | { id: string; baseUrl: string; includeCanonicalHeader: boolean; name: string; type: 'AKENEO_PIM'; baseUrlForCanonicalHeader?: string; }`\n Origin object as returned by the API (sensitive fields removed).\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst originResponse = await client.accounts.origins.get('id');\n\nconsole.log(originResponse);\n```", + perLanguage: { + cli: { + method: 'origins get', + example: + "imagekit accounts:origins get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'Accounts.Origins.Get', + example: + 'OriginGetParams parameters = new() { ID = "id" };\n\nvar originResponse = await client.Accounts.Origins.Get(parameters);\n\nConsole.WriteLine(originResponse);', + }, + go: { + method: 'client.Accounts.Origins.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\toriginResponse, err := client.Accounts.Origins.Get(context.TODO(), "id")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", originResponse)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/origins/$ID \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'accounts().origins().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.origins.OriginGetParams;\nimport com.imagekit.api.models.accounts.origins.OriginResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n OriginResponse originResponse = client.accounts().origins().get("id");\n }\n}', + }, + php: { + method: 'accounts->origins->get', + example: + "accounts->origins->get('id');\n\nvar_dump($originResponse);", + }, + python: { + method: 'accounts.origins.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\norigin_response = client.accounts.origins.get(\n "id",\n)\nprint(origin_response)', + }, + ruby: { + method: 'accounts.origins.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\norigin_response = image_kit.accounts.origins.get("id")\n\nputs(origin_response)', + }, + typescript: { + method: 'client.accounts.origins.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst originResponse = await client.accounts.origins.get('id');\n\nconsole.log(originResponse);", + }, + }, + }, + { + name: 'update', + endpoint: '/v1/accounts/origins/{id}', + httpMethod: 'put', + summary: 'Update origin', + description: + '**Note:** This API is currently in beta. \nUpdates the origin identified by `id` and returns the updated origin object.\n', + stainlessPath: '(resource) accounts.origins > (method) update', + qualified: 'client.accounts.origins.update', + params: [ + 'id: string;', + "OriginRequest: { accessKey: string; bucket: string; name: string; secretKey: string; type: 'S3'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { accessKey: string; bucket: string; endpoint: string; name: string; secretKey: string; type: 'S3_COMPATIBLE'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; s3ForcePathStyle?: boolean; } | { accessKey: string; bucket: string; name: string; secretKey: string; type: 'CLOUDINARY_BACKUP'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { baseUrl: string; name: string; type: 'WEB_FOLDER'; baseUrlForCanonicalHeader?: string; forwardHostHeaderToOrigin?: boolean; includeCanonicalHeader?: boolean; } | { name: string; type: 'WEB_PROXY'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; } | { bucket: string; clientEmail: string; name: string; privateKey: string; type: 'GCS'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { accountName: string; container: string; name: string; sasToken: string; type: 'AZURE_BLOB'; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; prefix?: string; } | { baseUrl: string; clientId: string; clientSecret: string; name: string; password: string; type: 'AKENEO_PIM'; username: string; baseUrlForCanonicalHeader?: string; includeCanonicalHeader?: boolean; };", + ], + response: 'object | object | object | object | object | object | object | object', + perLanguage: { + cli: { + method: 'origins update', + example: + "imagekit accounts:origins update \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id \\\n --access-key AKIAIOSFODNN7EXAMPLE \\\n --bucket product-images \\\n --name 'US S3 Storage' \\\n --secret-key wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY \\\n --type S3 \\\n --endpoint https://s3.eu-central-1.wasabisys.com \\\n --base-url https://images.example.com/assets \\\n --client-email service-account@project.iam.gserviceaccount.com \\\n --private-key '-----BEGIN PRIVATE KEY-----\\\\nMIIEv...' \\\n --account-name account123 \\\n --container images \\\n --sas-token '?sv=2023-01-03&sr=c&sig=abc123' \\\n --client-id akeneo-client-id \\\n --client-secret akeneo-client-secret \\\n --password strongpassword123 \\\n --username integration-user", + }, + csharp: { + method: 'Accounts.Origins.Update', + example: + 'OriginUpdateParams parameters = new()\n{\n ID = "id",\n OriginRequest = new S3()\n {\n AccessKey = "AKIATEST123",\n Bucket = "test-bucket",\n Name = "My S3 Origin",\n SecretKey = "secrettest123",\n BaseUrlForCanonicalHeader = "https://cdn.example.com",\n IncludeCanonicalHeader = false,\n Prefix = "images",\n },\n};\n\nvar originResponse = await client.Accounts.Origins.Update(parameters);\n\nConsole.WriteLine(originResponse);', + }, + go: { + method: 'client.Accounts.Origins.Update', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\toriginResponse, err := client.Accounts.Origins.Update(\n\t\tcontext.TODO(),\n\t\t"id",\n\t\timagekit.AccountOriginUpdateParams{\n\t\t\tOriginRequest: imagekit.OriginRequestUnionParam{\n\t\t\t\tOfS3: &imagekit.OriginRequestS3Param{\n\t\t\t\t\tAccessKey: "AKIATEST123",\n\t\t\t\t\tBucket: "test-bucket",\n\t\t\t\t\tName: "My S3 Origin",\n\t\t\t\t\tSecretKey: "secrettest123",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", originResponse)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/origins/$ID \\\n -X PUT \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "accessKey": "AKIAIOSFODNN7EXAMPLE",\n "bucket": "product-images",\n "name": "US S3 Storage",\n "secretKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",\n "type": "S3",\n "baseUrlForCanonicalHeader": "https://cdn.example.com",\n "prefix": "raw-assets"\n }\'', + }, + java: { + method: 'accounts().origins().update', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.origins.OriginRequest;\nimport com.imagekit.api.models.accounts.origins.OriginResponse;\nimport com.imagekit.api.models.accounts.origins.OriginUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n OriginUpdateParams params = OriginUpdateParams.builder()\n .id("id")\n .originRequest(OriginRequest.S3.builder()\n .accessKey("AKIATEST123")\n .bucket("test-bucket")\n .name("My S3 Origin")\n .secretKey("secrettest123")\n .build())\n .build();\n OriginResponse originResponse = client.accounts().origins().update(params);\n }\n}', + }, + php: { + method: 'accounts->origins->update', + example: + "accounts->origins->update(\n 'id',\n accessKey: 'AKIAIOSFODNN7EXAMPLE',\n bucket: 'gcs-media',\n name: 'US S3 Storage',\n secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n type: 'AKENEO_PIM',\n baseURLForCanonicalHeader: 'https://cdn.example.com',\n includeCanonicalHeader: false,\n prefix: 'uploads',\n endpoint: 'https://s3.eu-central-1.wasabisys.com',\n s3ForcePathStyle: true,\n baseURL: 'https://akeneo.company.com',\n forwardHostHeaderToOrigin: false,\n clientEmail: 'service-account@project.iam.gserviceaccount.com',\n privateKey: '-----BEGIN PRIVATE KEY-----\\\\nMIIEv...',\n accountName: 'account123',\n container: 'images',\n sasToken: '?sv=2023-01-03&sr=c&sig=abc123',\n clientID: 'akeneo-client-id',\n clientSecret: 'akeneo-client-secret',\n password: 'strongpassword123',\n username: 'integration-user',\n);\n\nvar_dump($originResponse);", + }, + python: { + method: 'accounts.origins.update', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\norigin_response = client.accounts.origins.update(\n id="id",\n access_key="AKIAIOSFODNN7EXAMPLE",\n bucket="product-images",\n name="US S3 Storage",\n secret_key="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",\n type="S3",\n)\nprint(origin_response)', + }, + ruby: { + method: 'accounts.origins.update', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\norigin_response = image_kit.accounts.origins.update(\n "id",\n origin_request: {accessKey: "AKIATEST123", bucket: "test-bucket", name: "My S3 Origin", secretKey: "secrettest123", type: :S3}\n)\n\nputs(origin_response)', + }, + typescript: { + method: 'client.accounts.origins.update', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst originResponse = await client.accounts.origins.update('id', {\n accessKey: 'AKIAIOSFODNN7EXAMPLE',\n bucket: 'product-images',\n name: 'US S3 Storage',\n secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n type: 'S3',\n});\n\nconsole.log(originResponse);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/accounts/origins/{id}', + httpMethod: 'delete', + summary: 'Delete origin', + description: + '**Note:** This API is currently in beta. \nPermanently removes the origin identified by `id`. If the origin is in use by any URL‑endpoints, the API will return an error.\n', + stainlessPath: '(resource) accounts.origins > (method) delete', + qualified: 'client.accounts.origins.delete', + params: ['id: string;'], + markdown: + "## delete\n\n`client.accounts.origins.delete(id: string): void`\n\n**delete** `/v1/accounts/origins/{id}`\n\n**Note:** This API is currently in beta. \nPermanently removes the origin identified by `id`. If the origin is in use by any URL‑endpoints, the API will return an error.\n\n\n### Parameters\n\n- `id: string`\n Unique identifier for the origin. This is generated by ImageKit when you create a new origin.\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nawait client.accounts.origins.delete('id')\n```", + perLanguage: { + cli: { + method: 'origins delete', + example: + "imagekit accounts:origins delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'Accounts.Origins.Delete', + example: + 'OriginDeleteParams parameters = new() { ID = "id" };\n\nawait client.Accounts.Origins.Delete(parameters);', + }, + go: { + method: 'client.Accounts.Origins.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\terr := client.Accounts.Origins.Delete(context.TODO(), "id")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/origins/$ID \\\n -X DELETE \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'accounts().origins().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.origins.OriginDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n client.accounts().origins().delete("id");\n }\n}', + }, + php: { + method: 'accounts->origins->delete', + example: + "accounts->origins->delete('id');\n\nvar_dump($result);", + }, + python: { + method: 'accounts.origins.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nclient.accounts.origins.delete(\n "id",\n)', + }, + ruby: { + method: 'accounts.origins.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresult = image_kit.accounts.origins.delete("id")\n\nputs(result)', + }, + typescript: { + method: 'client.accounts.origins.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nawait client.accounts.origins.delete('id');", + }, + }, + }, + { + name: 'list', + endpoint: '/v1/accounts/url-endpoints', + httpMethod: 'get', + summary: 'List URL‑endpoints', + description: + '**Note:** This API is currently in beta. \nReturns an array of all URL‑endpoints configured including the default URL-endpoint generated by ImageKit during account creation.\n', + stainlessPath: '(resource) accounts.urlEndpoints > (method) list', + qualified: 'client.accounts.urlEndpoints.list', + response: + "{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }[]", + markdown: + "## list\n\n`client.accounts.urlEndpoints.list(): object[]`\n\n**get** `/v1/accounts/url-endpoints`\n\n**Note:** This API is currently in beta. \nReturns an array of all URL‑endpoints configured including the default URL-endpoint generated by ImageKit during account creation.\n\n\n### Returns\n\n- `{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }[]`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst urlEndpointResponses = await client.accounts.urlEndpoints.list();\n\nconsole.log(urlEndpointResponses);\n```", + perLanguage: { + cli: { + method: 'urlEndpoints list', + example: + "imagekit accounts:url-endpoints list \\\n --private-key 'My Private Key' \\\n --password 'My Password'", + }, + csharp: { + method: 'Accounts.UrlEndpoints.List', + example: + 'UrlEndpointListParams parameters = new();\n\nvar urlEndpointResponses = await client.Accounts.UrlEndpoints.List(parameters);\n\nConsole.WriteLine(urlEndpointResponses);', + }, + go: { + method: 'client.Accounts.URLEndpoints.List', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\turlEndpointResponses, err := client.Accounts.URLEndpoints.List(context.TODO())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", urlEndpointResponses)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/url-endpoints \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'accounts().urlEndpoints().list', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointListParams;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n List urlEndpointResponses = client.accounts().urlEndpoints().list();\n }\n}', + }, + php: { + method: 'accounts->urlEndpoints->list', + example: + "accounts->urlEndpoints->list();\n\nvar_dump($urlEndpointResponses);", + }, + python: { + method: 'accounts.url_endpoints.list', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nurl_endpoint_responses = client.accounts.url_endpoints.list()\nprint(url_endpoint_responses)', + }, + ruby: { + method: 'accounts.url_endpoints.list', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nurl_endpoint_responses = image_kit.accounts.url_endpoints.list\n\nputs(url_endpoint_responses)', + }, + typescript: { + method: 'client.accounts.urlEndpoints.list', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst urlEndpointResponses = await client.accounts.urlEndpoints.list();\n\nconsole.log(urlEndpointResponses);", + }, + }, + }, + { + name: 'create', + endpoint: '/v1/accounts/url-endpoints', + httpMethod: 'post', + summary: 'Create URL‑endpoint', + description: + '**Note:** This API is currently in beta. \nCreates a new URL‑endpoint and returns the resulting object.\n', + stainlessPath: '(resource) accounts.urlEndpoints > (method) create', + qualified: 'client.accounts.urlEndpoints.create', + params: [ + 'description: string;', + 'origins?: string[];', + 'urlPrefix?: string;', + "urlRewriter?: { type: 'CLOUDINARY'; preserveAssetDeliveryTypes?: boolean; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; };", + ], + response: + "{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }", + markdown: + "## create\n\n`client.accounts.urlEndpoints.create(description: string, origins?: string[], urlPrefix?: string, urlRewriter?: { type: 'CLOUDINARY'; preserveAssetDeliveryTypes?: boolean; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }): { id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: object | object | object; }`\n\n**post** `/v1/accounts/url-endpoints`\n\n**Note:** This API is currently in beta. \nCreates a new URL‑endpoint and returns the resulting object.\n\n\n### Parameters\n\n- `description: string`\n Description of the URL endpoint.\n\n- `origins?: string[]`\n Ordered list of origin IDs to try when the file isn’t in the Media Library; ImageKit checks them in the sequence provided. Origin must be created before it can be used in a URL endpoint.\n\n- `urlPrefix?: string`\n Path segment appended to your base URL to form the endpoint (letters, digits, and hyphens only — or empty for the default endpoint).\n\n- `urlRewriter?: { type: 'CLOUDINARY'; preserveAssetDeliveryTypes?: boolean; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }`\n Configuration for third-party URL rewriting.\n\n### Returns\n\n- `{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }`\n URL‑endpoint object as returned by the API.\n\n - `id: string`\n - `description: string`\n - `origins: string[]`\n - `urlPrefix: string`\n - `urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst urlEndpointResponse = await client.accounts.urlEndpoints.create({ description: 'My custom URL endpoint' });\n\nconsole.log(urlEndpointResponse);\n```", + perLanguage: { + cli: { + method: 'urlEndpoints create', + example: + "imagekit accounts:url-endpoints create \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --description 'My custom URL endpoint'", + }, + csharp: { + method: 'Accounts.UrlEndpoints.Create', + example: + 'UrlEndpointCreateParams parameters = new()\n{\n Description = "My custom URL endpoint"\n};\n\nvar urlEndpointResponse = await client.Accounts.UrlEndpoints.Create(parameters);\n\nConsole.WriteLine(urlEndpointResponse);', + }, + go: { + method: 'client.Accounts.URLEndpoints.New', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\turlEndpointResponse, err := client.Accounts.URLEndpoints.New(context.TODO(), imagekit.AccountURLEndpointNewParams{\n\t\tURLEndpointRequest: imagekit.URLEndpointRequestParam{\n\t\t\tDescription: "My custom URL endpoint",\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", urlEndpointResponse.ID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/url-endpoints \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "description": "My custom URL endpoint",\n "origins": [\n "origin-id-1"\n ],\n "urlPrefix": "product-images"\n }\'', + }, + java: { + method: 'accounts().urlEndpoints().create', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointCreateParams;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointRequest;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n UrlEndpointRequest params = UrlEndpointRequest.builder()\n .description("My custom URL endpoint")\n .build();\n UrlEndpointResponse urlEndpointResponse = client.accounts().urlEndpoints().create(params);\n }\n}', + }, + php: { + method: 'accounts->urlEndpoints->create', + example: + "accounts->urlEndpoints->create(\n description: 'My custom URL endpoint',\n origins: ['origin-id-1'],\n urlPrefix: 'product-images',\n urlRewriter: ['type' => 'CLOUDINARY', 'preserveAssetDeliveryTypes' => true],\n);\n\nvar_dump($urlEndpointResponse);", + }, + python: { + method: 'accounts.url_endpoints.create', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nurl_endpoint_response = client.accounts.url_endpoints.create(\n description="My custom URL endpoint",\n)\nprint(url_endpoint_response.id)', + }, + ruby: { + method: 'accounts.url_endpoints.create', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nurl_endpoint_response = image_kit.accounts.url_endpoints.create(description: "My custom URL endpoint")\n\nputs(url_endpoint_response)', + }, + typescript: { + method: 'client.accounts.urlEndpoints.create', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst urlEndpointResponse = await client.accounts.urlEndpoints.create({\n description: 'My custom URL endpoint',\n});\n\nconsole.log(urlEndpointResponse.id);", + }, + }, + }, + { + name: 'get', + endpoint: '/v1/accounts/url-endpoints/{id}', + httpMethod: 'get', + summary: 'Get URL‑endpoint', + description: + '**Note:** This API is currently in beta. \nRetrieves the URL‑endpoint identified by `id`.\n', + stainlessPath: '(resource) accounts.urlEndpoints > (method) get', + qualified: 'client.accounts.urlEndpoints.get', + params: ['id: string;'], + response: + "{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }", + markdown: + "## get\n\n`client.accounts.urlEndpoints.get(id: string): { id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: object | object | object; }`\n\n**get** `/v1/accounts/url-endpoints/{id}`\n\n**Note:** This API is currently in beta. \nRetrieves the URL‑endpoint identified by `id`.\n\n\n### Parameters\n\n- `id: string`\n Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new URL-endpoint. For the default URL-endpoint, this is always `default`.\n\n### Returns\n\n- `{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }`\n URL‑endpoint object as returned by the API.\n\n - `id: string`\n - `description: string`\n - `origins: string[]`\n - `urlPrefix: string`\n - `urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst urlEndpointResponse = await client.accounts.urlEndpoints.get('id');\n\nconsole.log(urlEndpointResponse);\n```", + perLanguage: { + cli: { + method: 'urlEndpoints get', + example: + "imagekit accounts:url-endpoints get \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'Accounts.UrlEndpoints.Get', + example: + 'UrlEndpointGetParams parameters = new() { ID = "id" };\n\nvar urlEndpointResponse = await client.Accounts.UrlEndpoints.Get(parameters);\n\nConsole.WriteLine(urlEndpointResponse);', + }, + go: { + method: 'client.Accounts.URLEndpoints.Get', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\turlEndpointResponse, err := client.Accounts.URLEndpoints.Get(context.TODO(), "id")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", urlEndpointResponse.ID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/url-endpoints/$ID \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'accounts().urlEndpoints().get', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointGetParams;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n UrlEndpointResponse urlEndpointResponse = client.accounts().urlEndpoints().get("id");\n }\n}', + }, + php: { + method: 'accounts->urlEndpoints->get', + example: + "accounts->urlEndpoints->get('id');\n\nvar_dump($urlEndpointResponse);", + }, + python: { + method: 'accounts.url_endpoints.get', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nurl_endpoint_response = client.accounts.url_endpoints.get(\n "id",\n)\nprint(url_endpoint_response.id)', + }, + ruby: { + method: 'accounts.url_endpoints.get', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nurl_endpoint_response = image_kit.accounts.url_endpoints.get("id")\n\nputs(url_endpoint_response)', + }, + typescript: { + method: 'client.accounts.urlEndpoints.get', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst urlEndpointResponse = await client.accounts.urlEndpoints.get('id');\n\nconsole.log(urlEndpointResponse.id);", + }, + }, + }, + { + name: 'update', + endpoint: '/v1/accounts/url-endpoints/{id}', + httpMethod: 'put', + summary: 'Update URL‑endpoint', + description: + '**Note:** This API is currently in beta. \nUpdates the URL‑endpoint identified by `id` and returns the updated object.\n', + stainlessPath: '(resource) accounts.urlEndpoints > (method) update', + qualified: 'client.accounts.urlEndpoints.update', + params: [ + 'id: string;', + 'description: string;', + 'origins?: string[];', + 'urlPrefix?: string;', + "urlRewriter?: { type: 'CLOUDINARY'; preserveAssetDeliveryTypes?: boolean; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; };", + ], + response: + "{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }", + markdown: + "## update\n\n`client.accounts.urlEndpoints.update(id: string, description: string, origins?: string[], urlPrefix?: string, urlRewriter?: { type: 'CLOUDINARY'; preserveAssetDeliveryTypes?: boolean; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }): { id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: object | object | object; }`\n\n**put** `/v1/accounts/url-endpoints/{id}`\n\n**Note:** This API is currently in beta. \nUpdates the URL‑endpoint identified by `id` and returns the updated object.\n\n\n### Parameters\n\n- `id: string`\n Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new URL-endpoint. For the default URL-endpoint, this is always `default`.\n\n- `description: string`\n Description of the URL endpoint.\n\n- `origins?: string[]`\n Ordered list of origin IDs to try when the file isn’t in the Media Library; ImageKit checks them in the sequence provided. Origin must be created before it can be used in a URL endpoint.\n\n- `urlPrefix?: string`\n Path segment appended to your base URL to form the endpoint (letters, digits, and hyphens only — or empty for the default endpoint).\n\n- `urlRewriter?: { type: 'CLOUDINARY'; preserveAssetDeliveryTypes?: boolean; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }`\n Configuration for third-party URL rewriting.\n\n### Returns\n\n- `{ id: string; description: string; origins: string[]; urlPrefix: string; urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }; }`\n URL‑endpoint object as returned by the API.\n\n - `id: string`\n - `description: string`\n - `origins: string[]`\n - `urlPrefix: string`\n - `urlRewriter?: { preserveAssetDeliveryTypes: boolean; type: 'CLOUDINARY'; } | { type: 'IMGIX'; } | { type: 'AKAMAI'; }`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst urlEndpointResponse = await client.accounts.urlEndpoints.update('id', { description: 'My custom URL endpoint' });\n\nconsole.log(urlEndpointResponse);\n```", + perLanguage: { + cli: { + method: 'urlEndpoints update', + example: + "imagekit accounts:url-endpoints update \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id \\\n --description 'My custom URL endpoint'", + }, + csharp: { + method: 'Accounts.UrlEndpoints.Update', + example: + 'UrlEndpointUpdateParams parameters = new()\n{\n ID = "id",\n Description = "My custom URL endpoint",\n};\n\nvar urlEndpointResponse = await client.Accounts.UrlEndpoints.Update(parameters);\n\nConsole.WriteLine(urlEndpointResponse);', + }, + go: { + method: 'client.Accounts.URLEndpoints.Update', + example: + 'package main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\turlEndpointResponse, err := client.Accounts.URLEndpoints.Update(\n\t\tcontext.TODO(),\n\t\t"id",\n\t\timagekit.AccountURLEndpointUpdateParams{\n\t\t\tURLEndpointRequest: imagekit.URLEndpointRequestParam{\n\t\t\t\tDescription: "My custom URL endpoint",\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", urlEndpointResponse.ID)\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/url-endpoints/$ID \\\n -X PUT \\\n -H \'Content-Type: application/json\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -d \'{\n "description": "My custom URL endpoint",\n "origins": [\n "origin-id-1"\n ],\n "urlPrefix": "product-images"\n }\'', + }, + java: { + method: 'accounts().urlEndpoints().update', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointRequest;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n UrlEndpointUpdateParams params = UrlEndpointUpdateParams.builder()\n .id("id")\n .urlEndpointRequest(UrlEndpointRequest.builder()\n .description("My custom URL endpoint")\n .build())\n .build();\n UrlEndpointResponse urlEndpointResponse = client.accounts().urlEndpoints().update(params);\n }\n}', + }, + php: { + method: 'accounts->urlEndpoints->update', + example: + "accounts->urlEndpoints->update(\n 'id',\n description: 'My custom URL endpoint',\n origins: ['origin-id-1'],\n urlPrefix: 'product-images',\n urlRewriter: ['type' => 'CLOUDINARY', 'preserveAssetDeliveryTypes' => true],\n);\n\nvar_dump($urlEndpointResponse);", + }, + python: { + method: 'accounts.url_endpoints.update', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nurl_endpoint_response = client.accounts.url_endpoints.update(\n id="id",\n description="My custom URL endpoint",\n)\nprint(url_endpoint_response.id)', + }, + ruby: { + method: 'accounts.url_endpoints.update', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nurl_endpoint_response = image_kit.accounts.url_endpoints.update("id", description: "My custom URL endpoint")\n\nputs(url_endpoint_response)', + }, + typescript: { + method: 'client.accounts.urlEndpoints.update', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst urlEndpointResponse = await client.accounts.urlEndpoints.update('id', {\n description: 'My custom URL endpoint',\n});\n\nconsole.log(urlEndpointResponse.id);", + }, + }, + }, + { + name: 'delete', + endpoint: '/v1/accounts/url-endpoints/{id}', + httpMethod: 'delete', + summary: 'Delete URL‑endpoint', + description: + '**Note:** This API is currently in beta. \nDeletes the URL‑endpoint identified by `id`. You cannot delete the default URL‑endpoint created by ImageKit during account creation.\n', + stainlessPath: '(resource) accounts.urlEndpoints > (method) delete', + qualified: 'client.accounts.urlEndpoints.delete', + params: ['id: string;'], + markdown: + "## delete\n\n`client.accounts.urlEndpoints.delete(id: string): void`\n\n**delete** `/v1/accounts/url-endpoints/{id}`\n\n**Note:** This API is currently in beta. \nDeletes the URL‑endpoint identified by `id`. You cannot delete the default URL‑endpoint created by ImageKit during account creation.\n\n\n### Parameters\n\n- `id: string`\n Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new URL-endpoint. For the default URL-endpoint, this is always `default`.\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nawait client.accounts.urlEndpoints.delete('id')\n```", + perLanguage: { + cli: { + method: 'urlEndpoints delete', + example: + "imagekit accounts:url-endpoints delete \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --id id", + }, + csharp: { + method: 'Accounts.UrlEndpoints.Delete', + example: + 'UrlEndpointDeleteParams parameters = new() { ID = "id" };\n\nawait client.Accounts.UrlEndpoints.Delete(parameters);', + }, + go: { + method: 'client.Accounts.URLEndpoints.Delete', + example: + 'package main\n\nimport (\n\t"context"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\terr := client.Accounts.URLEndpoints.Delete(context.TODO(), "id")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n', + }, + http: { + example: + 'curl https://api.imagekit.io/v1/accounts/url-endpoints/$ID \\\n -X DELETE \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS"', + }, + java: { + method: 'accounts().urlEndpoints().delete', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.accounts.urlendpoints.UrlEndpointDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n client.accounts().urlEndpoints().delete("id");\n }\n}', + }, + php: { + method: 'accounts->urlEndpoints->delete', + example: + "accounts->urlEndpoints->delete('id');\n\nvar_dump($result);", + }, + python: { + method: 'accounts.url_endpoints.delete', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nclient.accounts.url_endpoints.delete(\n "id",\n)', + }, + ruby: { + method: 'accounts.url_endpoints.delete', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresult = image_kit.accounts.url_endpoints.delete("id")\n\nputs(result)', + }, + typescript: { + method: 'client.accounts.urlEndpoints.delete', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nawait client.accounts.urlEndpoints.delete('id');", + }, + }, + }, + { + name: 'upload', + endpoint: '/api/v2/files/upload', + httpMethod: 'post', + summary: 'Upload file V2', + description: + 'The V2 API enhances security by verifying the entire payload using JWT. This API is in beta.\n\nImageKit.io allows you to upload files directly from both the server and client sides. For server-side uploads, private API key authentication is used. For client-side uploads, generate a one-time `token` from your secure backend using private API. [Learn more](/docs/api-reference/upload-file/upload-file-v2#how-to-implement-secure-client-side-file-upload) about how to implement secure client-side file upload.\n\n**File size limit** \\\nOn the free plan, the maximum upload file sizes are 25MB for images, audio, and raw files, and 100MB for videos. On the Lite paid plan, these limits increase to 40MB for images, audio, and raw files and 300MB for videos, whereas on the Pro paid plan, these limits increase to 50MB for images, audio, and raw files and 2GB for videos. These limits can be further increased with enterprise plans.\n\n**Version limit** \\\nA file can have a maximum of 100 versions.\n\n**Demo applications**\n\n- A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more.\n- [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies.\n', + stainlessPath: '(resource) beta.v2.files > (method) upload', + qualified: 'client.beta.v2.files.upload', + params: [ + 'file: string;', + 'fileName: string;', + 'token?: string;', + 'checks?: string;', + 'customCoordinates?: string;', + 'customMetadata?: object;', + 'description?: string;', + "extensions?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; } | { id: string; name: 'saved-extension'; }[];", + 'folder?: string;', + 'isPrivateFile?: boolean;', + 'isPublished?: boolean;', + 'overwriteAITags?: boolean;', + 'overwriteCustomMetadata?: boolean;', + 'overwriteFile?: boolean;', + 'overwriteTags?: boolean;', + 'responseFields?: string[];', + 'tags?: string[];', + "transformation?: { post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]; pre?: string; };", + 'useUniqueFileName?: boolean;', + 'webhookUrl?: string;', + ], + response: + "{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; extensionStatus?: { ai-auto-description?: 'success' | 'pending' | 'failed'; ai-tasks?: 'success' | 'pending' | 'failed'; aws-auto-tagging?: 'success' | 'pending' | 'failed'; google-auto-tagging?: 'success' | 'pending' | 'failed'; remove-bg?: 'success' | 'pending' | 'failed'; }; fileId?: string; filePath?: string; fileType?: string; height?: number; isPrivateFile?: boolean; isPublished?: boolean; metadata?: { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: object; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnailUrl?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }", + markdown: + "## upload\n\n`client.beta.v2.files.upload(file: string, fileName: string, token?: string, checks?: string, customCoordinates?: string, customMetadata?: object, description?: string, extensions?: { name: 'remove-bg'; options?: object; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: object | object | object[]; } | { id: string; name: 'saved-extension'; }[], folder?: string, isPrivateFile?: boolean, isPublished?: boolean, overwriteAITags?: boolean, overwriteCustomMetadata?: boolean, overwriteFile?: boolean, overwriteTags?: boolean, responseFields?: string[], tags?: string[], transformation?: { post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]; pre?: string; }, useUniqueFileName?: boolean, webhookUrl?: string): { AITags?: object[]; audioCodec?: string; bitRate?: number; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; extensionStatus?: object; fileId?: string; filePath?: string; fileType?: string; height?: number; isPrivateFile?: boolean; isPublished?: boolean; metadata?: metadata; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnailUrl?: string; url?: string; versionInfo?: object; videoCodec?: string; width?: number; }`\n\n**post** `/api/v2/files/upload`\n\nThe V2 API enhances security by verifying the entire payload using JWT. This API is in beta.\n\nImageKit.io allows you to upload files directly from both the server and client sides. For server-side uploads, private API key authentication is used. For client-side uploads, generate a one-time `token` from your secure backend using private API. [Learn more](/docs/api-reference/upload-file/upload-file-v2#how-to-implement-secure-client-side-file-upload) about how to implement secure client-side file upload.\n\n**File size limit** \\\nOn the free plan, the maximum upload file sizes are 25MB for images, audio, and raw files, and 100MB for videos. On the Lite paid plan, these limits increase to 40MB for images, audio, and raw files and 300MB for videos, whereas on the Pro paid plan, these limits increase to 50MB for images, audio, and raw files and 2GB for videos. These limits can be further increased with enterprise plans.\n\n**Version limit** \\\nA file can have a maximum of 100 versions.\n\n**Demo applications**\n\n- A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more.\n- [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies.\n\n\n### Parameters\n\n- `file: string`\n The API accepts any of the following:\n\n- **Binary data** – send the raw bytes as `multipart/form-data`.\n- **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch.\n- **Base64 string** – the file encoded as a Base64 data URI or plain Base64.\n\nWhen supplying a URL, the server must receive the response headers within 8 seconds; otherwise the request fails with 400 Bad Request.\n\n\n- `fileName: string`\n The name with which the file has to be uploaded.\n\n\n- `token?: string`\n This is the client-generated JSON Web Token (JWT). The ImageKit.io server uses it to authenticate and check that the upload request parameters have not been tampered with after the token has been generated. Learn how to create the token on the page below. This field is only required for authentication when uploading a file from the client side.\n\n\n**Note**: Sending a JWT that has been used in the past will result in a validation error. Even if your previous request resulted in an error, you should always send a new token.\n\n\n**⚠️Warning**: JWT must be generated on the server-side because it is generated using your account's private API key. This field is required for authentication when uploading a file from the client-side.\n\n\n- `checks?: string`\n Server-side checks to run on the asset.\nRead more about [Upload API checks](/docs/api-reference/upload-file/upload-file-v2#upload-api-checks).\n\n\n- `customCoordinates?: string`\n Define an important area in the image. This is only relevant for image type files.\n\n - To be passed as a string with the x and y coordinates of the top-left corner, and width and height of the area of interest in the format `x,y,width,height`. For example - `10,10,100,100`\n - Can be used with fo-customtransformation.\n - If this field is not specified and the file is overwritten, then customCoordinates will be removed.\n\n\n- `customMetadata?: object`\n JSON key-value pairs to associate with the asset. Create the custom metadata fields before setting these values.\n\n\n- `description?: string`\n Optional text to describe the contents of the file.\n\n\n- `extensions?: { name: 'remove-bg'; options?: { add_shadow?: boolean; bg_color?: string; bg_image_url?: string; semitransparency?: boolean; }; } | { maxTags: number; minConfidence: number; name: 'google-auto-tagging' | 'aws-auto-tagging'; } | { name: 'ai-auto-description'; } | { name: 'ai-tasks'; tasks: { instruction: string; type: 'select_tags'; max_selections?: number; min_selections?: number; vocabulary?: string[]; } | { field: string; instruction: string; type: 'select_metadata'; max_selections?: number; min_selections?: number; vocabulary?: string | number | boolean[]; } | { instruction: string; type: 'yes_no'; on_no?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_unknown?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; on_yes?: { add_tags?: string[]; remove_tags?: string[]; set_metadata?: object[]; unset_metadata?: object[]; }; }[]; } | { id: string; name: 'saved-extension'; }[]`\n Array of extensions to be applied to the asset. Each extension can be configured with specific parameters based on the extension type.\n\n\n- `folder?: string`\n The folder path in which the image has to be uploaded. If the folder(s) didn't exist before, a new folder(s) is created. Using multiple `/` creates a nested folder.\n\n\n- `isPrivateFile?: boolean`\n Whether to mark the file as private or not.\n\nIf `true`, the file is marked as private and is accessible only using named transformation or signed URL.\n\n\n- `isPublished?: boolean`\n Whether to upload file as published or not.\n\nIf `false`, the file is marked as unpublished, which restricts access to the file only via the media library. Files in draft or unpublished state can only be publicly accessed after being published.\n\nThe option to upload in draft state is only available in custom enterprise pricing plans.\n\n\n- `overwriteAITags?: boolean`\n If set to `true` and a file already exists at the exact location, its AITags will be removed. Set `overwriteAITags` to `false` to preserve AITags.\n\n\n- `overwriteCustomMetadata?: boolean`\n If the request does not have `customMetadata`, and a file already exists at the exact location, existing customMetadata will be removed.\n\n\n- `overwriteFile?: boolean`\n If `false` and `useUniqueFileName` is also `false`, and a file already exists at the exact location, upload API will return an error immediately.\n\n\n- `overwriteTags?: boolean`\n If the request does not have `tags`, and a file already exists at the exact location, existing tags will be removed.\n\n\n- `responseFields?: string[]`\n Array of response field keys to include in the API response body.\n\n\n- `tags?: string[]`\n Set the tags while uploading the file.\nProvide an array of tag strings (e.g. `[\"tag1\", \"tag2\", \"tag3\"]`). The combined length of all tag characters must not exceed 500, and the `%` character is not allowed.\nIf this field is not specified and the file is overwritten, the existing tags will be removed.\n\n\n- `transformation?: { post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]; pre?: string; }`\n Configure pre-processing (`pre`) and post-processing (`post`) transformations.\n\n- `pre` — applied before the file is uploaded to the Media Library. \n Useful for reducing file size or applying basic optimizations upfront (e.g., resize, compress).\n\n- `post` — applied immediately after upload. \n Ideal for generating transformed versions (like video encodes or thumbnails) in advance, so they're ready for delivery without delay.\n\nYou can mix and match any combination of post-processing types.\n\n - `post?: { type: 'transformation'; value: string; } | { type: 'gif-to-video'; value?: string; } | { type: 'thumbnail'; value?: string; } | { protocol: 'hls' | 'dash'; type: 'abs'; value: string; }[]`\n List of transformations to apply *after* the file is uploaded. \nEach item must match one of the following types:\n`transformation`, `gif-to-video`, `thumbnail`, `abs`.\n\n - `pre?: string`\n Transformation string to apply before uploading the file to the Media Library. Useful for optimizing files at ingestion.\n\n\n- `useUniqueFileName?: boolean`\n Whether to use a unique filename for this file or not.\n\nIf `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique filename.\n\nIf `false`, then the image is uploaded with the provided filename parameter, and any existing file with the same name is replaced.\n\n\n- `webhookUrl?: string`\n The final status of extensions after they have completed execution will be delivered to this endpoint as a POST request. [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) about the webhook payload structure.\n\n\n### Returns\n\n- `{ AITags?: { confidence?: number; name?: string; source?: string; }[]; audioCodec?: string; bitRate?: number; customCoordinates?: string; customMetadata?: object; description?: string; duration?: number; embeddedMetadata?: object; extensionStatus?: { ai-auto-description?: 'success' | 'pending' | 'failed'; ai-tasks?: 'success' | 'pending' | 'failed'; aws-auto-tagging?: 'success' | 'pending' | 'failed'; google-auto-tagging?: 'success' | 'pending' | 'failed'; remove-bg?: 'success' | 'pending' | 'failed'; }; fileId?: string; filePath?: string; fileType?: string; height?: number; isPrivateFile?: boolean; isPublished?: boolean; metadata?: { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: object; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }; name?: string; selectedFieldsSchema?: object; size?: number; tags?: string[]; thumbnailUrl?: string; url?: string; versionInfo?: { id?: string; name?: string; }; videoCodec?: string; width?: number; }`\n Object containing details of a successful upload.\n\n - `AITags?: { confidence?: number; name?: string; source?: string; }[]`\n - `audioCodec?: string`\n - `bitRate?: number`\n - `customCoordinates?: string`\n - `customMetadata?: object`\n - `description?: string`\n - `duration?: number`\n - `embeddedMetadata?: object`\n - `extensionStatus?: { ai-auto-description?: 'success' | 'pending' | 'failed'; ai-tasks?: 'success' | 'pending' | 'failed'; aws-auto-tagging?: 'success' | 'pending' | 'failed'; google-auto-tagging?: 'success' | 'pending' | 'failed'; remove-bg?: 'success' | 'pending' | 'failed'; }`\n - `fileId?: string`\n - `filePath?: string`\n - `fileType?: string`\n - `height?: number`\n - `isPrivateFile?: boolean`\n - `isPublished?: boolean`\n - `metadata?: { audioCodec?: string; bitRate?: number; density?: number; duration?: number; exif?: { exif?: { ApertureValue?: number; ColorSpace?: number; CreateDate?: string; CustomRendered?: number; DateTimeOriginal?: string; ExifImageHeight?: number; ExifImageWidth?: number; ExifVersion?: string; ExposureCompensation?: number; ExposureMode?: number; ExposureProgram?: number; ExposureTime?: number; Flash?: number; FlashpixVersion?: string; FNumber?: number; FocalLength?: number; FocalPlaneResolutionUnit?: number; FocalPlaneXResolution?: number; FocalPlaneYResolution?: number; InteropOffset?: number; ISO?: number; MeteringMode?: number; SceneCaptureType?: number; ShutterSpeedValue?: number; SubSecTime?: string; WhiteBalance?: number; }; gps?: { GPSVersionID?: number[]; }; image?: { ExifOffset?: number; GPSInfo?: number; Make?: string; Model?: string; ModifyDate?: string; Orientation?: number; ResolutionUnit?: number; Software?: string; XResolution?: number; YCbCrPositioning?: number; YResolution?: number; }; interoperability?: { InteropIndex?: string; InteropVersion?: string; }; makernote?: object; thumbnail?: { Compression?: number; ResolutionUnit?: number; ThumbnailLength?: number; ThumbnailOffset?: number; XResolution?: number; YResolution?: number; }; }; format?: string; hasColorProfile?: boolean; hasTransparency?: boolean; height?: number; pHash?: string; quality?: number; size?: number; videoCodec?: string; width?: number; }`\n - `name?: string`\n - `selectedFieldsSchema?: object`\n - `size?: number`\n - `tags?: string[]`\n - `thumbnailUrl?: string`\n - `url?: string`\n - `versionInfo?: { id?: string; name?: string; }`\n - `videoCodec?: string`\n - `width?: number`\n\n### Example\n\n```typescript\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\nconst response = await client.beta.v2.files.upload({ file: fs.createReadStream('path/to/file'), fileName: 'fileName' });\n\nconsole.log(response);\n```", + perLanguage: { + cli: { + method: 'files upload', + example: + "imagekit beta:v2:files upload \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file 'Example data' \\\n --file-name fileName", + }, + csharp: { + method: 'Beta.V2.Files.Upload', + example: + 'FileUploadParams parameters = new()\n{\n File = Encoding.UTF8.GetBytes("Example data"),\n FileName = "fileName",\n};\n\nvar response = await client.Beta.V2.Files.Upload(parameters);\n\nConsole.WriteLine(response);', + }, + go: { + method: 'client.Beta.V2.Files.Upload', + example: + 'package main\n\nimport (\n\t"bytes"\n\t"context"\n\t"fmt"\n\t"io"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\tresponse, err := client.Beta.V2.Files.Upload(context.TODO(), imagekit.BetaV2FileUploadParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte("Example data"))),\n\t\tFileName: "fileName",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.VideoCodec)\n}\n', + }, + http: { + example: + 'curl https://upload.imagekit.io/api/v2/files/upload \\\n -H \'Content-Type: multipart/form-data\' \\\n -u "$IMAGEKIT_PRIVATE_KEY:OPTIONAL_IMAGEKIT_IGNORES_THIS" \\\n -F \'file=@/path/to/file\' \\\n -F fileName=fileName \\\n -F checks=\'"request.folder" : "marketing/"\n \' \\\n -F customMetadata=\'{"brand":"bar","color":"bar"}\' \\\n -F description=\'Running shoes\' \\\n -F extensions=\'[{"name":"remove-bg","options":{"add_shadow":true}},{"maxTags":5,"minConfidence":95,"name":"google-auto-tagging"},{"name":"ai-auto-description"},{"name":"ai-tasks","tasks":[{"instruction":"What types of clothing items are visible in this image?","type":"select_tags","vocabulary":["shirt","tshirt","dress","trousers","jacket"]},{"instruction":"Is this a luxury or high-end fashion item?","type":"yes_no","on_yes":{"add_tags":["luxury","premium"]}}]},{"id":"ext_abc123","name":"saved-extension"}]\' \\\n -F responseFields=\'["tags","customCoordinates","isPrivateFile"]\' \\\n -F tags=\'["t-shirt","round-neck","men"]\' \\\n -F transformation=\'{"post":[{"type":"thumbnail","value":"w-150,h-150"},{"protocol":"dash","type":"abs","value":"sr-240_360_480_720_1080"}]}\'', + }, + java: { + method: 'beta().v2().files().upload', + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.beta.v2.files.FileUploadParams;\nimport com.imagekit.api.models.beta.v2.files.FileUploadResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n FileUploadParams params = FileUploadParams.builder()\n .file(new ByteArrayInputStream("Example data".getBytes()))\n .fileName("fileName")\n .build();\n FileUploadResponse response = client.beta().v2().files().upload(params);\n }\n}', + }, + php: { + method: 'beta->v2->files->upload', + example: + "beta->v2->files->upload(\n file: 'file',\n fileName: 'fileName',\n token: 'token',\n checks: \"\\\"request.folder\\\" : \\\"marketing/\\\"\\n\",\n customCoordinates: 'customCoordinates',\n customMetadata: ['brand' => 'bar', 'color' => 'bar'],\n description: 'Running shoes',\n extensions: [\n [\n 'name' => 'remove-bg',\n 'options' => [\n 'addShadow' => true,\n 'bgColor' => 'bg_color',\n 'bgImageURL' => 'bg_image_url',\n 'semitransparency' => true,\n ],\n ],\n ['maxTags' => 5, 'minConfidence' => 95, 'name' => 'google-auto-tagging'],\n ['name' => 'ai-auto-description'],\n [\n 'name' => 'ai-tasks',\n 'tasks' => [\n [\n 'instruction' => 'What types of clothing items are visible in this image?',\n 'type' => 'select_tags',\n 'maxSelections' => 1,\n 'minSelections' => 0,\n 'vocabulary' => ['shirt', 'tshirt', 'dress', 'trousers', 'jacket'],\n ],\n [\n 'instruction' => 'Is this a luxury or high-end fashion item?',\n 'type' => 'yes_no',\n 'onNo' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n 'onUnknown' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n 'onYes' => [\n 'addTags' => ['luxury', 'premium'],\n 'removeTags' => ['budget', 'affordable'],\n 'setMetadata' => [['field' => 'price_range', 'value' => 'premium']],\n 'unsetMetadata' => [['field' => 'price_range']],\n ],\n ],\n ],\n ],\n ['id' => 'ext_abc123', 'name' => 'saved-extension'],\n ],\n folder: 'folder',\n isPrivateFile: true,\n isPublished: true,\n overwriteAITags: true,\n overwriteCustomMetadata: true,\n overwriteFile: true,\n overwriteTags: true,\n responseFields: ['tags', 'customCoordinates', 'isPrivateFile'],\n tags: ['t-shirt', 'round-neck', 'men'],\n transformation: [\n 'post' => [\n ['type' => 'thumbnail', 'value' => 'w-150,h-150'],\n [\n 'protocol' => 'dash',\n 'type' => 'abs',\n 'value' => 'sr-240_360_480_720_1080',\n ],\n ],\n 'pre' => 'w-300,h-300,q-80',\n ],\n useUniqueFileName: true,\n webhookURL: 'https://example.com',\n);\n\nvar_dump($response);", + }, + python: { + method: 'beta.v2.files.upload', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nresponse = client.beta.v2.files.upload(\n file=b"Example data",\n file_name="fileName",\n)\nprint(response.video_codec)', + }, + ruby: { + method: 'beta.v2.files.upload', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresponse = image_kit.beta.v2.files.upload(file: StringIO.new("Example data"), file_name: "fileName")\n\nputs(response)', + }, + typescript: { + method: 'client.beta.v2.files.upload', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.beta.v2.files.upload({\n file: fs.createReadStream('path/to/file'),\n fileName: 'fileName',\n});\n\nconsole.log(response.videoCodec);", + }, + }, + }, + { + name: 'unwrap', + endpoint: '', + httpMethod: '', + summary: '', + description: '', + stainlessPath: '(resource) webhooks > (method) unwrap', + qualified: 'client.webhooks.unwrap', + perLanguage: { + cli: { + example: + "imagekit webhooks unwrap \\\n --private-key 'My Private Key' \\\n --password 'My Password'", + }, + csharp: { + example: 'WebhookUnwrapParams parameters = new();\n\nawait client.Webhooks.Unwrap(parameters);', + }, + go: { + method: 'client.Webhooks.Unwrap', + example: + 'package main\n\nimport (\n\t"context"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\terr := client.Webhooks.Unwrap(context.TODO())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n', + }, + java: { + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.webhooks.WebhookUnwrapParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n client.webhooks().unwrap();\n }\n}', + }, + php: { + method: 'webhooks->unwrap', + example: + "webhooks->unwrap();\n\nvar_dump($result);", + }, + python: { + method: 'webhooks.unwrap', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nclient.webhooks.unwrap()', + }, + ruby: { + method: 'webhooks.unwrap', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresult = image_kit.webhooks.unwrap\n\nputs(result)', + }, + typescript: { + method: 'client.webhooks.unwrap', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nawait client.webhooks.unwrap();", + }, + }, + }, + { + name: 'unsafe_unwrap', + endpoint: '', + httpMethod: '', + summary: '', + description: '', + stainlessPath: '(resource) webhooks > (method) unsafe_unwrap', + qualified: 'client.webhooks.unsafeUnwrap', + perLanguage: { + cli: { + example: + "imagekit webhooks unsafe-unwrap \\\n --private-key 'My Private Key' \\\n --password 'My Password'", + }, + csharp: { + example: + 'WebhookUnsafeUnwrapParams parameters = new();\n\nawait client.Webhooks.UnsafeUnwrap(parameters);', + }, + go: { + method: 'client.Webhooks.UnsafeUnwrap', + example: + 'package main\n\nimport (\n\t"context"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"),\n\t\toption.WithPassword("My Password"),\n\t)\n\terr := client.Webhooks.UnsafeUnwrap(context.TODO())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n', + }, + java: { + example: + 'package com.imagekit.api.example;\n\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.webhooks.WebhookUnsafeUnwrapParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n ImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\n client.webhooks().unsafeUnwrap();\n }\n}', + }, + php: { + method: 'webhooks->unsafeUnwrap', + example: + "webhooks->unsafeUnwrap();\n\nvar_dump($result);", + }, + python: { + method: 'webhooks.unsafe_unwrap', + example: + 'import os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\nclient.webhooks.unsafe_unwrap()', + }, + ruby: { + method: 'webhooks.unsafe_unwrap', + example: + 'require "imagekitio"\n\nimage_kit = Imagekitio::Client.new(private_key: "My Private Key", password: "My Password")\n\nresult = image_kit.webhooks.unsafe_unwrap\n\nputs(result)', + }, + typescript: { + method: 'client.webhooks.unsafeUnwrap', + example: + "import ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nawait client.webhooks.unsafeUnwrap();", + }, + }, + }, +]; + +const EMBEDDED_READMES: { language: string; content: string }[] = [ + { + language: 'python', + content: + '# Image Kit Python API library\n\n\n[![PyPI version](https://img.shields.io/pypi/v/imagekitio.svg?label=pypi%20(stable))](https://pypi.org/project/imagekitio/)\n\nThe Image Kit Python library provides convenient access to the Image Kit REST API from any Python 3.9+\napplication. The library includes type definitions for all request params and response fields,\nand offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).\n\n\n\n\n\n## MCP Server\n\nUse the Image Kit MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40imagekit%2Fapi-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBpbWFnZWtpdC9hcGktbWNwIl0sImVudiI6eyJJTUFHRUtJVF9QUklWQVRFX0tFWSI6Ik15IFByaXZhdGUgS2V5IiwiT1BUSU9OQUxfSU1BR0VLSVRfSUdOT1JFU19USElTIjoiTXkgUGFzc3dvcmQiLCJJTUFHRUtJVF9XRUJIT09LX1NFQ1JFVCI6Ik15IFdlYmhvb2sgU2VjcmV0In19)\n[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40imagekit%2Fapi-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40imagekit%2Fapi-mcp%22%5D%2C%22env%22%3A%7B%22IMAGEKIT_PRIVATE_KEY%22%3A%22My%20Private%20Key%22%2C%22OPTIONAL_IMAGEKIT_IGNORES_THIS%22%3A%22My%20Password%22%2C%22IMAGEKIT_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Documentation\n\nThe REST API documentation can be found on [imagekit.io](https://imagekit.io/docs/api-reference). The full API of this library can be found in [api.md](api.md).\n\n## Installation\n\n```sh\n# install from PyPI\npip install imagekitio\n```\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n```python\nimport os\nfrom imagekitio import ImageKit\n\nclient = ImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\n\nresponse = client.files.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n)\nprint(response.video_codec)\n```\n\nWhile you can provide a `private_key` keyword argument,\nwe recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)\nto add `IMAGEKIT_PRIVATE_KEY="My Private Key"` to your `.env` file\nso that your Private Key is not stored in source control.\n\n## Async usage\n\nSimply import `AsyncImageKit` instead of `ImageKit` and use `await` with each API call:\n\n```python\nimport os\nimport asyncio\nfrom imagekitio import AsyncImageKit\n\nclient = AsyncImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n)\n\nasync def main() -> None:\n response = await client.files.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n )\n print(response.video_codec)\n\nasyncio.run(main())\n```\n\nFunctionality between the synchronous and asynchronous clients is otherwise identical.\n\n### With aiohttp\n\nBy default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.\n\nYou can enable this by installing `aiohttp`:\n\n```sh\n# install from PyPI\npip install imagekitio[aiohttp]\n```\n\nThen you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:\n\n```python\nimport os\nimport asyncio\nfrom imagekitio import DefaultAioHttpClient\nfrom imagekitio import AsyncImageKit\n\nasync def main() -> None:\n async with AsyncImageKit(\n private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted\n password=os.environ.get("OPTIONAL_IMAGEKIT_IGNORES_THIS"), # This is the default and can be omitted\n http_client=DefaultAioHttpClient(),\n) as client:\n response = await client.files.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n )\n print(response.video_codec)\n\nasyncio.run(main())\n```\n\n\n\n## Using types\n\nNested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like:\n\n- Serializing back into JSON, `model.to_json()`\n- Converting to a dictionary, `model.to_dict()`\n\nTyped requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.\n\n\n\n## Nested params\n\nNested parameters are dictionaries, typed using `TypedDict`, for example:\n\n```python\nfrom imagekitio import ImageKit\n\nclient = ImageKit()\n\nresponse = client.files.upload(\n file=b"Example data",\n file_name="fileName",\n transformation={\n "post": [{\n "type": "thumbnail",\n "value": "w-150,h-150",\n }, {\n "protocol": "dash",\n "type": "abs",\n "value": "sr-240_360_480_720_1080",\n }]\n },\n)\nprint(response.transformation)\n```\n\n## File uploads\n\nRequest parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`.\n\n```python\nfrom pathlib import Path\nfrom imagekitio import ImageKit\n\nclient = ImageKit()\n\nclient.files.upload(\n file=Path("/path/to/file"),\n file_name="fileName",\n)\n```\n\nThe async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically.\n\n## Handling errors\n\nWhen the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `imagekitio.APIConnectionError` is raised.\n\nWhen the API returns a non-success status code (that is, 4xx or 5xx\nresponse), a subclass of `imagekitio.APIStatusError` is raised, containing `status_code` and `response` properties.\n\nAll errors inherit from `imagekitio.APIError`.\n\n```python\nimport imagekitio\nfrom imagekitio import ImageKit\n\nclient = ImageKit()\n\ntry:\n client.files.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n )\nexcept imagekitio.APIConnectionError as e:\n print("The server could not be reached")\n print(e.__cause__) # an underlying Exception, likely raised within httpx.\nexcept imagekitio.RateLimitError as e:\n print("A 429 status code was received; we should back off a bit.")\nexcept imagekitio.APIStatusError as e:\n print("Another non-200-range status code was received")\n print(e.status_code)\n print(e.response)\n```\n\nError codes are as follows:\n\n| Status Code | Error Type |\n| ----------- | -------------------------- |\n| 400 | `BadRequestError` |\n| 401 | `AuthenticationError` |\n| 403 | `PermissionDeniedError` |\n| 404 | `NotFoundError` |\n| 422 | `UnprocessableEntityError` |\n| 429 | `RateLimitError` |\n| >=500 | `InternalServerError` |\n| N/A | `APIConnectionError` |\n\n### Retries\n\nCertain errors are automatically retried 2 times by default, with a short exponential backoff.\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,\n429 Rate Limit, and >=500 Internal errors are all retried by default.\n\nYou can use the `max_retries` option to configure or disable retry settings:\n\n```python\nfrom imagekitio import ImageKit\n\n# Configure the default for all requests:\nclient = ImageKit(\n # default is 2\n max_retries=0,\n)\n\n# Or, configure per-request:\nclient.with_options(max_retries = 5).files.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n)\n```\n\n### Timeouts\n\nBy default requests time out after 1 minute. You can configure this with a `timeout` option,\nwhich accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:\n\n```python\nfrom imagekitio import ImageKit\n\n# Configure the default for all requests:\nclient = ImageKit(\n # 20 seconds (default is 1 minute)\n timeout=20.0,\n)\n\n# More granular control:\nclient = ImageKit(\n timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),\n)\n\n# Override per-request:\nclient.with_options(timeout = 5.0).files.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n)\n```\n\nOn timeout, an `APITimeoutError` is thrown.\n\nNote that requests that time out are [retried twice by default](#retries).\n\n\n\n## Advanced\n\n### Logging\n\nWe use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.\n\nYou can enable logging by setting the environment variable `IMAGE_KIT_LOG` to `info`.\n\n```shell\n$ export IMAGE_KIT_LOG=info\n```\n\nOr to `debug` for more verbose logging.\n\n### How to tell whether `None` means `null` or missing\n\nIn an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:\n\n```py\nif response.my_field is None:\n if \'my_field\' not in response.model_fields_set:\n print(\'Got json like {}, without a "my_field" key present at all.\')\n else:\n print(\'Got json like {"my_field": null}.\')\n```\n\n### Accessing raw response data (e.g. headers)\n\nThe "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,\n\n```py\nfrom imagekitio import ImageKit\n\nclient = ImageKit()\nresponse = client.files.with_raw_response.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n)\nprint(response.headers.get(\'X-My-Header\'))\n\nfile = response.parse() # get the object that `files.upload()` would have returned\nprint(file.video_codec)\n```\n\nThese methods return an [`APIResponse`](https://github.com/imagekit-developer/imagekit-python/tree/master/src/imagekitio/_response.py) object.\n\nThe async client returns an [`AsyncAPIResponse`](https://github.com/imagekit-developer/imagekit-python/tree/master/src/imagekitio/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.\n\n#### `.with_streaming_response`\n\nThe above interface eagerly reads the full response body when you make the request, which may not always be what you want.\n\nTo stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.\n\n```python\nwith client.files.with_streaming_response.upload(\n file=b"https://www.example.com/public-url.jpg",\n file_name="file-name.jpg",\n) as response :\n print(response.headers.get(\'X-My-Header\'))\n\n for line in response.iter_lines():\n print(line)\n```\n\nThe context manager is required so that the response will reliably be closed.\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API.\n\nIf you need to access undocumented endpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other\nhttp verbs. Options on the client will be respected (such as retries) when making this request.\n\n```py\nimport httpx\n\nresponse = client.post(\n "/foo",\n cast_to=httpx.Response,\n body={"my_param": True},\n)\n\nprint(response.headers.get("x-foo"))\n```\n\n#### Undocumented request params\n\nIf you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You\ncan also get all the extra fields on the Pydantic model as a dict with\n[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).\n\n### Configuring the HTTP client\n\nYou can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:\n\n- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)\n- Custom [transports](https://www.python-httpx.org/advanced/transports/)\n- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality\n\n```python\nimport httpx\nfrom imagekitio import ImageKit, DefaultHttpxClient\n\nclient = ImageKit(\n # Or use the `IMAGE_KIT_BASE_URL` env var\n base_url="http://my.test.server.example.com:8083",\n http_client=DefaultHttpxClient(proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0")),\n)\n```\n\nYou can also customize the client on a per-request basis by using `with_options()`:\n\n```python\nclient.with_options(http_client=DefaultHttpxClient(...))\n```\n\n### Managing HTTP resources\n\nBy default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.\n\n```py\nfrom imagekitio import ImageKit\n\nwith ImageKit() as client:\n # make requests here\n ...\n\n# HTTP client is now closed\n```\n\n## Versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/imagekit-developer/imagekit-python/issues) with questions, bugs, or suggestions.\n\n### Determining the installed version\n\nIf you\'ve upgraded to the latest version but aren\'t seeing any new features you were expecting then your python environment is likely still using an older version.\n\nYou can determine the version that is being used at runtime with:\n\n```py\nimport imagekitio\nprint(imagekitio.__version__)\n```\n\n## Requirements\n\nPython 3.9 or higher.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n', + }, + { + language: 'go', + content: + '# Image Kit Go API Library\n\nGo Reference\n\nThe Image Kit Go library provides convenient access to the [Image Kit REST API](https://imagekit.io/docs/api-reference)\nfrom applications written in Go.\n\n\n\n## MCP Server\n\nUse the Image Kit MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40imagekit%2Fapi-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBpbWFnZWtpdC9hcGktbWNwIl0sImVudiI6eyJJTUFHRUtJVF9QUklWQVRFX0tFWSI6Ik15IFByaXZhdGUgS2V5IiwiT1BUSU9OQUxfSU1BR0VLSVRfSUdOT1JFU19USElTIjoiTXkgUGFzc3dvcmQiLCJJTUFHRUtJVF9XRUJIT09LX1NFQ1JFVCI6Ik15IFdlYmhvb2sgU2VjcmV0In19)\n[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40imagekit%2Fapi-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40imagekit%2Fapi-mcp%22%5D%2C%22env%22%3A%7B%22IMAGEKIT_PRIVATE_KEY%22%3A%22My%20Private%20Key%22%2C%22OPTIONAL_IMAGEKIT_IGNORES_THIS%22%3A%22My%20Password%22%2C%22IMAGEKIT_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Installation\n\n\n\n```go\nimport (\n\t"github.com/imagekit-developer/imagekit-go" // imported as SDK_PackageName\n)\n```\n\n\n\nOr to pin the version:\n\n\n\n```sh\ngo get -u \'github.com/imagekit-developer/imagekit-go@v0.0.1\'\n```\n\n\n\n## Requirements\n\nThis library requires Go 1.22+.\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n```go\npackage main\n\nimport (\n\t"bytes"\n\t"context"\n\t"fmt"\n\t"io"\n\n\t"github.com/imagekit-developer/imagekit-go"\n\t"github.com/imagekit-developer/imagekit-go/option"\n)\n\nfunc main() {\n\tclient := imagekit.NewClient(\n\t\toption.WithPrivateKey("My Private Key"), // defaults to os.LookupEnv("IMAGEKIT_PRIVATE_KEY")\n\t\toption.WithPassword("My Password"), // defaults to os.LookupEnv("OPTIONAL_IMAGEKIT_IGNORES_THIS")\n\t)\n\tresponse, err := client.Files.Upload(context.TODO(), imagekit.FileUploadParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte("https://www.example.com/public-url.jpg"))),\n\t\tFileName: "file-name.jpg",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", response.VideoCodec)\n}\n\n```\n\n### Request fields\n\nAll request parameters are wrapped in a generic `Field` type,\nwhich we use to distinguish zero values from null or omitted fields.\n\nThis prevents accidentally sending a zero value if you forget a required parameter,\nand enables explicitly sending `null`, `false`, `\'\'`, or `0` on optional parameters.\nAny field not specified is not sent.\n\nTo construct fields with values, use the helpers `String()`, `Int()`, `Float()`, or most commonly, the generic `F[T]()`.\nTo send a null, use `Null[T]()`, and to send a nonconforming value, use `Raw[T](any)`. For example:\n\n```go\nparams := FooParams{\n\tName: SDK_PackageName.F("hello"),\n\n\t// Explicitly send `"description": null`\n\tDescription: SDK_PackageName.Null[string](),\n\n\tPoint: SDK_PackageName.F(SDK_PackageName.Point{\n\t\tX: SDK_PackageName.Int(0),\n\t\tY: SDK_PackageName.Int(1),\n\n\t\t// In cases where the API specifies a given type,\n\t\t// but you want to send something else, use `Raw`:\n\t\tZ: SDK_PackageName.Raw[int64](0.01), // sends a float\n\t}),\n}\n```\n\n### Response objects\n\nAll fields in response structs are value types (not pointers or wrappers).\n\nIf a given field is `null`, not present, or invalid, the corresponding field\nwill simply be its zero value.\n\nAll response structs also include a special `JSON` field, containing more detailed\ninformation about each property, which you can use like so:\n\n```go\nif res.Name == "" {\n\t// true if `"name"` is either not present or explicitly null\n\tres.JSON.Name.IsNull()\n\n\t// true if the `"name"` key was not present in the response JSON at all\n\tres.JSON.Name.IsMissing()\n\n\t// When the API returns data that cannot be coerced to the expected type:\n\tif res.JSON.Name.IsInvalid() {\n\t\traw := res.JSON.Name.Raw()\n\n\t\tlegacyName := struct{\n\t\t\tFirst string `json:"first"`\n\t\t\tLast string `json:"last"`\n\t\t}{}\n\t\tjson.Unmarshal([]byte(raw), &legacyName)\n\t\tname = legacyName.First + " " + legacyName.Last\n\t}\n}\n```\n\nThese `.JSON` structs also include an `Extras` map containing\nany properties in the json response that were not specified\nin the struct. This can be useful for API features not yet\npresent in the SDK.\n\n```go\nbody := res.JSON.ExtraFields["my_unexpected_field"].Raw()\n```\n\n### RequestOptions\n\nThis library uses the functional options pattern. Functions defined in the\n`SDK_PackageOptionName` package return a `RequestOption`, which is a closure that mutates a\n`RequestConfig`. These options can be supplied to the client or at individual\nrequests. For example:\n\n```go\nclient := SDK_PackageName.SDK_ClientInitializerName(\n\t// Adds a header to every request made by the client\n\tSDK_PackageOptionName.WithHeader("X-Some-Header", "custom_header_info"),\n)\n\nclient.Files.Upload(context.TODO(), ...,\n\t// Override the header\n\tSDK_PackageOptionName.WithHeader("X-Some-Header", "some_other_custom_header_info"),\n\t// Add an undocumented field to the request body, using sjson syntax\n\tSDK_PackageOptionName.WithJSONSet("some.json.path", map[string]string{"my": "object"}),\n)\n```\n\nSee the [full list of request options](https://pkg.go.dev/github.com/imagekit-developer/imagekit-go/SDK_PackageOptionName).\n\n### Pagination\n\nThis library provides some conveniences for working with paginated list endpoints.\n\nYou can use `.ListAutoPaging()` methods to iterate through items across all pages:\n\n\n\nOr you can use simple `.List()` methods to fetch a single page and receive a standard response object\nwith additional helper methods like `.GetNextPage()`, e.g.:\n\n\n\n### Errors\n\nWhen the API returns a non-success status code, we return an error with type\n`*SDK_PackageName.Error`. This contains the `StatusCode`, `*http.Request`, and\n`*http.Response` values of the request, as well as the JSON of the error body\n(much like other response objects in the SDK).\n\nTo handle errors, we recommend that you use the `errors.As` pattern:\n\n```go\n_, err := client.Files.Upload(context.TODO(), imagekit.FileUploadParams{\n\tFile: io.Reader(bytes.NewBuffer([]byte("https://www.example.com/public-url.jpg"))),\n\tFileName: "file-name.jpg",\n})\nif err != nil {\n\tvar apierr *imagekit.Error\n\tif errors.As(err, &apierr) {\n\t\tprintln(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request\n\t\tprintln(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response\n\t}\n\tpanic(err.Error()) // GET "/api/v1/files/upload": 400 Bad Request { ... }\n}\n```\n\nWhen other errors occur, they are returned unwrapped; for example,\nif HTTP transport fails, you might receive `*url.Error` wrapping `*net.OpError`.\n\n### Timeouts\n\nRequests do not time out by default; use context to configure a timeout for a request lifecycle.\n\nNote that if a request is [retried](#retries), the context timeout does not start over.\nTo set a per-retry timeout, use `SDK_PackageOptionName.WithRequestTimeout()`.\n\n```go\n// This sets the timeout for the request, including all the retries.\nctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\ndefer cancel()\nclient.Files.Upload(\n\tctx,\n\timagekit.FileUploadParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte("https://www.example.com/public-url.jpg"))),\n\t\tFileName: "file-name.jpg",\n\t},\n\t// This sets the per-retry timeout\n\toption.WithRequestTimeout(20*time.Second),\n)\n```\n\n### File uploads\n\nRequest parameters that correspond to file uploads in multipart requests are typed as\n`param.Field[io.Reader]`. The contents of the `io.Reader` will by default be sent as a multipart form\npart with the file name of "anonymous_file" and content-type of "application/octet-stream".\n\nThe file name and content-type can be customized by implementing `Name() string` or `ContentType()\nstring` on the run-time type of `io.Reader`. Note that `os.File` implements `Name() string`, so a\nfile returned by `os.Open` will be sent with the file name on disk.\n\nWe also provide a helper `SDK_PackageName.FileParam(reader io.Reader, filename string, contentType string)`\nwhich can be used to wrap any `io.Reader` with the appropriate file name and content type.\n\n```go\n// A file from the file system\nfile, err := os.Open("/path/to/file")\nimagekit.FileUploadParams{\n\tFile: file,\n\tFileName: "fileName",\n}\n\n// A file from a string\nimagekit.FileUploadParams{\n\tFile: strings.NewReader("my file contents"),\n\tFileName: "fileName",\n}\n\n// With a custom filename and contentType\nimagekit.FileUploadParams{\n\tFile: imagekit.NewFile(strings.NewReader(`{"hello": "foo"}`), "file.go", "application/json"),\n\tFileName: "fileName",\n}\n```\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nWe retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit,\nand >=500 Internal errors.\n\nYou can use the `WithMaxRetries` option to configure or disable this:\n\n```go\n// Configure the default for all requests:\nclient := imagekit.NewClient(\n\toption.WithMaxRetries(0), // default is 2\n)\n\n// Override per-request:\nclient.Files.Upload(\n\tcontext.TODO(),\n\timagekit.FileUploadParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte("https://www.example.com/public-url.jpg"))),\n\t\tFileName: "file-name.jpg",\n\t},\n\toption.WithMaxRetries(5),\n)\n```\n\n\n### Accessing raw response data (e.g. response headers)\n\nYou can access the raw HTTP response data by using the `option.WithResponseInto()` request option. This is useful when\nyou need to examine response headers, status codes, or other details.\n\n```go\n// Create a variable to store the HTTP response\nvar response *http.Response\nresponse, err := client.Files.Upload(\n\tcontext.TODO(),\n\timagekit.FileUploadParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte("https://www.example.com/public-url.jpg"))),\n\t\tFileName: "file-name.jpg",\n\t},\n\toption.WithResponseInto(&response),\n)\nif err != nil {\n\t// handle error\n}\nfmt.Printf("%+v\\n", response)\n\nfmt.Printf("Status Code: %d\\n", response.StatusCode)\nfmt.Printf("Headers: %+#v\\n", response.Header)\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.Get`, `client.Post`, and other HTTP verbs.\n`RequestOptions` on the client, such as retries, will be respected when making these requests.\n\n```go\nvar (\n // params can be an io.Reader, a []byte, an encoding/json serializable object,\n // or a "…Params" struct defined in this library.\n params map[string]interface{}\n\n // result can be an []byte, *http.Response, a encoding/json deserializable object,\n // or a model defined in this library.\n result *http.Response\n)\nerr := client.Post(context.Background(), "/unspecified", params, &result)\nif err != nil {\n …\n}\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use either the `SDK_PackageOptionName.WithQuerySet()`\nor the `SDK_PackageOptionName.WithJSONSet()` methods.\n\n```go\nparams := FooNewParams{\n ID: SDK_PackageName.F("id_xxxx"),\n Data: SDK_PackageName.F(FooNewParamsData{\n FirstName: SDK_PackageName.F("John"),\n }),\n}\nclient.Foo.New(context.Background(), params, SDK_PackageOptionName.WithJSONSet("data.last_name", "Doe"))\n```\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may either access the raw JSON of the response as a string\nwith `result.JSON.RawJSON()`, or get the raw JSON of a particular field on the result with\n`result.JSON.Foo.Raw()`.\n\nAny fields that are not present on the response struct will be saved and can be accessed by `result.JSON.ExtraFields()` which returns the extra fields as a `map[string]Field`.\n\n### Middleware\n\nWe provide `SDK_PackageOptionName.WithMiddleware` which applies the given\nmiddleware to requests.\n\n```go\nfunc Logger(req *http.Request, next SDK_PackageOptionName.MiddlewareNext) (res *http.Response, err error) {\n\t// Before the request\n\tstart := time.Now()\n\tLogReq(req)\n\n\t// Forward the request to the next handler\n\tres, err = next(req)\n\n\t// Handle stuff after the request\n\tend := time.Now()\n\tLogRes(res, err, start - end)\n\n return res, err\n}\n\nclient := SDK_PackageName.SDK_ClientInitializerName(\n\tSDK_PackageOptionName.WithMiddleware(Logger),\n)\n```\n\nWhen multiple middlewares are provided as variadic arguments, the middlewares\nare applied left to right. If `SDK_PackageOptionName.WithMiddleware` is given\nmultiple times, for example first in the client then the method, the\nmiddleware in the client will run first and the middleware given in the method\nwill run next.\n\nYou may also replace the default `http.Client` with\n`SDK_PackageOptionName.WithHTTPClient(client)`. Only one http client is\naccepted (this overwrites any previous client) and receives requests after any\nmiddleware has been applied.\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/imagekit-developer/imagekit-go/issues) with questions, bugs, or suggestions.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n', + }, + { + language: 'terraform', + content: + '# Image Kit Terraform Provider\n\nThe [Image Kit Terraform provider](https://registry.terraform.io/providers/stainless-sdks/imagekit/latest/docs) provides convenient access to\nthe [Image Kit REST API](https://imagekit.io/docs/api-reference) from Terraform.\n\n\n\n## Requirements\n\nThis provider requires Terraform CLI 1.0 or later. You can [install it for your system](https://developer.hashicorp.com/terraform/install)\non Hashicorp\'s website.\n\n## Usage\n\nAdd the following to your `main.tf` file:\n\n\n\n```hcl\n# Declare the provider and version\nterraform {\n required_providers {\n SDK_ProviderTypeName = {\n source = "stainless-sdks/imagekit"\n version = "~> 0.0.1"\n }\n }\n}\n\n# Initialize the provider\nprovider "imagekit" {\n # Your ImageKit private API key (starts with `private_`).\n You can find this in the [ImageKit dashboard](https://imagekit.io/dashboard/developer/api-keys).\n private_key = "My Private Key" # or set IMAGEKIT_PRIVATE_KEY env variable\n # ImageKit uses your API key as username and ignores the password. \n The SDK sets a dummy value. You can ignore this field.\n password = "My Password" # or set OPTIONAL_IMAGEKIT_IGNORES_THIS env variable\n # Your ImageKit webhook secret for verifying webhook signatures (starts with `whsec_`).\n You can find this in the [ImageKit dashboard](https://imagekit.io/dashboard/developer/webhooks).\n Only required if you\'re using webhooks.\n webhook_secret = "My Webhook Secret" # or set IMAGEKIT_WEBHOOK_SECRET env variable\n}\n\n# Configure a resource\nresource "imagekit_account_origin" "example_account_origin" {\n access_key = "AKIAIOSFODNN7EXAMPLE"\n bucket = "product-images"\n name = "US S3 Storage"\n secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"\n type = "S3"\n base_url_for_canonical_header = "https://cdn.example.com"\n include_canonical_header = false\n prefix = "raw-assets"\n}\n```\n\n\n\nInitialize your project by running `terraform init` in the directory.\n\nAdditional examples can be found in the [./examples](./examples) folder within this repository, and you can\nrefer to the full documentation on [the Terraform Registry](https://registry.terraform.io/providers/stainless-sdks/imagekit/latest/docs).\n\n### Provider Options\nWhen you initialize the provider, the following options are supported. It is recommended to use environment variables for sensitive values like access tokens.\nIf an environment variable is provided, then the option does not need to be set in the terraform source.\n\n| Property | Environment variable | Required | Default value |\n| -------------- | -------------------------------- | -------- | -------------- |\n| private_key | `IMAGEKIT_PRIVATE_KEY` | true | — |\n| webhook_secret | `IMAGEKIT_WEBHOOK_SECRET` | false | — |\n| password | `OPTIONAL_IMAGEKIT_IGNORES_THIS` | false | `"do_not_set"` |\n\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/stainless-sdks/imagekit-terraform/issues) with questions, bugs, or suggestions.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n', + }, + { + language: 'typescript', + content: + "# Image Kit TypeScript API Library\n\n[![NPM version](https://img.shields.io/npm/v/@imagekit/nodejs.svg?label=npm%20(stable))](https://npmjs.org/package/@imagekit/nodejs) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/@imagekit/nodejs)\n\nThis library provides convenient access to the Image Kit REST API from server-side TypeScript or JavaScript.\n\n\n\nThe REST API documentation can be found on [imagekit.io](https://imagekit.io/docs/api-reference). The full API of this library can be found in [api.md](api.md).\n\n\n\n## MCP Server\n\nUse the Image Kit MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40imagekit%2Fapi-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBpbWFnZWtpdC9hcGktbWNwIl0sImVudiI6eyJJTUFHRUtJVF9QUklWQVRFX0tFWSI6Ik15IFByaXZhdGUgS2V5IiwiT1BUSU9OQUxfSU1BR0VLSVRfSUdOT1JFU19USElTIjoiTXkgUGFzc3dvcmQiLCJJTUFHRUtJVF9XRUJIT09LX1NFQ1JFVCI6Ik15IFdlYmhvb2sgU2VjcmV0In19)\n[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40imagekit%2Fapi-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40imagekit%2Fapi-mcp%22%5D%2C%22env%22%3A%7B%22IMAGEKIT_PRIVATE_KEY%22%3A%22My%20Private%20Key%22%2C%22OPTIONAL_IMAGEKIT_IGNORES_THIS%22%3A%22My%20Password%22%2C%22IMAGEKIT_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Installation\n\n```sh\nnpm install @imagekit/nodejs\n```\n\n\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n\n```js\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst response = await client.files.upload({\n file: fs.createReadStream('path/to/file'),\n fileName: 'file-name.jpg',\n});\n\nconsole.log(response.videoCodec);\n```\n\n\n\n### Request & Response types\n\nThis library includes TypeScript definitions for all request params and response fields. You may import and use them like so:\n\n\n```ts\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n privateKey: process.env['IMAGEKIT_PRIVATE_KEY'], // This is the default and can be omitted\n password: process.env['OPTIONAL_IMAGEKIT_IGNORES_THIS'], // This is the default and can be omitted\n});\n\nconst params: ImageKit.FileUploadParams = {\n file: fs.createReadStream('path/to/file'),\n fileName: 'file-name.jpg',\n};\nconst response: ImageKit.FileUploadResponse = await client.files.upload(params);\n```\n\nDocumentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.\n\n## File uploads\n\nRequest parameters that correspond to file uploads can be passed in many different forms:\n- `File` (or an object with the same structure)\n- a `fetch` `Response` (or an object with the same structure)\n- an `fs.ReadStream`\n- the return value of our `toFile` helper\n\n```ts\nimport fs from 'fs';\nimport ImageKit, { toFile } from '@imagekit/nodejs';\n\nconst client = new ImageKit();\n\n// If you have access to Node `fs` we recommend using `fs.createReadStream()`:\nawait client.files.upload({ file: fs.createReadStream('/path/to/file'), fileName: 'fileName' });\n\n// Or if you have the web `File` API you can pass a `File` instance:\nawait client.files.upload({ file: new File(['my bytes'], 'file'), fileName: 'fileName' });\n\n// You can also pass a `fetch` `Response`:\nawait client.files.upload({ file: await fetch('https://somesite/file'), fileName: 'fileName' });\n\n// Finally, if none of the above are convenient, you can use our `toFile` helper:\nawait client.files.upload({\n file: await toFile(Buffer.from('my bytes'), 'file'),\n fileName: 'fileName',\n});\nawait client.files.upload({\n file: await toFile(new Uint8Array([0, 1, 2]), 'file'),\n fileName: 'fileName',\n});\n```\n\n\n\n## Handling errors\n\nWhen the library is unable to connect to the API,\nor if the API returns a non-success status code (i.e., 4xx or 5xx response),\na subclass of `APIError` will be thrown:\n\n\n```ts\nconst response = await client.files\n .upload({ file: fs.createReadStream('path/to/file'), fileName: 'file-name.jpg' })\n .catch(async (err) => {\n if (err instanceof ImageKit.APIError) {\n console.log(err.status); // 400\n console.log(err.name); // BadRequestError\n console.log(err.headers); // {server: 'nginx', ...}\n } else {\n throw err;\n }\n });\n```\n\nError codes are as follows:\n\n| Status Code | Error Type |\n| ----------- | -------------------------- |\n| 400 | `BadRequestError` |\n| 401 | `AuthenticationError` |\n| 403 | `PermissionDeniedError` |\n| 404 | `NotFoundError` |\n| 422 | `UnprocessableEntityError` |\n| 429 | `RateLimitError` |\n| >=500 | `InternalServerError` |\n| N/A | `APIConnectionError` |\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,\n429 Rate Limit, and >=500 Internal errors will all be retried by default.\n\nYou can use the `maxRetries` option to configure or disable this:\n\n\n```js\n// Configure the default for all requests:\nconst client = new ImageKit({\n maxRetries: 0, // default is 2\n});\n\n// Or, configure per-request:\nawait client.files.upload({ file: fs.createReadStream('path/to/file'), fileName: 'file-name.jpg' }, {\n maxRetries: 5,\n});\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default. You can configure this with a `timeout` option:\n\n\n```ts\n// Configure the default for all requests:\nconst client = new ImageKit({\n timeout: 20 * 1000, // 20 seconds (default is 1 minute)\n});\n\n// Override per-request:\nawait client.files.upload({ file: fs.createReadStream('path/to/file'), fileName: 'file-name.jpg' }, {\n timeout: 5 * 1000,\n});\n```\n\nOn timeout, an `APIConnectionTimeoutError` is thrown.\n\nNote that requests which time out will be [retried twice by default](#retries).\n\n\n\n\n\n## Advanced Usage\n\n### Accessing raw Response data (e.g., headers)\n\nThe \"raw\" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return.\nThis method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.\n\nYou can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.\nUnlike `.asResponse()` this method consumes the body, returning once it is parsed.\n\n\n```ts\nconst client = new ImageKit();\n\nconst response = await client.files\n .upload({ file: fs.createReadStream('path/to/file'), fileName: 'file-name.jpg' })\n .asResponse();\nconsole.log(response.headers.get('X-My-Header'));\nconsole.log(response.statusText); // access the underlying Response object\n\nconst { data: response, response: raw } = await client.files\n .upload({ file: fs.createReadStream('path/to/file'), fileName: 'file-name.jpg' })\n .withResponse();\nconsole.log(raw.headers.get('X-My-Header'));\nconsole.log(response.videoCodec);\n```\n\n### Logging\n\n> [!IMPORTANT]\n> All log messages are intended for debugging only. The format and content of log messages\n> may change between releases.\n\n#### Log levels\n\nThe log level can be configured in two ways:\n\n1. Via the `IMAGE_KIT_LOG` environment variable\n2. Using the `logLevel` client option (overrides the environment variable if set)\n\n```ts\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n logLevel: 'debug', // Show all log messages\n});\n```\n\nAvailable log levels, from most to least verbose:\n\n- `'debug'` - Show debug messages, info, warnings, and errors\n- `'info'` - Show info messages, warnings, and errors\n- `'warn'` - Show warnings and errors (default)\n- `'error'` - Show only errors\n- `'off'` - Disable all logging\n\nAt the `'debug'` level, all HTTP requests and responses are logged, including headers and bodies.\nSome authentication-related headers are redacted, but sensitive data in request and response bodies\nmay still be visible.\n\n#### Custom logger\n\nBy default, this library logs to `globalThis.console`. You can also provide a custom logger.\nMost logging libraries are supported, including [pino](https://www.npmjs.com/package/pino), [winston](https://www.npmjs.com/package/winston), [bunyan](https://www.npmjs.com/package/bunyan), [consola](https://www.npmjs.com/package/consola), [signale](https://www.npmjs.com/package/signale), and [@std/log](https://jsr.io/@std/log). If your logger doesn't work, please open an issue.\n\nWhen providing a custom logger, the `logLevel` option still controls which messages are emitted, messages\nbelow the configured level will not be sent to your logger.\n\n```ts\nimport ImageKit from '@imagekit/nodejs';\nimport pino from 'pino';\n\nconst logger = pino();\n\nconst client = new ImageKit({\n logger: logger.child({ name: 'ImageKit' }),\n logLevel: 'debug', // Send all messages to pino, allowing it to filter\n});\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs.\nOptions on the client, such as retries, will be respected when making these requests.\n\n```ts\nawait client.post('/some/path', {\n body: { some_prop: 'foo' },\n query: { some_query_arg: 'bar' },\n});\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented\nparameter. This library doesn't validate at runtime that the request matches the type, so any extra values you\nsend will be sent as-is.\n\n```ts\nclient.files.upload({\n // ...\n // @ts-expect-error baz is not yet public\n baz: 'undocumented option',\n});\n```\n\nFor requests with the `GET` verb, any extra params will be in the query, all other requests will send the\nextra param in the body.\n\nIf you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may access the response object with `// @ts-expect-error` on\nthe response object, or cast the response object to the requisite type. Like the request params, we do not\nvalidate or strip extra properties from the response from the API.\n\n### Customizing the fetch client\n\nBy default, this library expects a global `fetch` function is defined.\n\nIf you want to use a different `fetch` function, you can either polyfill the global:\n\n```ts\nimport fetch from 'my-fetch';\n\nglobalThis.fetch = fetch;\n```\n\nOr pass it to the client:\n\n```ts\nimport ImageKit from '@imagekit/nodejs';\nimport fetch from 'my-fetch';\n\nconst client = new ImageKit({ fetch });\n```\n\n### Fetch options\n\nIf you want to set custom `fetch` options without overriding the `fetch` function, you can provide a `fetchOptions` object when instantiating the client or making a request. (Request-specific options override client options.)\n\n```ts\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n fetchOptions: {\n // `RequestInit` options\n },\n});\n```\n\n#### Configuring proxies\n\nTo modify proxy behavior, you can provide custom `fetchOptions` that add runtime-specific proxy\noptions to requests:\n\n **Node** [[docs](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md#example---proxyagent-with-fetch)]\n\n```ts\nimport ImageKit from '@imagekit/nodejs';\nimport * as undici from 'undici';\n\nconst proxyAgent = new undici.ProxyAgent('http://localhost:8888');\nconst client = new ImageKit({\n fetchOptions: {\n dispatcher: proxyAgent,\n },\n});\n```\n\n **Bun** [[docs](https://bun.sh/guides/http/proxy)]\n\n```ts\nimport ImageKit from '@imagekit/nodejs';\n\nconst client = new ImageKit({\n fetchOptions: {\n proxy: 'http://localhost:8888',\n },\n});\n```\n\n **Deno** [[docs](https://docs.deno.com/api/deno/~/Deno.createHttpClient)]\n\n```ts\nimport ImageKit from 'npm:@imagekit/nodejs';\n\nconst httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });\nconst client = new ImageKit({\n fetchOptions: {\n client: httpClient,\n },\n});\n```\n\n## Frequently Asked Questions\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/imagekit-developer/imagekit-nodejs/issues) with questions, bugs, or suggestions.\n\n## Requirements\n\nTypeScript >= 4.9 is supported.\n\nThe following runtimes are supported:\n\n- Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more)\n- Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.\n- Deno v1.28.0 or higher.\n- Bun 1.0 or later.\n- Cloudflare Workers.\n- Vercel Edge Runtime.\n- Jest 28 or greater with the `\"node\"` environment (`\"jsdom\"` is not supported at this time).\n- Nitro v2.6 or greater.\n\nNote that React Native is not supported at this time.\n\nIf you are interested in other runtime environments, please open or upvote an issue on GitHub.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n", + }, + { + language: 'ruby', + content: + '# Image Kit Ruby API library\n\nThe Image Kit Ruby library provides convenient access to the Image Kit REST API from any Ruby 3.2.0+ application. It ships with comprehensive types & docstrings in Yard, RBS, and RBI – [see below](https://github.com/imagekit-developer/imagekit-ruby#Sorbet) for usage with Sorbet. The standard library\'s `net/http` is used as the HTTP transport, with connection pooling via the `connection_pool` gem.\n\n\n\n\n\n## MCP Server\n\nUse the Image Kit MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40imagekit%2Fapi-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBpbWFnZWtpdC9hcGktbWNwIl0sImVudiI6eyJJTUFHRUtJVF9QUklWQVRFX0tFWSI6Ik15IFByaXZhdGUgS2V5IiwiT1BUSU9OQUxfSU1BR0VLSVRfSUdOT1JFU19USElTIjoiTXkgUGFzc3dvcmQiLCJJTUFHRUtJVF9XRUJIT09LX1NFQ1JFVCI6Ik15IFdlYmhvb2sgU2VjcmV0In19)\n[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40imagekit%2Fapi-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40imagekit%2Fapi-mcp%22%5D%2C%22env%22%3A%7B%22IMAGEKIT_PRIVATE_KEY%22%3A%22My%20Private%20Key%22%2C%22OPTIONAL_IMAGEKIT_IGNORES_THIS%22%3A%22My%20Password%22%2C%22IMAGEKIT_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Documentation\n\nDocumentation for releases of this gem can be found [on RubyDoc](https://gemdocs.org/gems/imagekitio).\n\nThe REST API documentation can be found on [imagekit.io](https://imagekit.io/docs/api-reference).\n\n## Installation\n\nTo use this gem, install via Bundler by adding the following to your application\'s `Gemfile`:\n\n\n\n```ruby\ngem "imagekitio", "~> 0.0.1"\n```\n\n\n\n## Usage\n\n```ruby\nrequire "bundler/setup"\nrequire "imagekitio"\n\nimage_kit = Imagekitio::Client.new(\n private_key: ENV["IMAGEKIT_PRIVATE_KEY"], # This is the default and can be omitted\n password: ENV["OPTIONAL_IMAGEKIT_IGNORES_THIS"] # This is the default and can be omitted\n)\n\nresponse = image_kit.files.upload(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg"\n)\n\nputs(response.videoCodec)\n```\n\n\n\n\n\n### File uploads\n\nRequest parameters that correspond to file uploads can be passed as raw contents, a [`Pathname`](https://rubyapi.org/3.2/o/pathname) instance, [`StringIO`](https://rubyapi.org/3.2/o/stringio), or more.\n\n```ruby\nrequire "pathname"\n\n# Use `Pathname` to send the filename and/or avoid paging a large file into memory:\nresponse = image_kit.files.upload(file: Pathname("/path/to/file"))\n\n# Alternatively, pass file contents or a `StringIO` directly:\nresponse = image_kit.files.upload(file: File.read("/path/to/file"))\n\n# Or, to control the filename and/or content type:\nfile = Imagekitio::FilePart.new(File.read("/path/to/file"), filename: "/path/to/file", content_type: "…")\nresponse = image_kit.files.upload(file: file)\n\nputs(response.videoCodec)\n```\n\nNote that you can also pass a raw `IO` descriptor, but this disables retries, as the library can\'t be sure if the descriptor is a file or pipe (which cannot be rewound).\n\n### Handling errors\n\nWhen the library is unable to connect to the API, or if the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of `Imagekitio::Errors::APIError` will be thrown:\n\n```ruby\nbegin\n file = image_kit.files.upload(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg"\n )\nrescue Imagekitio::Errors::APIConnectionError => e\n puts("The server could not be reached")\n puts(e.cause) # an underlying Exception, likely raised within `net/http`\nrescue Imagekitio::Errors::RateLimitError => e\n puts("A 429 status code was received; we should back off a bit.")\nrescue Imagekitio::Errors::APIStatusError => e\n puts("Another non-200-range status code was received")\n puts(e.status)\nend\n```\n\nError codes are as follows:\n\n| Cause | Error Type |\n| ---------------- | -------------------------- |\n| HTTP 400 | `BadRequestError` |\n| HTTP 401 | `AuthenticationError` |\n| HTTP 403 | `PermissionDeniedError` |\n| HTTP 404 | `NotFoundError` |\n| HTTP 409 | `ConflictError` |\n| HTTP 422 | `UnprocessableEntityError` |\n| HTTP 429 | `RateLimitError` |\n| HTTP >= 500 | `InternalServerError` |\n| Other HTTP error | `APIStatusError` |\n| Timeout | `APITimeoutError` |\n| Network error | `APIConnectionError` |\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\n\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts will all be retried by default.\n\nYou can use the `max_retries` option to configure or disable this:\n\n```ruby\n# Configure the default for all requests:\nimage_kit = Imagekitio::Client.new(\n max_retries: 0 # default is 2\n)\n\n# Or, configure per-request:\nimage_kit.files.upload(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg",\n request_options: {max_retries: 5}\n)\n```\n\n### Timeouts\n\nBy default, requests will time out after 60 seconds. You can use the timeout option to configure or disable this:\n\n```ruby\n# Configure the default for all requests:\nimage_kit = Imagekitio::Client.new(\n timeout: nil # default is 60\n)\n\n# Or, configure per-request:\nimage_kit.files.upload(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg",\n request_options: {timeout: 5}\n)\n```\n\nOn timeout, `Imagekitio::Errors::APITimeoutError` is raised.\n\nNote that requests that time out are retried by default.\n\n## Advanced concepts\n\n### BaseModel\n\nAll parameter and response objects inherit from `Imagekitio::Internal::Type::BaseModel`, which provides several conveniences, including:\n\n1. All fields, including unknown ones, are accessible with `obj[:prop]` syntax, and can be destructured with `obj => {prop: prop}` or pattern-matching syntax.\n\n2. Structural equivalence for equality; if two API calls return the same values, comparing the responses with == will return true.\n\n3. Both instances and the classes themselves can be pretty-printed.\n\n4. Helpers such as `#to_h`, `#deep_to_h`, `#to_json`, and `#to_yaml`.\n\n### Making custom or undocumented requests\n\n#### Undocumented properties\n\nYou can send undocumented parameters to any endpoint, and read undocumented response properties, like so:\n\nNote: the `extra_` parameters of the same name overrides the documented parameters.\n\n```ruby\nresponse =\n image_kit.files.upload(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg",\n request_options: {\n extra_query: {my_query_parameter: value},\n extra_body: {my_body_parameter: value},\n extra_headers: {"my-header": value}\n }\n )\n\nputs(response[:my_undocumented_property])\n```\n\n#### Undocumented request params\n\nIf you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` under the `request_options:` parameter when making a request, as seen in the examples above.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints while retaining the benefit of auth, retries, and so on, you can make requests using `client.request`, like so:\n\n```ruby\nresponse = client.request(\n method: :post,\n path: \'/undocumented/endpoint\',\n query: {"dog": "woof"},\n headers: {"useful-header": "interesting-value"},\n body: {"hello": "world"}\n)\n```\n\n### Concurrency & connection pooling\n\nThe `Imagekitio::Client` instances are threadsafe, but are only are fork-safe when there are no in-flight HTTP requests.\n\nEach instance of `Imagekitio::Client` has its own HTTP connection pool with a default size of 99. As such, we recommend instantiating the client once per application in most settings.\n\nWhen all available connections from the pool are checked out, requests wait for a new connection to become available, with queue time counting towards the request timeout.\n\nUnless otherwise specified, other classes in the SDK do not have locks protecting their underlying data structure.\n\n## Sorbet\n\nThis library provides comprehensive [RBI](https://sorbet.org/docs/rbi) definitions, and has no dependency on sorbet-runtime.\n\nYou can provide typesafe request parameters like so:\n\n```ruby\nimage_kit.files.upload(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg"\n)\n```\n\nOr, equivalently:\n\n```ruby\n# Hashes work, but are not typesafe:\nimage_kit.files.upload(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg"\n)\n\n# You can also splat a full Params class:\nparams = Imagekitio::FileUploadParams.new(\n file: StringIO.new("https://www.example.com/public-url.jpg"),\n file_name: "file-name.jpg"\n)\nimage_kit.files.upload(**params)\n```\n\n### Enums\n\nSince this library does not depend on `sorbet-runtime`, it cannot provide [`T::Enum`](https://sorbet.org/docs/tenum) instances. Instead, we provide "tagged symbols" instead, which is always a primitive at runtime:\n\n```ruby\n# :all\nputs(Imagekitio::AssetListParams::FileType::ALL)\n\n# Revealed type: `T.all(Imagekitio::AssetListParams::FileType, Symbol)`\nT.reveal_type(Imagekitio::AssetListParams::FileType::ALL)\n```\n\nEnum parameters have a "relaxed" type, so you can either pass in enum constants or their literal value:\n\n```ruby\n# Using the enum constants preserves the tagged type information:\nimage_kit.assets.list(\n file_type: Imagekitio::AssetListParams::FileType::ALL,\n # …\n)\n\n# Literal values are also permissible:\nimage_kit.assets.list(\n file_type: :all,\n # …\n)\n```\n\n## Versioning\n\nThis package follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions. As the library is in initial development and has a major version of `0`, APIs may change at any time.\n\nThis package considers improvements to the (non-runtime) `*.rbi` and `*.rbs` type definitions to be non-breaking changes.\n\n## Requirements\n\nRuby 3.2.0 or higher.\n\n## Contributing\n\nSee [the contributing documentation](https://github.com/imagekit-developer/imagekit-ruby/tree/master/CONTRIBUTING.md).\n', + }, + { + language: 'java', + content: + '# Image Kit Java API Library\n\n\n[![Maven Central](https://img.shields.io/maven-central/v/com.imagekit.api/image-kit-java)](https://central.sonatype.com/artifact/com.imagekit.api/image-kit-java/0.0.1)\n[![javadoc](https://javadoc.io/badge2/com.imagekit.api/image-kit-java/0.0.1/javadoc.svg)](https://javadoc.io/doc/com.imagekit.api/image-kit-java/0.0.1)\n\n\nThe Image Kit Java SDK provides convenient access to the [Image Kit REST API](https://imagekit.io/docs/api-reference) from applications written in Java.\n\n\n\n\n\n## MCP Server\n\nUse the Image Kit MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40imagekit%2Fapi-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBpbWFnZWtpdC9hcGktbWNwIl0sImVudiI6eyJJTUFHRUtJVF9QUklWQVRFX0tFWSI6Ik15IFByaXZhdGUgS2V5IiwiT1BUSU9OQUxfSU1BR0VLSVRfSUdOT1JFU19USElTIjoiTXkgUGFzc3dvcmQiLCJJTUFHRUtJVF9XRUJIT09LX1NFQ1JFVCI6Ik15IFdlYmhvb2sgU2VjcmV0In19)\n[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40imagekit%2Fapi-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40imagekit%2Fapi-mcp%22%5D%2C%22env%22%3A%7B%22IMAGEKIT_PRIVATE_KEY%22%3A%22My%20Private%20Key%22%2C%22OPTIONAL_IMAGEKIT_IGNORES_THIS%22%3A%22My%20Password%22%2C%22IMAGEKIT_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\nThe REST API documentation can be found on [imagekit.io](https://imagekit.io/docs/api-reference). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.imagekit.api/image-kit-java/0.0.1).\n\n## Installation\n\n### Gradle\n\n~~~kotlin\nimplementation("com.imagekit.api:image-kit-java:0.0.1")\n~~~\n\n### Maven\n\n~~~xml\n\n com.imagekit.api\n image-kit-java\n 0.0.1\n\n~~~\n\n## Requirements\n\nThis library requires Java 8 or later.\n\n## Usage\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.io.ByteArrayInputStream;\n\n// Configures using the `imagekit.imagekitPrivateKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties\n// Or configures using the `IMAGEKIT_PRIVATE_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables\nImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\nFileUploadParams params = FileUploadParams.builder()\n .file(new ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes()))\n .fileName("file-name.jpg")\n .build();\nFileUploadResponse response = client.files().upload(params);\n```\n\n## Client configuration\n\nConfigure the client using system properties or environment variables:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\n\n// Configures using the `imagekit.imagekitPrivateKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties\n// Or configures using the `IMAGEKIT_PRIVATE_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables\nImageKitClient client = ImageKitOkHttpClient.fromEnv();\n```\n\nOr manually:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n .privateKey("My Private Key")\n .password("My Password")\n .build();\n```\n\nOr using a combination of the two approaches:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n // Configures using the `imagekit.imagekitPrivateKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties\n // Or configures using the `IMAGEKIT_PRIVATE_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables\n .fromEnv()\n .privateKey("My Private Key")\n .build();\n```\n\nSee this table for the available options:\n\n| Setter | System property | Environment variable | Required | Default value |\n| --------------- | -------------------------------------- | -------------------------------- | -------- | --------------------------- |\n| `privateKey` | `imagekit.imagekitPrivateKey` | `IMAGEKIT_PRIVATE_KEY` | true | - |\n| `password` | `imagekit.optionalImagekitIgnoresThis` | `OPTIONAL_IMAGEKIT_IGNORES_THIS` | false | `"do_not_set"` |\n| `webhookSecret` | `imagekit.imagekitWebhookSecret` | `IMAGEKIT_WEBHOOK_SECRET` | false | - |\n| `baseUrl` | `imagekit.baseUrl` | `IMAGE_KIT_BASE_URL` | true | `"https://api.imagekit.io"` |\n\nSystem properties take precedence over environment variables.\n\n> [!TIP]\n> Don\'t create more than one client in the same application. Each client has a connection pool and\n> thread pools, which are more efficient to share between requests.\n\n### Modifying configuration\n\nTo temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\n\nImageKitClient clientWithOptions = client.withOptions(optionsBuilder -> {\n optionsBuilder.baseUrl("https://example.com");\n optionsBuilder.maxRetries(42);\n});\n```\n\nThe `withOptions()` method does not affect the original client or service.\n\n## Requests and responses\n\nTo send a request to the Image Kit API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class.\n\nFor example, `client.files().upload(...)` should be called with an instance of `FileUploadParams`, and it will return an instance of `FileUploadResponse`.\n\n## Immutability\n\nEach class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it.\n\nEach class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy.\n\nBecause each class is immutable, builder modification will _never_ affect already built class instances.\n\n## Asynchronous execution\n\nThe default client is synchronous. To switch to asynchronous execution, call the `async()` method:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.io.ByteArrayInputStream;\nimport java.util.concurrent.CompletableFuture;\n\n// Configures using the `imagekit.imagekitPrivateKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties\n// Or configures using the `IMAGEKIT_PRIVATE_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables\nImageKitClient client = ImageKitOkHttpClient.fromEnv();\n\nFileUploadParams params = FileUploadParams.builder()\n .file(new ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes()))\n .fileName("file-name.jpg")\n .build();\nCompletableFuture response = client.async().files().upload(params);\n```\n\nOr create an asynchronous client from the beginning:\n\n```java\nimport com.imagekit.api.client.ImageKitClientAsync;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync;\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.io.ByteArrayInputStream;\nimport java.util.concurrent.CompletableFuture;\n\n// Configures using the `imagekit.imagekitPrivateKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties\n// Or configures using the `IMAGEKIT_PRIVATE_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables\nImageKitClientAsync client = ImageKitOkHttpClientAsync.fromEnv();\n\nFileUploadParams params = FileUploadParams.builder()\n .file(new ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes()))\n .fileName("file-name.jpg")\n .build();\nCompletableFuture response = client.files().upload(params);\n```\n\nThe asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s.\n\n\n\n## File uploads\n\nThe SDK defines methods that accept files.\n\nTo upload a file, pass a [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html):\n\n```java\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.nio.file.Paths;\n\nFileUploadParams params = FileUploadParams.builder()\n .fileName("fileName")\n .file(Paths.get("/path/to/file"))\n .build();\nFileUploadResponse response = client.files().upload(params);\n```\n\nOr an arbitrary [`InputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html):\n\n```java\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.net.URL;\n\nFileUploadParams params = FileUploadParams.builder()\n .fileName("fileName")\n .file(new URL("https://example.com//path/to/file").openStream())\n .build();\nFileUploadResponse response = client.files().upload(params);\n```\n\nOr a `byte[]` array:\n\n```java\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\n\nFileUploadParams params = FileUploadParams.builder()\n .fileName("fileName")\n .file("content".getBytes())\n .build();\nFileUploadResponse response = client.files().upload(params);\n```\n\nNote that when passing a non-`Path` its filename is unknown so it will not be included in the request. To manually set a filename, pass a [`MultipartField`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt):\n\n```java\nimport com.imagekit.api.core.MultipartField;\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.io.InputStream;\nimport java.net.URL;\n\nFileUploadParams params = FileUploadParams.builder()\n .fileName("fileName")\n .file(MultipartField.builder()\n .value(new URL("https://example.com//path/to/file").openStream())\n .filename("/path/to/file")\n .build())\n .build();\nFileUploadResponse response = client.files().upload(params);\n```\n\n\n\n## Raw responses\n\nThe SDK defines methods that deserialize responses into instances of Java classes. However, these methods don\'t provide access to the response headers, status code, or the raw response body.\n\nTo access this data, prefix any HTTP method call on a client or service with `withRawResponse()`:\n\n```java\nimport com.imagekit.api.core.http.Headers;\nimport com.imagekit.api.core.http.HttpResponseFor;\nimport com.imagekit.api.models.files.FileUploadParams;\nimport com.imagekit.api.models.files.FileUploadResponse;\nimport java.io.ByteArrayInputStream;\n\nFileUploadParams params = FileUploadParams.builder()\n .file(new ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes()))\n .fileName("file-name.jpg")\n .build();\nHttpResponseFor response = client.files().withRawResponse().upload(params);\n\nint statusCode = response.statusCode();\nHeaders headers = response.headers();\n```\n\nYou can still deserialize the response into an instance of a Java class if needed:\n\n```java\nimport com.imagekit.api.models.files.FileUploadResponse;\n\nFileUploadResponse parsedResponse = response.parse();\n```\n\n## Error handling\n\nThe SDK throws custom unchecked exception types:\n\n- [`ImageKitServiceException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:\n\n | Status | Exception |\n | ------ | -------------------------------------------------- |\n | 400 | [`BadRequestException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/BadRequestException.kt) |\n | 401 | [`UnauthorizedException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnauthorizedException.kt) |\n | 403 | [`PermissionDeniedException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/PermissionDeniedException.kt) |\n | 404 | [`NotFoundException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/NotFoundException.kt) |\n | 422 | [`UnprocessableEntityException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnprocessableEntityException.kt) |\n | 429 | [`RateLimitException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/RateLimitException.kt) |\n | 5xx | [`InternalServerException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/InternalServerException.kt) |\n | others | [`UnexpectedStatusCodeException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnexpectedStatusCodeException.kt) |\n\n- [`ImageKitIoException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitIoException.kt): I/O networking errors.\n\n- [`ImageKitRetryableException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitRetryableException.kt): Generic error indicating a failure that could be retried by the client.\n\n- [`ImageKitInvalidDataException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that\'s supposed to be required, but the API unexpectedly omitted it from the response.\n\n- [`ImageKitException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.\n\n\n\n## Logging\n\nThe SDK uses the standard [OkHttp logging interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor).\n\nEnable logging by setting the `IMAGE_KIT_LOG` environment variable to `info`:\n\n```sh\nexport IMAGE_KIT_LOG=info\n```\n\nOr to `debug` for more verbose logging:\n\n```sh\nexport IMAGE_KIT_LOG=debug\n```\n\n## ProGuard and R8\n\nAlthough the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `image-kit-java-core` is published with a [configuration file](image-kit-java-core/src/main/resources/META-INF/proguard/image-kit-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage).\n\nProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.\n\n\n\n\n\n## Jackson\n\nThe SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.\n\nThe SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).\n\nIf the SDK threw an exception, but you\'re _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) or [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt).\n\n> [!CAUTION]\n> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.\n\nAlso note that there are bugs in older Jackson versions that can affect the SDK. We don\'t work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead.\n\n## Network options\n\n### Retries\n\nThe SDK automatically retries 2 times by default, with a short exponential backoff between requests.\n\nOnly the following error types are retried:\n- Connection errors (for example, due to a network connectivity problem)\n- 408 Request Timeout\n- 409 Conflict\n- 429 Rate Limit\n- 5xx Internal\n\nThe API may also explicitly instruct the SDK to retry or not retry a request.\n\nTo set a custom number of retries, configure the client using the `maxRetries` method:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n .fromEnv()\n .maxRetries(4)\n .build();\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default.\n\nTo set a custom timeout, configure the method call using the `timeout` method:\n\n```java\nimport com.imagekit.api.models.files.FileUploadResponse;\n\nFileUploadResponse response = client.files().upload(\n params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()\n);\n```\n\nOr configure the default for all method calls at the client level:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport java.time.Duration;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n .fromEnv()\n .timeout(Duration.ofSeconds(30))\n .build();\n```\n\n### Proxies\n\nTo route requests through a proxy, configure the client using the `proxy` method:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport java.net.InetSocketAddress;\nimport java.net.Proxy;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n .fromEnv()\n .proxy(new Proxy(\n Proxy.Type.HTTP, new InetSocketAddress(\n "https://example.com", 8080\n )\n ))\n .build();\n```\n\n### Connection pooling\n\nTo customize the underlying OkHttp connection pool, configure the client using the `maxIdleConnections` and `keepAliveDuration` methods:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\nimport java.time.Duration;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n .fromEnv()\n // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa.\n .maxIdleConnections(10)\n .keepAliveDuration(Duration.ofMinutes(2))\n .build();\n```\n\nIf both options are unset, OkHttp\'s default connection pool settings are used.\n\n### HTTPS\n\n> [!NOTE]\n> Most applications should not call these methods, and instead use the system defaults. The defaults include\n> special optimizations that can be lost if the implementations are modified.\n\nTo configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n .fromEnv()\n // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa.\n .sslSocketFactory(yourSSLSocketFactory)\n .trustManager(yourTrustManager)\n .hostnameVerifier(yourHostnameVerifier)\n .build();\n```\n\n\n\n### Custom HTTP client\n\nThe SDK consists of three artifacts:\n- `image-kit-java-core`\n - Contains core SDK logic\n - Does not depend on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`ImageKitClient`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClient.kt), [`ImageKitClientAsync`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsync.kt), [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt), and [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), all of which can work with any HTTP client\n- `image-kit-java-client-okhttp`\n - Depends on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) and [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt), which provide a way to construct [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt) and [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), respectively, using OkHttp\n- `image-kit-java`\n - Depends on and exposes the APIs of both `image-kit-java-core` and `image-kit-java-client-okhttp`\n - Does not have its own logic\n\nThis structure allows replacing the SDK\'s default HTTP client without pulling in unnecessary dependencies.\n\n#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html)\n\n> [!TIP]\n> Try the available [network options](#network-options) before replacing the default client.\n\nTo use a customized `OkHttpClient`:\n\n1. Replace your [`image-kit-java` dependency](#installation) with `image-kit-java-core`\n2. Copy `image-kit-java-client-okhttp`\'s [`OkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/OkHttpClient.kt) class into your code and customize it\n3. Construct [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt) or [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), similarly to [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) or [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt), using your customized client\n\n### Completely custom HTTP client\n\nTo use a completely custom HTTP client:\n\n1. Replace your [`image-kit-java` dependency](#installation) with `image-kit-java-core`\n2. Write a class that implements the [`HttpClient`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpClient.kt) interface\n3. Construct [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt) or [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), similarly to [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) or [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt), using your new client class\n\n## Undocumented API functionality\n\nThe SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.\n\n### Parameters\n\nTo set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:\n\n```java\nimport com.imagekit.api.core.JsonValue;\nimport com.imagekit.api.models.files.FileUploadParams;\n\nFileUploadParams params = FileUploadParams.builder()\n .putAdditionalHeader("Secret-Header", "42")\n .putAdditionalQueryParam("secret_query_param", "42")\n .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))\n .build();\n```\n\nThese can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.\n\nTo set undocumented parameters on _nested_ headers, query params, or body classes, call the `putAdditionalProperty` method on the nested class:\n\n```java\nimport com.imagekit.api.core.JsonValue;\nimport com.imagekit.api.models.files.FileUploadParams;\n\nFileUploadParams params = FileUploadParams.builder()\n .transformation(FileUploadParams.Transformation.builder()\n .putAdditionalProperty("secretProperty", JsonValue.from("42"))\n .build())\n .build();\n```\n\nThese properties can be accessed on the nested built object later using the `_additionalProperties()` method.\n\nTo set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt) object to its setter:\n\n```java\nimport com.imagekit.api.core.JsonValue;\nimport com.imagekit.api.models.files.FileUploadParams;\n\nFileUploadParams params = FileUploadParams.builder()\n .file(JsonValue.from(42))\n .fileName("file-name.jpg")\n .build();\n```\n\nThe most straightforward way to create a [`JsonValue`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt) is using its `from(...)` method:\n\n```java\nimport com.imagekit.api.core.JsonValue;\nimport java.util.List;\nimport java.util.Map;\n\n// Create primitive JSON values\nJsonValue nullValue = JsonValue.from(null);\nJsonValue booleanValue = JsonValue.from(true);\nJsonValue numberValue = JsonValue.from(42);\nJsonValue stringValue = JsonValue.from("Hello World!");\n\n// Create a JSON array value equivalent to `["Hello", "World"]`\nJsonValue arrayValue = JsonValue.from(List.of(\n "Hello", "World"\n));\n\n// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`\nJsonValue objectValue = JsonValue.from(Map.of(\n "a", 1,\n "b", 2\n));\n\n// Create an arbitrarily nested JSON equivalent to:\n// {\n// "a": [1, 2],\n// "b": [3, 4]\n// }\nJsonValue complexValue = JsonValue.from(Map.of(\n "a", List.of(\n 1, 2\n ),\n "b", List.of(\n 3, 4\n )\n));\n```\n\nNormally a `Builder` class\'s `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.\n\nTo forcibly omit a required parameter or property, pass [`JsonMissing`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt):\n\n```java\nimport com.imagekit.api.core.JsonMissing;\nimport com.imagekit.api.models.files.FileUploadParams;\n\nFileUploadParams params = FileUploadParams.builder()\n .fileName("fileName")\n .file(JsonMissing.of())\n .build();\n```\n\n### Response properties\n\nTo access undocumented response properties, call the `_additionalProperties()` method:\n\n```java\nimport com.imagekit.api.core.JsonValue;\nimport java.util.Map;\n\nMap additionalProperties = client.files().upload(params)._additionalProperties();\nJsonValue secretPropertyValue = additionalProperties.get("secretProperty");\n\nString result = secretPropertyValue.accept(new JsonValue.Visitor<>() {\n @Override\n public String visitNull() {\n return "It\'s null!";\n }\n\n @Override\n public String visitBoolean(boolean value) {\n return "It\'s a boolean!";\n }\n\n @Override\n public String visitNumber(Number value) {\n return "It\'s a number!";\n }\n\n // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`\n // The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden\n});\n```\n\nTo access a property\'s raw JSON value, which may be undocumented, call its `_` prefixed method:\n\n```java\nimport com.imagekit.api.core.JsonField;\nimport java.io.InputStream;\nimport java.util.Optional;\n\nJsonField file = client.files().upload(params)._file();\n\nif (file.isMissing()) {\n // The property is absent from the JSON response\n} else if (file.isNull()) {\n // The property was set to literal null\n} else {\n // Check if value was provided as a string\n // Other methods include `asNumber()`, `asBoolean()`, etc.\n Optional jsonString = file.asString();\n\n // Try to deserialize into a custom type\n MyClass myObject = file.asUnknown().orElseThrow().convert(MyClass.class);\n}\n```\n\n### Response validation\n\nIn rare cases, the API may return a response that doesn\'t match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else.\n\nBy default, the SDK will not throw an exception in this case. It will throw [`ImageKitInvalidDataException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitInvalidDataException.kt) only if you directly access the property.\n\nIf you would prefer to check that the response is completely well-typed upfront, then either call `validate()`:\n\n```java\nimport com.imagekit.api.models.files.FileUploadResponse;\n\nFileUploadResponse response = client.files().upload(params).validate();\n```\n\nOr configure the method call to validate the response using the `responseValidation` method:\n\n```java\nimport com.imagekit.api.models.files.FileUploadResponse;\n\nFileUploadResponse response = client.files().upload(\n params, RequestOptions.builder().responseValidation(true).build()\n);\n```\n\nOr configure the default for all method calls at the client level:\n\n```java\nimport com.imagekit.api.client.ImageKitClient;\nimport com.imagekit.api.client.okhttp.ImageKitOkHttpClient;\n\nImageKitClient client = ImageKitOkHttpClient.builder()\n .fromEnv()\n .responseValidation(true)\n .build();\n```\n\n## FAQ\n\n### Why don\'t you use plain `enum` classes?\n\nJava `enum` classes are not trivially [forwards compatible](https://www.stainless.com/blog/making-java-enums-forwards-compatible). Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.\n\n### Why do you represent fields using `JsonField` instead of just plain `T`?\n\nUsing `JsonField` enables a few features:\n\n- Allowing usage of [undocumented API functionality](#undocumented-api-functionality)\n- Lazily [validating the API response against the expected shape](#response-validation)\n- Representing absent vs explicitly null values\n\n### Why don\'t you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)?\n\nIt is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don\'t want to introduce a breaking change every time we add a field to a class.\n\n### Why don\'t you use checked exceptions?\n\nChecked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.\n\nChecked exceptions:\n\n- Are verbose to handle\n- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error\n- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function)\n- Don\'t play well with lambdas (also due to the function coloring problem)\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/stainless-sdks/imagekit-java/issues) with questions, bugs, or suggestions.\n', + }, + { + language: 'csharp', + content: + '# Image Kit C# API Library\n\nThe Image Kit C# SDK provides convenient access to the [Image Kit REST API](https://imagekit.io/docs/api-reference) from applications written in C#.\n\n## Installation\n\n```bash\ngit clone git@github.com:stainless-sdks/imagekit-csharp.git\ndotnet add reference imagekit-csharp/src/ImageKit\n```\n\n## Requirements\n\nThis library requires .NET Standard 2.0 or later.\n\n## Usage\n\nSee the [`examples`](examples) directory for complete and runnable examples.\n\n```csharp\nImageKitClient client = new();\n\nFileUploadParams parameters = new()\n{\n File = Encoding.UTF8.GetBytes("https://www.example.com/public-url.jpg"),\n FileName = "file-name.jpg",\n};\n\nvar response = await client.Files.Upload(parameters);\n\nConsole.WriteLine(response);\n```', + }, + { + language: 'cli', + content: + "# Image Kit CLI\n\nThe official CLI for the [Image Kit REST API](https://imagekit.io/docs/api-reference).\n\n## Installation\n\n### Installing with Go\n\nTo test or install the CLI locally, you need [Go](https://go.dev/doc/install) version 1.22 or later installed.\n\n~~~sh\ngo install 'github.com/stainless-sdks/imagekit-cli/cmd/imagekit@latest'\n~~~\n\nOnce you have run `go install`, the binary is placed in your Go bin directory:\n\n- **Default location**: `$HOME/go/bin` (or `$GOPATH/bin` if GOPATH is set)\n- **Check your path**: Run `go env GOPATH` to see the base directory\n\nIf commands aren't found after installation, add the Go bin directory to your PATH:\n\n~~~sh\n# Add to your shell profile (.zshrc, .bashrc, etc.)\nexport PATH=\"$PATH:$(go env GOPATH)/bin\"\n~~~\n\n### Running Locally\n\nAfter cloning the git repository for this project, you can use the\n`scripts/run` script to run the tool locally:\n\n~~~sh\n./scripts/run args...\n~~~\n\n## Usage\n\nThe CLI follows a resource-based command structure:\n\n~~~sh\nimagekit [resource] [flags...]\n~~~\n\n~~~sh\nimagekit files upload \\\n --private-key 'My Private Key' \\\n --password 'My Password' \\\n --file 'Example data' \\\n --file-name file-name.jpg\n~~~\n\nFor details about specific commands, use the `--help` flag.\n\n### Environment variables\n\n| Environment variable | Description | Required | Default value |\n| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -------------- |\n| `IMAGEKIT_PRIVATE_KEY` | Your ImageKit private API key (starts with `private_`).\nYou can find this in the [ImageKit dashboard](https://imagekit.io/dashboard/developer/api-keys).\n | yes | |\n| `OPTIONAL_IMAGEKIT_IGNORES_THIS` | ImageKit uses your API key as username and ignores the password. \nThe SDK sets a dummy value. You can ignore this field.\n | no | `\"do_not_set\"` |\n| `IMAGEKIT_WEBHOOK_SECRET` | Your ImageKit webhook secret for verifying webhook signatures (starts with `whsec_`).\nYou can find this in the [ImageKit dashboard](https://imagekit.io/dashboard/developer/webhooks).\nOnly required if you're using webhooks.\n | no | `null` |\n\n### Global flags\n\n- `--private-key` - Your ImageKit private API key (starts with `private_`).\nYou can find this in the [ImageKit dashboard](https://imagekit.io/dashboard/developer/api-keys).\n (can also be set with `IMAGEKIT_PRIVATE_KEY` env var)\n- `--password` - ImageKit uses your API key as username and ignores the password. \nThe SDK sets a dummy value. You can ignore this field.\n (can also be set with `OPTIONAL_IMAGEKIT_IGNORES_THIS` env var)\n- `--webhook-secret` - Your ImageKit webhook secret for verifying webhook signatures (starts with `whsec_`).\nYou can find this in the [ImageKit dashboard](https://imagekit.io/dashboard/developer/webhooks).\nOnly required if you're using webhooks.\n (can also be set with `IMAGEKIT_WEBHOOK_SECRET` env var)\n- `--help` - Show command line usage\n- `--debug` - Enable debug logging (includes HTTP request/response details)\n- `--version`, `-v` - Show the CLI version\n- `--base-url` - Use a custom API backend URL\n- `--format` - Change the output format (`auto`, `explore`, `json`, `jsonl`, `pretty`, `raw`, `yaml`)\n- `--format-error` - Change the output format for errors (`auto`, `explore`, `json`, `jsonl`, `pretty`, `raw`, `yaml`)\n- `--transform` - Transform the data output using [GJSON syntax](https://github.com/tidwall/gjson/blob/master/SYNTAX.md)\n- `--transform-error` - Transform the error output using [GJSON syntax](https://github.com/tidwall/gjson/blob/master/SYNTAX.md)\n\n### Passing files as arguments\n\nTo pass files to your API, you can use the `@myfile.ext` syntax:\n\n~~~bash\nimagekit --arg @abe.jpg\n~~~\n\nFiles can also be passed inside JSON or YAML blobs:\n\n~~~bash\nimagekit --arg '{image: \"@abe.jpg\"}'\n# Equivalent:\nimagekit < --username '\\@abe'\n~~~\n\n#### Explicit encoding\n\nFor JSON endpoints, the CLI tool does filetype sniffing to determine whether the\nfile contents should be sent as a string literal (for plain text files) or as a\nbase64-encoded string literal (for binary files). If you need to explicitly send\nthe file as either plain text or base64-encoded data, you can use\n`@file://myfile.txt` (for string encoding) or `@data://myfile.dat` (for\nbase64-encoding). Note that absolute paths will begin with `@file://` or\n`@data://`, followed by a third `/` (for example, `@file:///tmp/file.txt`).\n\n~~~bash\nimagekit --arg @data://file.txt\n~~~\n", + }, + { + language: 'php', + content: + '# Image Kit PHP API Library\n\nThe Image Kit PHP library provides convenient access to the Image Kit REST API from any PHP 8.1.0+ application.\n\n## Installation\n\nTo use this package, install via Composer by adding the following to your application\'s `composer.json`:\n\n```json\n{\n "repositories": [\n {\n "type": "vcs",\n "url": "git@github.com:stainless-sdks/imagekit-php.git"\n }\n ],\n "require": {\n "imagekit/imagekit": "dev-main"\n }\n}\n```\n\n## Usage\n\n```php\nfiles->upload(file: \'file\', fileName: \'file-name.jpg\');\n\nvar_dump($response->videoCodec);\n```', + }, +]; + +const INDEX_OPTIONS = { + fields: [ + 'name', + 'endpoint', + 'summary', + 'description', + 'qualified', + 'stainlessPath', + 'content', + 'sectionContext', + ], + storeFields: ['kind', '_original'], + searchOptions: { + prefix: true, + fuzzy: 0.1, + boost: { + name: 5, + stainlessPath: 3, + endpoint: 3, + qualified: 3, + summary: 2, + content: 1, + description: 1, + } as Record, + }, +}; + +/** + * Self-contained local search engine backed by MiniSearch. + * Method data is embedded at SDK build time; prose documents + * can be loaded from an optional docs directory at runtime. + */ +export class LocalDocsSearch { + private methodIndex: MiniSearch; + private proseIndex: MiniSearch; + + private constructor() { + this.methodIndex = new MiniSearch(INDEX_OPTIONS); + this.proseIndex = new MiniSearch(INDEX_OPTIONS); + } + + static async create(opts?: { docsDir?: string }): Promise { + const instance = new LocalDocsSearch(); + instance.indexMethods(EMBEDDED_METHODS); + for (const readme of EMBEDDED_READMES) { + instance.indexProse(readme.content, `readme:${readme.language}`); + } + if (opts?.docsDir) { + await instance.loadDocsDirectory(opts.docsDir); + } + return instance; + } + + search(props: { + query: string; + language?: string; + detail?: string; + maxResults?: number; + maxLength?: number; + }): SearchResult { + const { query, language = 'typescript', detail = 'default', maxResults = 5, maxLength = 100_000 } = props; + + const useMarkdown = detail === 'verbose' || detail === 'high'; + + // Search both indices and merge results by score. + // Filter prose hits so language-tagged content (READMEs and docs with + // frontmatter) only matches the requested language. + const methodHits = this.methodIndex + .search(query) + .map((hit) => ({ ...hit, _kind: 'http_method' as const })); + const proseHits = this.proseIndex + .search(query) + .filter((hit) => { + const source = ((hit as Record)['_original'] as ProseChunk | undefined)?.source; + if (!source) return true; + // Check for language-tagged sources: "readme:" or "lang::" + let taggedLang: string | undefined; + if (source.startsWith('readme:')) taggedLang = source.slice('readme:'.length); + else if (source.startsWith('lang:')) taggedLang = source.split(':')[1]; + if (!taggedLang) return true; + return taggedLang === language || (language === 'javascript' && taggedLang === 'typescript'); + }) + .map((hit) => ({ ...hit, _kind: 'prose' as const })); + const merged = [...methodHits, ...proseHits].sort((a, b) => b.score - a.score); + const top = merged.slice(0, maxResults); + + const fullResults: (string | Record)[] = []; + + for (const hit of top) { + const original = (hit as Record)['_original']; + if (hit._kind === 'http_method') { + const m = original as MethodEntry; + if (useMarkdown && m.markdown) { + fullResults.push(m.markdown); + } else { + // Use per-language data when available, falling back to the + // top-level fields (which are TypeScript-specific in the + // legacy codepath). + const langData = m.perLanguage?.[language]; + fullResults.push({ + method: langData?.method ?? m.qualified, + summary: m.summary, + description: m.description, + endpoint: `${m.httpMethod.toUpperCase()} ${m.endpoint}`, + ...(langData?.example ? { example: langData.example } : {}), + ...(m.params ? { params: m.params } : {}), + ...(m.response ? { response: m.response } : {}), + }); + } + } else { + const c = original as ProseChunk; + fullResults.push({ + content: c.content, + ...(c.source ? { source: c.source } : {}), + }); + } + } + + let totalLength = 0; + const results: (string | Record)[] = []; + for (const result of fullResults) { + const len = typeof result === 'string' ? result.length : JSON.stringify(result).length; + totalLength += len; + if (totalLength > maxLength) break; + results.push(result); + } + + if (results.length < fullResults.length) { + results.unshift(`Truncated; showing ${results.length} of ${fullResults.length} results.`); + } + + return { results }; + } + + private indexMethods(methods: MethodEntry[]): void { + const docs: MiniSearchDocument[] = methods.map((m, i) => ({ + id: `method-${i}`, + kind: 'http_method' as const, + name: m.name, + endpoint: m.endpoint, + summary: m.summary, + description: m.description, + qualified: m.qualified, + stainlessPath: m.stainlessPath, + _original: m as unknown as Record, + })); + if (docs.length > 0) { + this.methodIndex.addAll(docs); + } + } + + private async loadDocsDirectory(docsDir: string): Promise { + let entries; + try { + entries = await fs.readdir(docsDir, { withFileTypes: true }); + } catch (err) { + getLogger().warn({ err, docsDir }, 'Could not read docs directory'); + return; + } + + const files = entries + .filter((e) => e.isFile()) + .filter((e) => e.name.endsWith('.md') || e.name.endsWith('.markdown') || e.name.endsWith('.json')); + + for (const file of files) { + try { + const filePath = path.join(docsDir, file.name); + const content = await fs.readFile(filePath, 'utf-8'); + + if (file.name.endsWith('.json')) { + const texts = extractTexts(JSON.parse(content)); + if (texts.length > 0) { + this.indexProse(texts.join('\n\n'), file.name); + } + } else { + // Parse optional YAML frontmatter for language tagging. + // Files with a "language" field in frontmatter will only + // surface in searches for that language. + // + // Example: + // --- + // language: python + // --- + // # Error handling in Python + // ... + const frontmatter = parseFrontmatter(content); + const source = frontmatter.language ? `lang:${frontmatter.language}:${file.name}` : file.name; + this.indexProse(content, source); + } + } catch (err) { + getLogger().warn({ err, file: file.name }, 'Failed to index docs file'); + } + } + } + + private indexProse(markdown: string, source: string): void { + const chunks = chunkMarkdown(markdown); + const baseId = this.proseIndex.documentCount; + + const docs: MiniSearchDocument[] = chunks.map((chunk, i) => ({ + id: `prose-${baseId + i}`, + kind: 'prose' as const, + content: chunk.content, + ...(chunk.sectionContext != null ? { sectionContext: chunk.sectionContext } : {}), + _original: { ...chunk, source } as unknown as Record, + })); + + if (docs.length > 0) { + this.proseIndex.addAll(docs); + } + } +} + +/** Lightweight markdown chunker — splits on headers, chunks by word count. */ +function chunkMarkdown(markdown: string): { content: string; tag: string; sectionContext?: string }[] { + // Strip YAML frontmatter + const stripped = markdown.replace(/^---\n[\s\S]*?\n---\n?/, ''); + const lines = stripped.split('\n'); + + const chunks: { content: string; tag: string; sectionContext?: string }[] = []; + const headers: string[] = []; + let current: string[] = []; + + const flush = () => { + const text = current.join('\n').trim(); + if (!text) return; + const sectionContext = headers.length > 0 ? headers.join(' > ') : undefined; + // Split into ~200-word chunks + const words = text.split(/\s+/); + for (let i = 0; i < words.length; i += 200) { + const slice = words.slice(i, i + 200).join(' '); + if (slice) { + chunks.push({ content: slice, tag: 'p', ...(sectionContext != null ? { sectionContext } : {}) }); + } + } + current = []; + }; + + for (const line of lines) { + const headerMatch = line.match(/^(#{1,6})\s+(.+)/); + if (headerMatch) { + flush(); + const level = headerMatch[1]!.length; + const text = headerMatch[2]!.trim(); + while (headers.length >= level) headers.pop(); + headers.push(text); + } else { + current.push(line); + } + } + flush(); + + return chunks; +} + +/** Recursively extracts string values from a JSON structure. */ +function extractTexts(data: unknown, depth = 0): string[] { + if (depth > 10) return []; + if (typeof data === 'string') return data.trim() ? [data] : []; + if (Array.isArray(data)) return data.flatMap((item) => extractTexts(item, depth + 1)); + if (typeof data === 'object' && data !== null) { + return Object.values(data).flatMap((v) => extractTexts(v, depth + 1)); + } + return []; +} + +/** Parses YAML frontmatter from a markdown string, extracting the language field if present. */ +function parseFrontmatter(markdown: string): { language?: string } { + const match = markdown.match(/^---\n([\s\S]*?)\n---/); + if (!match) return {}; + const body = match[1] ?? ''; + const langMatch = body.match(/^language:\s*(.+)$/m); + return langMatch ? { language: langMatch[1]!.trim() } : {}; +} diff --git a/packages/mcp-server/src/logger.ts b/packages/mcp-server/src/logger.ts new file mode 100644 index 00000000..29dab11c --- /dev/null +++ b/packages/mcp-server/src/logger.ts @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { pino, type Level, type Logger } from 'pino'; +import pretty from 'pino-pretty'; + +let _logger: Logger | undefined; + +export function configureLogger({ level, pretty: usePretty }: { level: Level; pretty: boolean }): void { + _logger = pino( + { + level, + timestamp: pino.stdTimeFunctions.isoTime, + formatters: { + level(label) { + return { level: label }; + }, + }, + }, + usePretty ? pretty({ colorize: true, levelFirst: true, destination: 2 }) : process.stderr, + ); +} + +export function getLogger(): Logger { + if (!_logger) { + throw new Error('Logger has not been configured. Call configureLogger() before using the logger.'); + } + return _logger; +} diff --git a/packages/mcp-server/src/methods.ts b/packages/mcp-server/src/methods.ts new file mode 100644 index 00000000..a2a4f930 --- /dev/null +++ b/packages/mcp-server/src/methods.ts @@ -0,0 +1,370 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { McpOptions } from './options'; + +export type SdkMethod = { + clientCallName: string; + fullyQualifiedName: string; + httpMethod?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'query'; + httpPath?: string; +}; + +export const sdkMethods: SdkMethod[] = [ + { + clientCallName: 'client.customMetadataFields.create', + fullyQualifiedName: 'customMetadataFields.create', + httpMethod: 'post', + httpPath: '/v1/customMetadataFields', + }, + { + clientCallName: 'client.customMetadataFields.update', + fullyQualifiedName: 'customMetadataFields.update', + httpMethod: 'patch', + httpPath: '/v1/customMetadataFields/{id}', + }, + { + clientCallName: 'client.customMetadataFields.list', + fullyQualifiedName: 'customMetadataFields.list', + httpMethod: 'get', + httpPath: '/v1/customMetadataFields', + }, + { + clientCallName: 'client.customMetadataFields.delete', + fullyQualifiedName: 'customMetadataFields.delete', + httpMethod: 'delete', + httpPath: '/v1/customMetadataFields/{id}', + }, + { + clientCallName: 'client.files.update', + fullyQualifiedName: 'files.update', + httpMethod: 'patch', + httpPath: '/v1/files/{fileId}/details', + }, + { + clientCallName: 'client.files.delete', + fullyQualifiedName: 'files.delete', + httpMethod: 'delete', + httpPath: '/v1/files/{fileId}', + }, + { + clientCallName: 'client.files.copy', + fullyQualifiedName: 'files.copy', + httpMethod: 'post', + httpPath: '/v1/files/copy', + }, + { + clientCallName: 'client.files.get', + fullyQualifiedName: 'files.get', + httpMethod: 'get', + httpPath: '/v1/files/{fileId}/details', + }, + { + clientCallName: 'client.files.move', + fullyQualifiedName: 'files.move', + httpMethod: 'post', + httpPath: '/v1/files/move', + }, + { + clientCallName: 'client.files.rename', + fullyQualifiedName: 'files.rename', + httpMethod: 'put', + httpPath: '/v1/files/rename', + }, + { + clientCallName: 'client.files.upload', + fullyQualifiedName: 'files.upload', + httpMethod: 'post', + httpPath: '/api/v1/files/upload', + }, + { + clientCallName: 'client.files.bulk.delete', + fullyQualifiedName: 'files.bulk.delete', + httpMethod: 'post', + httpPath: '/v1/files/batch/deleteByFileIds', + }, + { + clientCallName: 'client.files.bulk.addTags', + fullyQualifiedName: 'files.bulk.addTags', + httpMethod: 'post', + httpPath: '/v1/files/addTags', + }, + { + clientCallName: 'client.files.bulk.removeAITags', + fullyQualifiedName: 'files.bulk.removeAITags', + httpMethod: 'post', + httpPath: '/v1/files/removeAITags', + }, + { + clientCallName: 'client.files.bulk.removeTags', + fullyQualifiedName: 'files.bulk.removeTags', + httpMethod: 'post', + httpPath: '/v1/files/removeTags', + }, + { + clientCallName: 'client.files.versions.list', + fullyQualifiedName: 'files.versions.list', + httpMethod: 'get', + httpPath: '/v1/files/{fileId}/versions', + }, + { + clientCallName: 'client.files.versions.delete', + fullyQualifiedName: 'files.versions.delete', + httpMethod: 'delete', + httpPath: '/v1/files/{fileId}/versions/{versionId}', + }, + { + clientCallName: 'client.files.versions.get', + fullyQualifiedName: 'files.versions.get', + httpMethod: 'get', + httpPath: '/v1/files/{fileId}/versions/{versionId}', + }, + { + clientCallName: 'client.files.versions.restore', + fullyQualifiedName: 'files.versions.restore', + httpMethod: 'put', + httpPath: '/v1/files/{fileId}/versions/{versionId}/restore', + }, + { + clientCallName: 'client.files.metadata.get', + fullyQualifiedName: 'files.metadata.get', + httpMethod: 'get', + httpPath: '/v1/files/{fileId}/metadata', + }, + { + clientCallName: 'client.files.metadata.getFromURL', + fullyQualifiedName: 'files.metadata.getFromURL', + httpMethod: 'get', + httpPath: '/v1/metadata', + }, + { + clientCallName: 'client.savedExtensions.create', + fullyQualifiedName: 'savedExtensions.create', + httpMethod: 'post', + httpPath: '/v1/saved-extensions', + }, + { + clientCallName: 'client.savedExtensions.update', + fullyQualifiedName: 'savedExtensions.update', + httpMethod: 'patch', + httpPath: '/v1/saved-extensions/{id}', + }, + { + clientCallName: 'client.savedExtensions.list', + fullyQualifiedName: 'savedExtensions.list', + httpMethod: 'get', + httpPath: '/v1/saved-extensions', + }, + { + clientCallName: 'client.savedExtensions.delete', + fullyQualifiedName: 'savedExtensions.delete', + httpMethod: 'delete', + httpPath: '/v1/saved-extensions/{id}', + }, + { + clientCallName: 'client.savedExtensions.get', + fullyQualifiedName: 'savedExtensions.get', + httpMethod: 'get', + httpPath: '/v1/saved-extensions/{id}', + }, + { + clientCallName: 'client.assets.list', + fullyQualifiedName: 'assets.list', + httpMethod: 'get', + httpPath: '/v1/files', + }, + { + clientCallName: 'client.cache.invalidation.create', + fullyQualifiedName: 'cache.invalidation.create', + httpMethod: 'post', + httpPath: '/v1/files/purge', + }, + { + clientCallName: 'client.cache.invalidation.get', + fullyQualifiedName: 'cache.invalidation.get', + httpMethod: 'get', + httpPath: '/v1/files/purge/{requestId}', + }, + { + clientCallName: 'client.folders.create', + fullyQualifiedName: 'folders.create', + httpMethod: 'post', + httpPath: '/v1/folder', + }, + { + clientCallName: 'client.folders.delete', + fullyQualifiedName: 'folders.delete', + httpMethod: 'delete', + httpPath: '/v1/folder', + }, + { + clientCallName: 'client.folders.copy', + fullyQualifiedName: 'folders.copy', + httpMethod: 'post', + httpPath: '/v1/bulkJobs/copyFolder', + }, + { + clientCallName: 'client.folders.move', + fullyQualifiedName: 'folders.move', + httpMethod: 'post', + httpPath: '/v1/bulkJobs/moveFolder', + }, + { + clientCallName: 'client.folders.rename', + fullyQualifiedName: 'folders.rename', + httpMethod: 'post', + httpPath: '/v1/bulkJobs/renameFolder', + }, + { + clientCallName: 'client.folders.job.get', + fullyQualifiedName: 'folders.job.get', + httpMethod: 'get', + httpPath: '/v1/bulkJobs/{jobId}', + }, + { + clientCallName: 'client.accounts.usage.get', + fullyQualifiedName: 'accounts.usage.get', + httpMethod: 'get', + httpPath: '/v1/accounts/usage', + }, + { + clientCallName: 'client.accounts.origins.create', + fullyQualifiedName: 'accounts.origins.create', + httpMethod: 'post', + httpPath: '/v1/accounts/origins', + }, + { + clientCallName: 'client.accounts.origins.update', + fullyQualifiedName: 'accounts.origins.update', + httpMethod: 'put', + httpPath: '/v1/accounts/origins/{id}', + }, + { + clientCallName: 'client.accounts.origins.list', + fullyQualifiedName: 'accounts.origins.list', + httpMethod: 'get', + httpPath: '/v1/accounts/origins', + }, + { + clientCallName: 'client.accounts.origins.delete', + fullyQualifiedName: 'accounts.origins.delete', + httpMethod: 'delete', + httpPath: '/v1/accounts/origins/{id}', + }, + { + clientCallName: 'client.accounts.origins.get', + fullyQualifiedName: 'accounts.origins.get', + httpMethod: 'get', + httpPath: '/v1/accounts/origins/{id}', + }, + { + clientCallName: 'client.accounts.urlEndpoints.create', + fullyQualifiedName: 'accounts.urlEndpoints.create', + httpMethod: 'post', + httpPath: '/v1/accounts/url-endpoints', + }, + { + clientCallName: 'client.accounts.urlEndpoints.update', + fullyQualifiedName: 'accounts.urlEndpoints.update', + httpMethod: 'put', + httpPath: '/v1/accounts/url-endpoints/{id}', + }, + { + clientCallName: 'client.accounts.urlEndpoints.list', + fullyQualifiedName: 'accounts.urlEndpoints.list', + httpMethod: 'get', + httpPath: '/v1/accounts/url-endpoints', + }, + { + clientCallName: 'client.accounts.urlEndpoints.delete', + fullyQualifiedName: 'accounts.urlEndpoints.delete', + httpMethod: 'delete', + httpPath: '/v1/accounts/url-endpoints/{id}', + }, + { + clientCallName: 'client.accounts.urlEndpoints.get', + fullyQualifiedName: 'accounts.urlEndpoints.get', + httpMethod: 'get', + httpPath: '/v1/accounts/url-endpoints/{id}', + }, + { + clientCallName: 'client.beta.v2.files.upload', + fullyQualifiedName: 'beta.v2.files.upload', + httpMethod: 'post', + httpPath: '/api/v2/files/upload', + }, + { clientCallName: 'client.webhooks.unsafeUnwrap', fullyQualifiedName: 'webhooks.unsafeUnwrap' }, + { clientCallName: 'client.webhooks.unwrap', fullyQualifiedName: 'webhooks.unwrap' }, +]; + +function allowedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined { + if (!options) { + return undefined; + } + + let allowedMethods: SdkMethod[]; + + if (options.codeAllowHttpGets || options.codeAllowedMethods) { + // Start with nothing allowed and then add into it from options + let allowedMethodsSet = new Set(); + + if (options.codeAllowHttpGets) { + // Add all methods that map to an HTTP GET + sdkMethods + .filter((method) => method.httpMethod === 'get') + .forEach((method) => allowedMethodsSet.add(method)); + } + + if (options.codeAllowedMethods) { + // Add all methods that match any of the allowed regexps + const allowedRegexps = options.codeAllowedMethods.map((pattern) => { + try { + return new RegExp(pattern); + } catch (e) { + throw new Error( + `Invalid regex pattern for allowed method: "${pattern}": ${e instanceof Error ? e.message : e}`, + ); + } + }); + + sdkMethods + .filter((method) => allowedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName))) + .forEach((method) => allowedMethodsSet.add(method)); + } + + allowedMethods = Array.from(allowedMethodsSet); + } else { + // Start with everything allowed + allowedMethods = [...sdkMethods]; + } + + if (options.codeBlockedMethods) { + // Filter down based on blocked regexps + const blockedRegexps = options.codeBlockedMethods.map((pattern) => { + try { + return new RegExp(pattern); + } catch (e) { + throw new Error( + `Invalid regex pattern for blocked method: "${pattern}": ${e instanceof Error ? e.message : e}`, + ); + } + }); + + allowedMethods = allowedMethods.filter( + (method) => !blockedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName)), + ); + } + + return allowedMethods; +} + +export function blockedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined { + const allowedMethods = allowedMethodsForCodeTool(options); + if (!allowedMethods) { + return undefined; + } + + const allowedSet = new Set(allowedMethods.map((method) => method.fullyQualifiedName)); + + // Return any methods that are not explicitly allowed + return sdkMethods.filter((method) => !allowedSet.has(method.fullyQualifiedName)); +} diff --git a/packages/mcp-server/src/options.ts b/packages/mcp-server/src/options.ts index c66ad8ce..f1518764 100644 --- a/packages/mcp-server/src/options.ts +++ b/packages/mcp-server/src/options.ts @@ -1,46 +1,114 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + import qs from 'qs'; import yargs from 'yargs'; import { hideBin } from 'yargs/helpers'; import z from 'zod'; +import { readEnv } from './util'; export type CLIOptions = McpOptions & { + debug: boolean; + logFormat: 'json' | 'pretty'; transport: 'stdio' | 'http'; port: number | undefined; socket: string | undefined; }; export type McpOptions = { + includeCodeTool?: boolean | undefined; includeDocsTools?: boolean | undefined; + stainlessApiKey?: string | undefined; + docsSearchMode?: 'stainless-api' | 'local' | undefined; + docsDir?: string | undefined; + codeAllowHttpGets?: boolean | undefined; + codeAllowedMethods?: string[] | undefined; + codeBlockedMethods?: string[] | undefined; + codeExecutionMode: McpCodeExecutionMode; + customInstructionsPath?: string | undefined; }; +export type McpCodeExecutionMode = 'stainless-sandbox' | 'local'; + export function parseCLIOptions(): CLIOptions { const opts = yargs(hideBin(process.argv)) - .option('tools', { + .option('code-allow-http-gets', { + type: 'boolean', + description: + 'Allow all code tool methods that map to HTTP GET operations. If all code-allow-* flags are unset, then everything is allowed.', + }) + .option('code-allowed-methods', { type: 'string', array: true, - choices: ['code', 'docs'], - description: 'Use dynamic tools or all tools', + description: + 'Methods to explicitly allow for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.', }) - .option('no-tools', { + .option('code-blocked-methods', { type: 'string', array: true, - choices: ['code', 'docs'], - description: 'Do not use any dynamic or all tools', + description: + 'Methods to explicitly block for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.', }) - .option('transport', { + .option('code-execution-mode', { type: 'string', - choices: ['stdio', 'http'], - default: 'stdio', - description: 'What transport to use; stdio for local servers or http for remote servers', + choices: ['stainless-sandbox', 'local'], + default: 'stainless-sandbox', + description: + "Where to run code execution in code tool; 'stainless-sandbox' will execute code in Stainless-hosted sandboxes whereas 'local' will execute code locally on the MCP server machine.", + }) + .option('custom-instructions-path', { + type: 'string', + description: 'Path to custom instructions for the MCP server', + }) + .option('debug', { type: 'boolean', description: 'Enable debug logging' }) + .option('docs-dir', { + type: 'string', + description: + 'Path to a directory of local documentation files (markdown/JSON) to include in local docs search.', + }) + .option('docs-search-mode', { + type: 'string', + choices: ['stainless-api', 'local'], + default: 'stainless-api', + description: + "Where to search documentation; 'stainless-api' uses the Stainless-hosted search API whereas 'local' uses an in-memory search index built from embedded SDK method data and optional local docs files.", + }) + .option('log-format', { + type: 'string', + choices: ['json', 'pretty'], + description: 'Format for log output; defaults to json unless tty is detected', + }) + .option('no-tools', { + type: 'string', + array: true, + choices: ['code', 'docs'], + description: 'Tools to explicitly disable', }) .option('port', { type: 'number', + default: 3000, description: 'Port to serve on if using http transport', }) - .option('socket', { + .option('socket', { type: 'string', description: 'Unix socket to serve on if using http transport' }) + .option('stainless-api-key', { + type: 'string', + default: readEnv('STAINLESS_API_KEY'), + description: + 'API key for Stainless. Used to authenticate requests to Stainless-hosted tools endpoints.', + }) + .option('tools', { + type: 'string', + array: true, + choices: ['code', 'docs'], + description: 'Tools to explicitly enable', + }) + .option('transport', { type: 'string', - description: 'Unix socket to serve on if using http transport', + choices: ['stdio', 'http'], + default: 'stdio', + description: 'What transport to use; stdio for local servers or http for remote servers', }) + .env('MCP_SERVER') + .version(true) .help(); const argv = opts.parseSync(); @@ -50,13 +118,29 @@ export function parseCLIOptions(): CLIOptions { : argv.tools?.includes(toolType) ? true : undefined; + const includeCodeTool = shouldIncludeToolType('code'); const includeDocsTools = shouldIncludeToolType('docs'); const transport = argv.transport as 'stdio' | 'http'; + const logFormat = + argv.logFormat ? (argv.logFormat as 'json' | 'pretty') + : process.stderr.isTTY ? 'pretty' + : 'json'; return { + ...(includeCodeTool !== undefined && { includeCodeTool }), ...(includeDocsTools !== undefined && { includeDocsTools }), + debug: !!argv.debug, + stainlessApiKey: argv.stainlessApiKey, + docsSearchMode: argv.docsSearchMode as 'stainless-api' | 'local' | undefined, + docsDir: argv.docsDir, + codeAllowHttpGets: argv.codeAllowHttpGets, + codeAllowedMethods: argv.codeAllowedMethods, + codeBlockedMethods: argv.codeBlockedMethods, + codeExecutionMode: argv.codeExecutionMode as McpCodeExecutionMode, + customInstructionsPath: argv.customInstructionsPath, transport, + logFormat, port: argv.port, socket: argv.socket, }; @@ -81,12 +165,21 @@ export function parseQueryOptions(defaultOptions: McpOptions, query: unknown): M const queryObject = typeof query === 'string' ? qs.parse(query) : query; const queryOptions = QueryOptions.parse(queryObject); + let codeTool: boolean | undefined = + queryOptions.no_tools && queryOptions.no_tools?.includes('code') ? false + : queryOptions.tools?.includes('code') ? true + : defaultOptions.includeCodeTool; + let docsTools: boolean | undefined = queryOptions.no_tools && queryOptions.no_tools?.includes('docs') ? false : queryOptions.tools?.includes('docs') ? true : defaultOptions.includeDocsTools; return { + ...(codeTool !== undefined && { includeCodeTool: codeTool }), ...(docsTools !== undefined && { includeDocsTools: docsTools }), + codeExecutionMode: defaultOptions.codeExecutionMode, + docsSearchMode: defaultOptions.docsSearchMode, + docsDir: defaultOptions.docsDir, }; } diff --git a/packages/mcp-server/src/server.ts b/packages/mcp-server/src/server.ts index 7b26259a..c9bb80fa 100644 --- a/packages/mcp-server/src/server.ts +++ b/packages/mcp-server/src/server.ts @@ -11,32 +11,43 @@ import { ClientOptions } from '@imagekit/nodejs'; import ImageKit from '@imagekit/nodejs'; import { codeTool } from './code-tool'; import docsSearchTool from './docs-search-tool'; +import { setLocalSearch } from './docs-search-tool'; +import { LocalDocsSearch } from './local-docs-search'; +import { getInstructions } from './instructions'; import { McpOptions } from './options'; -import { HandlerFunction, McpTool } from './types'; - -export { McpOptions } from './options'; -export { ClientOptions } from '@imagekit/nodejs'; - -export const newMcpServer = () => +import { blockedMethodsForCodeTool } from './methods'; +import { HandlerFunction, McpRequestContext, ToolCallResult, McpTool } from './types'; + +export const newMcpServer = async ({ + stainlessApiKey, + customInstructionsPath, +}: { + stainlessApiKey?: string | undefined; + customInstructionsPath?: string | undefined; +}) => new McpServer( { name: 'imagekit_nodejs_api', - version: '7.3.0', + version: '7.4.0', + }, + { + instructions: await getInstructions({ stainlessApiKey, customInstructionsPath }), + capabilities: { tools: {}, logging: {} }, }, - { capabilities: { tools: {}, logging: {} } }, ); -// Create server instance -export const server = newMcpServer(); - /** * Initializes the provided MCP Server with the given tools and handlers. * If not provided, the default client, tools and handlers will be used. */ -export function initMcpServer(params: { +export async function initMcpServer(params: { server: Server | McpServer; clientOptions?: ClientOptions; mcpOptions?: McpOptions; + stainlessApiKey?: string | undefined; + upstreamClientEnvs?: Record | undefined; + mcpSessionId?: string | undefined; + mcpClientInfo?: { name: string; version: string } | undefined; }) { const server = params.server instanceof McpServer ? params.server.server : params.server; @@ -55,14 +66,38 @@ export function initMcpServer(params: { error: logAtLevel('error'), }; - let client = new ImageKit({ - logger, - ...params.clientOptions, - defaultHeaders: { - ...params.clientOptions?.defaultHeaders, - 'X-Stainless-MCP': 'true', - }, - }); + if (params.mcpOptions?.docsSearchMode === 'local') { + const docsDir = params.mcpOptions?.docsDir; + const localSearch = await LocalDocsSearch.create(docsDir ? { docsDir } : undefined); + setLocalSearch(localSearch); + } + + let _client: ImageKit | undefined; + let _clientError: Error | undefined; + let _logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off' | undefined; + + const getClient = (): ImageKit => { + if (_clientError) throw _clientError; + if (!_client) { + try { + _client = new ImageKit({ + logger, + ...params.clientOptions, + defaultHeaders: { + ...params.clientOptions?.defaultHeaders, + 'X-Stainless-MCP': 'true', + }, + }); + if (_logLevel) { + _client = _client.withOptions({ logLevel: _logLevel }); + } + } catch (e) { + _clientError = e instanceof Error ? e : new Error(String(e)); + throw _clientError; + } + } + return _client; + }; const providedTools = selectTools(params.mcpOptions); const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool])); @@ -80,29 +115,59 @@ export function initMcpServer(params: { throw new Error(`Unknown tool: ${name}`); } - return executeHandler(mcpTool.handler, client, args); + let client: ImageKit; + try { + client = getClient(); + } catch (error) { + return { + content: [ + { + type: 'text' as const, + text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`, + }, + ], + isError: true, + }; + } + + return executeHandler({ + handler: mcpTool.handler, + reqContext: { + client, + stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey, + upstreamClientEnvs: params.upstreamClientEnvs, + mcpSessionId: params.mcpSessionId, + mcpClientInfo: params.mcpClientInfo, + }, + args, + }); }); server.setRequestHandler(SetLevelRequestSchema, async (request) => { const { level } = request.params; + let logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off'; switch (level) { case 'debug': - client = client.withOptions({ logLevel: 'debug' }); + logLevel = 'debug'; break; case 'info': - client = client.withOptions({ logLevel: 'info' }); + logLevel = 'info'; break; case 'notice': case 'warning': - client = client.withOptions({ logLevel: 'warn' }); + logLevel = 'warn'; break; case 'error': - client = client.withOptions({ logLevel: 'error' }); + logLevel = 'error'; break; default: - client = client.withOptions({ logLevel: 'off' }); + logLevel = 'off'; break; } + _logLevel = logLevel; + if (_client) { + _client = _client.withOptions({ logLevel }); + } return {}; }); } @@ -111,7 +176,16 @@ export function initMcpServer(params: { * Selects the tools to include in the MCP Server based on the provided options. */ export function selectTools(options?: McpOptions): McpTool[] { - const includedTools = [codeTool()]; + const includedTools = []; + + if (options?.includeCodeTool ?? true) { + includedTools.push( + codeTool({ + blockedMethods: blockedMethodsForCodeTool(options), + codeExecutionMode: options?.codeExecutionMode ?? 'stainless-sandbox', + }), + ); + } if (options?.includeDocsTools ?? true) { includedTools.push(docsSearchTool); } @@ -121,34 +195,14 @@ export function selectTools(options?: McpOptions): McpTool[] { /** * Runs the provided handler with the given client and arguments. */ -export async function executeHandler( - handler: HandlerFunction, - client: ImageKit, - args: Record | undefined, -) { - return await handler(client, args || {}); +export async function executeHandler({ + handler, + reqContext, + args, +}: { + handler: HandlerFunction; + reqContext: McpRequestContext; + args: Record | undefined; +}): Promise { + return await handler({ reqContext, args: args || {} }); } - -export const readEnv = (env: string): string | undefined => { - if (typeof (globalThis as any).process !== 'undefined') { - return (globalThis as any).process.env?.[env]?.trim(); - } else if (typeof (globalThis as any).Deno !== 'undefined') { - return (globalThis as any).Deno.env?.get?.(env)?.trim(); - } - return; -}; - -export const readEnvOrError = (env: string): string => { - let envValue = readEnv(env); - if (envValue === undefined) { - throw new Error(`Environment variable ${env} is not set`); - } - return envValue; -}; - -export const requireValue = (value: T | undefined, description: string): T => { - if (value === undefined) { - throw new Error(`Missing required value: ${description}`); - } - return value; -}; diff --git a/packages/mcp-server/src/stdio.ts b/packages/mcp-server/src/stdio.ts index f07696f3..b04a5441 100644 --- a/packages/mcp-server/src/stdio.ts +++ b/packages/mcp-server/src/stdio.ts @@ -1,12 +1,17 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { McpOptions } from './options'; import { initMcpServer, newMcpServer } from './server'; +import { getLogger } from './logger'; -export const launchStdioServer = async () => { - const server = newMcpServer(); +export const launchStdioServer = async (mcpOptions: McpOptions) => { + const server = await newMcpServer({ + stainlessApiKey: mcpOptions.stainlessApiKey, + customInstructionsPath: mcpOptions.customInstructionsPath, + }); - initMcpServer({ server }); + await initMcpServer({ server, mcpOptions, stainlessApiKey: mcpOptions.stainlessApiKey }); const transport = new StdioServerTransport(); await server.connect(transport); - console.error('MCP Server running on stdio'); + getLogger().info('MCP Server running on stdio'); }; diff --git a/packages/mcp-server/src/types.ts b/packages/mcp-server/src/types.ts index 6b307bec..32be9c01 100644 --- a/packages/mcp-server/src/types.ts +++ b/packages/mcp-server/src/types.ts @@ -42,10 +42,21 @@ export type ToolCallResult = { isError?: boolean; }; -export type HandlerFunction = ( - client: ImageKit, - args: Record | undefined, -) => Promise; +export type McpRequestContext = { + client: ImageKit; + stainlessApiKey?: string | undefined; + upstreamClientEnvs?: Record | undefined; + mcpSessionId?: string | undefined; + mcpClientInfo?: { name: string; version: string } | undefined; +}; + +export type HandlerFunction = ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: Record | undefined; +}) => Promise; export function asTextContentResult(result: unknown): ToolCallResult { return { diff --git a/packages/mcp-server/src/util.ts b/packages/mcp-server/src/util.ts new file mode 100644 index 00000000..40ed5501 --- /dev/null +++ b/packages/mcp-server/src/util.ts @@ -0,0 +1,25 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export const readEnv = (env: string): string | undefined => { + if (typeof (globalThis as any).process !== 'undefined') { + return (globalThis as any).process.env?.[env]?.trim(); + } else if (typeof (globalThis as any).Deno !== 'undefined') { + return (globalThis as any).Deno.env?.get?.(env)?.trim(); + } + return; +}; + +export const readEnvOrError = (env: string): string => { + let envValue = readEnv(env); + if (envValue === undefined) { + throw new Error(`Environment variable ${env} is not set`); + } + return envValue; +}; + +export const requireValue = (value: T | undefined, description: string): T => { + if (value === undefined) { + throw new Error(`Missing required value: ${description}`); + } + return value; +}; diff --git a/packages/mcp-server/tests/options.test.ts b/packages/mcp-server/tests/options.test.ts index 7a2d5114..17306295 100644 --- a/packages/mcp-server/tests/options.test.ts +++ b/packages/mcp-server/tests/options.test.ts @@ -1,4 +1,4 @@ -import { parseCLIOptions, parseQueryOptions } from '../src/options'; +import { parseCLIOptions } from '../src/options'; // Mock process.argv const mockArgv = (args: string[]) => { @@ -30,21 +30,3 @@ describe('parseCLIOptions', () => { cleanup(); }); }); - -describe('parseQueryOptions', () => { - const defaultOptions = {}; - - it('default parsing should be empty', () => { - const query = ''; - const result = parseQueryOptions(defaultOptions, query); - - expect(result).toEqual({}); - }); - - it('should handle invalid query string gracefully', () => { - const query = 'invalid=value&tools=invalid-operation'; - - // Should throw due to Zod validation for invalid tools - expect(() => parseQueryOptions(defaultOptions, query)).toThrow(); - }); -}); diff --git a/packages/mcp-server/yarn.lock b/packages/mcp-server/yarn.lock index fe102775..c7e37692 100644 --- a/packages/mcp-server/yarn.lock +++ b/packages/mcp-server/yarn.lock @@ -297,61 +297,101 @@ dependencies: "@jridgewell/trace-mapping" "0.3.9" -"@eslint-community/eslint-utils@^4.2.0", "@eslint-community/eslint-utils@^4.4.0": +"@eslint-community/eslint-utils@^4.4.0", "@eslint-community/eslint-utils@^4.8.0": version "4.9.1" resolved "https://registry.yarnpkg.com/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz#4e90af67bc51ddee6cdef5284edf572ec376b595" integrity sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ== dependencies: eslint-visitor-keys "^3.4.3" -"@eslint-community/regexpp@^4.10.0", "@eslint-community/regexpp@^4.6.1": +"@eslint-community/regexpp@^4.10.0", "@eslint-community/regexpp@^4.12.1": version "4.12.2" resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.12.2.tgz#bccdf615bcf7b6e8db830ec0b8d21c9a25de597b" integrity sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew== -"@eslint/eslintrc@^2.1.4": - version "2.1.4" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-2.1.4.tgz#388a269f0f25c1b6adc317b5a2c55714894c70ad" - integrity sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ== +"@eslint/config-array@^0.21.2": + version "0.21.2" + resolved "https://registry.yarnpkg.com/@eslint/config-array/-/config-array-0.21.2.tgz#f29e22057ad5316cf23836cee9a34c81fffcb7e6" + integrity sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw== dependencies: - ajv "^6.12.4" + "@eslint/object-schema" "^2.1.7" + debug "^4.3.1" + minimatch "^3.1.5" + +"@eslint/config-helpers@^0.4.2": + version "0.4.2" + resolved "https://registry.yarnpkg.com/@eslint/config-helpers/-/config-helpers-0.4.2.tgz#1bd006ceeb7e2e55b2b773ab318d300e1a66aeda" + integrity sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw== + dependencies: + "@eslint/core" "^0.17.0" + +"@eslint/core@^0.17.0": + version "0.17.0" + resolved "https://registry.yarnpkg.com/@eslint/core/-/core-0.17.0.tgz#77225820413d9617509da9342190a2019e78761c" + integrity sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ== + dependencies: + "@types/json-schema" "^7.0.15" + +"@eslint/eslintrc@^3.3.5": + version "3.3.5" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.3.5.tgz#c131793cfc1a7b96f24a83e0a8bbd4b881558c60" + integrity sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg== + dependencies: + ajv "^6.14.0" debug "^4.3.2" - espree "^9.6.0" - globals "^13.19.0" + espree "^10.0.1" + globals "^14.0.0" ignore "^5.2.0" import-fresh "^3.2.1" - js-yaml "^4.1.0" - minimatch "^3.1.2" + js-yaml "^4.1.1" + minimatch "^3.1.5" strip-json-comments "^3.1.1" -"@eslint/js@8.57.1": - version "8.57.1" - resolved "https://registry.yarnpkg.com/@eslint/js/-/js-8.57.1.tgz#de633db3ec2ef6a3c89e2f19038063e8a122e2c2" - integrity sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q== +"@eslint/js@9.39.4": + version "9.39.4" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.39.4.tgz#a3f83bfc6fd9bf33a853dfacd0b49b398eb596c1" + integrity sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw== -"@hono/node-server@^1.19.7": - version "1.19.9" - resolved "https://registry.yarnpkg.com/@hono/node-server/-/node-server-1.19.9.tgz#8f37119b1acf283fd3f6035f3d1356fdb97a09ac" - integrity sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw== +"@eslint/object-schema@^2.1.7": + version "2.1.7" + resolved "https://registry.yarnpkg.com/@eslint/object-schema/-/object-schema-2.1.7.tgz#6e2126a1347e86a4dedf8706ec67ff8e107ebbad" + integrity sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA== -"@humanwhocodes/config-array@^0.13.0": - version "0.13.0" - resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.13.0.tgz#fb907624df3256d04b9aa2df50d7aa97ec648748" - integrity sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw== +"@eslint/plugin-kit@^0.4.1": + version "0.4.1" + resolved "https://registry.yarnpkg.com/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz#9779e3fd9b7ee33571a57435cf4335a1794a6cb2" + integrity sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA== dependencies: - "@humanwhocodes/object-schema" "^2.0.3" - debug "^4.3.1" - minimatch "^3.0.5" + "@eslint/core" "^0.17.0" + levn "^0.4.1" + +"@hono/node-server@^1.19.10", "@hono/node-server@^1.19.9": + version "1.19.11" + resolved "https://registry.yarnpkg.com/@hono/node-server/-/node-server-1.19.11.tgz#dc419f0826dd2504e9fc86ad289d5636a0444e2f" + integrity sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g== + +"@humanfs/core@^0.19.1": + version "0.19.1" + resolved "https://registry.yarnpkg.com/@humanfs/core/-/core-0.19.1.tgz#17c55ca7d426733fe3c561906b8173c336b40a77" + integrity sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA== + +"@humanfs/node@^0.16.6": + version "0.16.7" + resolved "https://registry.yarnpkg.com/@humanfs/node/-/node-0.16.7.tgz#822cb7b3a12c5a240a24f621b5a2413e27a45f26" + integrity sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ== + dependencies: + "@humanfs/core" "^0.19.1" + "@humanwhocodes/retry" "^0.4.0" "@humanwhocodes/module-importer@^1.0.1": version "1.0.1" resolved "https://registry.yarnpkg.com/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz#af5b2691a22b44be847b0ca81641c5fb6ad0172c" integrity sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA== -"@humanwhocodes/object-schema@^2.0.3": - version "2.0.3" - resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz#4a2868d75d6d6963e423bcf90b7fd1be343409d3" - integrity sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA== +"@humanwhocodes/retry@^0.4.0", "@humanwhocodes/retry@^0.4.2": + version "0.4.3" + resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.4.3.tgz#c2b9d2e374ee62c586d3adbea87199b1d7a7a6ba" + integrity sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ== "@inquirer/checkbox@^3.0.1": version "3.0.1" @@ -741,12 +781,12 @@ "@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/sourcemap-codec" "^1.4.14" -"@modelcontextprotocol/sdk@^1.25.2": - version "1.25.2" - resolved "https://registry.yarnpkg.com/@modelcontextprotocol/sdk/-/sdk-1.25.2.tgz#2284560b4e044b4ce5f328ee180931110cb8c5cf" - integrity sha512-LZFeo4F9M5qOhC/Uc1aQSrBHxMrvxett+9KLHt7OhcExtoiRN9DKgbZffMP/nxjutWDQpfMDfP3nkHI4X9ijww== +"@modelcontextprotocol/sdk@^1.27.1": + version "1.27.1" + resolved "https://registry.yarnpkg.com/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz#a602cf823bf8a68e13e7112f50aeb02b09fb83b9" + integrity sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA== dependencies: - "@hono/node-server" "^1.19.7" + "@hono/node-server" "^1.19.9" ajv "^8.17.1" ajv-formats "^3.0.1" content-type "^1.0.5" @@ -754,14 +794,15 @@ cross-spawn "^7.0.5" eventsource "^3.0.2" eventsource-parser "^3.0.0" - express "^5.0.1" - express-rate-limit "^7.5.0" - jose "^6.1.1" + express "^5.2.1" + express-rate-limit "^8.2.1" + hono "^4.11.4" + jose "^6.1.3" json-schema-typed "^8.0.2" pkce-challenge "^5.0.0" raw-body "^3.0.0" zod "^3.25 || ^4.0" - zod-to-json-schema "^3.25.0" + zod-to-json-schema "^3.25.1" "@nodelib/fs.scandir@2.1.5": version "2.1.5" @@ -776,7 +817,7 @@ resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b" integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A== -"@nodelib/fs.walk@^1.2.3", "@nodelib/fs.walk@^1.2.8": +"@nodelib/fs.walk@^1.2.3": version "1.2.8" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a" integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg== @@ -784,6 +825,11 @@ "@nodelib/fs.scandir" "2.1.5" fastq "^1.6.0" +"@pinojs/redact@^0.4.0": + version "0.4.0" + resolved "https://registry.yarnpkg.com/@pinojs/redact/-/redact-0.4.0.tgz#c3de060dd12640dcc838516aa2a6803cc7b2e9d6" + integrity sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg== + "@pkgr/core@^0.2.9": version "0.2.9" resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.2.9.tgz#d229a7b7f9dac167a156992ef23c7f023653f53b" @@ -886,6 +932,11 @@ dependencies: "@types/node" "*" +"@types/cookie-parser@^1.4.10": + version "1.4.10" + resolved "https://registry.yarnpkg.com/@types/cookie-parser/-/cookie-parser-1.4.10.tgz#a045272a383a30597a01955d4f9c790018f214e4" + integrity sha512-B4xqkqfZ8Wek+rCOeRxsjMS9OgvzebEzzLYw7NHYuvzb7IdxOkI0ZHGgeEBX4PUM7QGVvNSK60T3OvWj3YfBRg== + "@types/cors@^2.8.19": version "2.8.19" resolved "https://registry.yarnpkg.com/@types/cors/-/cors-2.8.19.tgz#d93ea2673fd8c9f697367f5eeefc2bbfa94f0342" @@ -893,6 +944,11 @@ dependencies: "@types/node" "*" +"@types/estree@^1.0.6": + version "1.0.8" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.8.tgz#958b91c991b1867ced318bedea0e215ee050726e" + integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w== + "@types/express-serve-static-core@^5.0.0": version "5.1.1" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz#1a77faffee9572d39124933259be2523837d7eaa" @@ -951,6 +1007,11 @@ expect "^29.0.0" pretty-format "^29.0.0" +"@types/json-schema@^7.0.15": + version "7.0.15" + resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" + integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== + "@types/mute-stream@^0.0.4": version "0.0.4" resolved "https://registry.yarnpkg.com/@types/mute-stream/-/mute-stream-0.0.4.tgz#77208e56a08767af6c5e1237be8888e2f255c478" @@ -1100,11 +1161,6 @@ "@typescript-eslint/types" "8.31.1" eslint-visitor-keys "^4.2.0" -"@ungap/structured-clone@^1.2.0": - version "1.3.0" - resolved "https://registry.yarnpkg.com/@ungap/structured-clone/-/structured-clone-1.3.0.tgz#d06bbb384ebcf6c505fde1c3d0ed4ddffe0aaff8" - integrity sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g== - "@valtown/deno-http-worker@^0.0.21": version "0.0.21" resolved "https://registry.yarnpkg.com/@valtown/deno-http-worker/-/deno-http-worker-0.0.21.tgz#9ce3b5c1d0db211fe7ea8297881fe551838474ad" @@ -1130,11 +1186,16 @@ acorn-walk@^8.1.1: dependencies: acorn "^8.11.0" -acorn@^8.11.0, acorn@^8.4.1, acorn@^8.9.0: +acorn@^8.11.0, acorn@^8.4.1: version "8.15.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.15.0.tgz#a360898bc415edaac46c8241f6383975b930b816" integrity sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg== +acorn@^8.15.0: + version "8.16.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.16.0.tgz#4ce79c89be40afe7afe8f3adb902a1f1ce9ac08a" + integrity sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw== + aggregate-error@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.1.0.tgz#92670ff50f5359bdb7a3e0d40d0ec30c5737687a" @@ -1150,10 +1211,10 @@ ajv-formats@^3.0.1: dependencies: ajv "^8.0.0" -ajv@^6.12.4: - version "6.12.6" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" - integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== +ajv@^6.14.0: + version "6.14.0" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.14.0.tgz#fd067713e228210636ebb08c60bd3765d6dbe73a" + integrity sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw== dependencies: fast-deep-equal "^3.1.1" fast-json-stable-stringify "^2.0.0" @@ -1170,6 +1231,16 @@ ajv@^8.0.0, ajv@^8.17.1: json-schema-traverse "^1.0.0" require-from-string "^2.0.2" +ajv@^8.18.0: + version "8.18.0" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.18.0.tgz#8864186b6738d003eb3a933172bb3833e10cefbc" + integrity sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A== + dependencies: + fast-deep-equal "^3.1.3" + fast-uri "^3.0.1" + json-schema-traverse "^1.0.0" + require-from-string "^2.0.2" + ansi-escapes@^4.2.1, ansi-escapes@^4.3.2: version "4.3.2" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e" @@ -1219,6 +1290,11 @@ argparse@^2.0.1: resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== +atomic-sleep@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/atomic-sleep/-/atomic-sleep-1.0.0.tgz#eb85b77a601fc932cfe432c5acd364a9e2c9075b" + integrity sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ== + babel-jest@^29.7.0: version "29.7.0" resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.7.0.tgz#f4369919225b684c56085998ac63dbd05be020d5" @@ -1474,6 +1550,11 @@ color-name@~1.1.4: resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== +colorette@^2.0.7: + version "2.0.20" + resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.20.tgz#9eb793e6833067f7235902fcd3b09917a000a95a" + integrity sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w== + commander@^13.1.0: version "13.1.0" resolved "https://registry.yarnpkg.com/commander/-/commander-13.1.0.tgz#776167db68c78f38dcce1f9b8d7b8b9a488abf46" @@ -1499,12 +1580,25 @@ convert-source-map@^2.0.0: resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-2.0.0.tgz#4b560f649fc4e918dd0ab75cf4961e8bc882d82a" integrity sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg== +cookie-parser@^1.4.6: + version "1.4.7" + resolved "https://registry.yarnpkg.com/cookie-parser/-/cookie-parser-1.4.7.tgz#e2125635dfd766888ffe90d60c286404fa0e7b26" + integrity sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw== + dependencies: + cookie "0.7.2" + cookie-signature "1.0.6" + +cookie-signature@1.0.6: + version "1.0.6" + resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c" + integrity sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ== + cookie-signature@^1.2.1: version "1.2.2" resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.2.2.tgz#57c7fc3cc293acab9fec54d73e15690ebe4a1793" integrity sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg== -cookie@^0.7.1: +cookie@0.7.2, cookie@^0.7.1: version "0.7.2" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.7.2.tgz#556369c472a2ba910f2979891b526b3436237ed7" integrity sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w== @@ -1535,7 +1629,7 @@ create-require@^1.1.0: resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== -cross-spawn@^7.0.2, cross-spawn@^7.0.3, cross-spawn@^7.0.5: +cross-spawn@^7.0.3, cross-spawn@^7.0.5, cross-spawn@^7.0.6: version "7.0.6" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f" integrity sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA== @@ -1544,6 +1638,11 @@ cross-spawn@^7.0.2, cross-spawn@^7.0.3, cross-spawn@^7.0.5: shebang-command "^2.0.0" which "^2.0.1" +dateformat@^4.6.3: + version "4.6.3" + resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-4.6.3.tgz#556fa6497e5217fedb78821424f8a1c22fa3f4b5" + integrity sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA== + debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4, debug@^4.3.7, debug@^4.4.0, debug@^4.4.3: version "4.4.3" resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.3.tgz#c6ae432d9bd9662582fce08709b038c58e9e3d6a" @@ -1586,13 +1685,6 @@ diff@^4.0.1: resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== -doctrine@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-3.0.0.tgz#addebead72a6574db783639dc87a121773973961" - integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w== - dependencies: - esutils "^2.0.2" - dunder-proto@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/dunder-proto/-/dunder-proto-1.0.1.tgz#d7ae667e1dc83482f8b70fd0f6eefc50da30f58a" @@ -1627,6 +1719,13 @@ encodeurl@^2.0.0: resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-2.0.0.tgz#7b8ea898077d7e409d3ac45474ea38eaf0857a58" integrity sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg== +end-of-stream@^1.1.0: + version "1.4.5" + resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.5.tgz#7344d711dea40e0b74abc2ed49778743ccedb08c" + integrity sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg== + dependencies: + once "^1.4.0" + error-ex@^1.3.1: version "1.3.4" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.4.tgz#b3a8d8bb6f92eecc1629e3e27d3c8607a8a32414" @@ -1671,7 +1770,7 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== -eslint-plugin-prettier@^5.0.1: +eslint-plugin-prettier@^5.4.1: version "5.5.5" resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.5.tgz#9eae11593faa108859c26f9a9c367d619a0769c0" integrity sha512-hscXkbqUZ2sPithAuLm5MXL+Wph+U7wHngPBv9OMWwlP8iaflyxpjTYZkmdgB4/vPIhemRlBEoLrH7UC1n7aUw== @@ -1679,95 +1778,84 @@ eslint-plugin-prettier@^5.0.1: prettier-linter-helpers "^1.0.1" synckit "^0.11.12" -eslint-plugin-unused-imports@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-3.2.0.tgz#63a98c9ad5f622cd9f830f70bc77739f25ccfe0d" - integrity sha512-6uXyn6xdINEpxE1MtDjxQsyXB37lfyO2yKGVVgtD7WEWQGORSOZjgrD6hBhvGv4/SO+TOlS+UnC6JppRqbuwGQ== - dependencies: - eslint-rule-composer "^0.3.0" - -eslint-rule-composer@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/eslint-rule-composer/-/eslint-rule-composer-0.3.0.tgz#79320c927b0c5c0d3d3d2b76c8b4a488f25bbaf9" - integrity sha512-bt+Sh8CtDmn2OajxvNO+BX7Wn4CIWMpTRm3MaiKPCQcnnlm0CS2mhui6QaoeQugs+3Kj2ESKEEGJUdVafwhiCg== +eslint-plugin-unused-imports@^4.1.4: + version "4.4.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.4.1.tgz#a831f0a2937d7631eba30cb87091ab7d3a5da0e1" + integrity sha512-oZGYUz1X3sRMGUB+0cZyK2VcvRX5lm/vB56PgNNcU+7ficUCKm66oZWKUubXWnOuPjQ8PvmXtCViXBMONPe7tQ== -eslint-scope@^7.2.2: - version "7.2.2" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-7.2.2.tgz#deb4f92563390f32006894af62a22dba1c46423f" - integrity sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg== +eslint-scope@^8.4.0: + version "8.4.0" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-8.4.0.tgz#88e646a207fad61436ffa39eb505147200655c82" + integrity sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg== dependencies: esrecurse "^4.3.0" estraverse "^5.2.0" -eslint-visitor-keys@^3.4.1, eslint-visitor-keys@^3.4.3: +eslint-visitor-keys@^3.4.3: version "3.4.3" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== -eslint-visitor-keys@^4.2.0: +eslint-visitor-keys@^4.2.0, eslint-visitor-keys@^4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz#4cfea60fe7dd0ad8e816e1ed026c1d5251b512c1" integrity sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ== -eslint@^8.49.0: - version "8.57.1" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.57.1.tgz#7df109654aba7e3bbe5c8eae533c5e461d3c6ca9" - integrity sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA== - dependencies: - "@eslint-community/eslint-utils" "^4.2.0" - "@eslint-community/regexpp" "^4.6.1" - "@eslint/eslintrc" "^2.1.4" - "@eslint/js" "8.57.1" - "@humanwhocodes/config-array" "^0.13.0" +eslint@^9.39.1: + version "9.39.4" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.39.4.tgz#855da1b2e2ad66dc5991195f35e262bcec8117b5" + integrity sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ== + dependencies: + "@eslint-community/eslint-utils" "^4.8.0" + "@eslint-community/regexpp" "^4.12.1" + "@eslint/config-array" "^0.21.2" + "@eslint/config-helpers" "^0.4.2" + "@eslint/core" "^0.17.0" + "@eslint/eslintrc" "^3.3.5" + "@eslint/js" "9.39.4" + "@eslint/plugin-kit" "^0.4.1" + "@humanfs/node" "^0.16.6" "@humanwhocodes/module-importer" "^1.0.1" - "@nodelib/fs.walk" "^1.2.8" - "@ungap/structured-clone" "^1.2.0" - ajv "^6.12.4" + "@humanwhocodes/retry" "^0.4.2" + "@types/estree" "^1.0.6" + ajv "^6.14.0" chalk "^4.0.0" - cross-spawn "^7.0.2" + cross-spawn "^7.0.6" debug "^4.3.2" - doctrine "^3.0.0" escape-string-regexp "^4.0.0" - eslint-scope "^7.2.2" - eslint-visitor-keys "^3.4.3" - espree "^9.6.1" - esquery "^1.4.2" + eslint-scope "^8.4.0" + eslint-visitor-keys "^4.2.1" + espree "^10.4.0" + esquery "^1.5.0" esutils "^2.0.2" fast-deep-equal "^3.1.3" - file-entry-cache "^6.0.1" + file-entry-cache "^8.0.0" find-up "^5.0.0" glob-parent "^6.0.2" - globals "^13.19.0" - graphemer "^1.4.0" ignore "^5.2.0" imurmurhash "^0.1.4" is-glob "^4.0.0" - is-path-inside "^3.0.3" - js-yaml "^4.1.0" json-stable-stringify-without-jsonify "^1.0.1" - levn "^0.4.1" lodash.merge "^4.6.2" - minimatch "^3.1.2" + minimatch "^3.1.5" natural-compare "^1.4.0" optionator "^0.9.3" - strip-ansi "^6.0.1" - text-table "^0.2.0" -espree@^9.6.0, espree@^9.6.1: - version "9.6.1" - resolved "https://registry.yarnpkg.com/espree/-/espree-9.6.1.tgz#a2a17b8e434690a5432f2f8018ce71d331a48c6f" - integrity sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ== +espree@^10.0.1, espree@^10.4.0: + version "10.4.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-10.4.0.tgz#d54f4949d4629005a1fa168d937c3ff1f7e2a837" + integrity sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ== dependencies: - acorn "^8.9.0" + acorn "^8.15.0" acorn-jsx "^5.3.2" - eslint-visitor-keys "^3.4.1" + eslint-visitor-keys "^4.2.1" esprima@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== -esquery@^1.4.2: +esquery@^1.5.0: version "1.7.0" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.7.0.tgz#08d048f261f0ddedb5bae95f46809463d9c9496d" integrity sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g== @@ -1839,12 +1927,14 @@ expect@^29.0.0, expect@^29.7.0: jest-message-util "^29.7.0" jest-util "^29.7.0" -express-rate-limit@^7.5.0: - version "7.5.1" - resolved "https://registry.yarnpkg.com/express-rate-limit/-/express-rate-limit-7.5.1.tgz#8c3a42f69209a3a1c969890070ece9e20a879dec" - integrity sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw== +express-rate-limit@^8.2.1: + version "8.3.1" + resolved "https://registry.yarnpkg.com/express-rate-limit/-/express-rate-limit-8.3.1.tgz#0aaba098eadd40f6737f30a98e6b16fa1a29edfb" + integrity sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw== + dependencies: + ip-address "10.1.0" -express@^5.0.1, express@^5.1.0: +express@^5.1.0, express@^5.2.1: version "5.2.1" resolved "https://registry.yarnpkg.com/express/-/express-5.2.1.tgz#8f21d15b6d327f92b4794ecf8cb08a72f956ac04" integrity sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw== @@ -1887,6 +1977,11 @@ external-editor@^3.1.0: iconv-lite "^0.4.24" tmp "^0.0.33" +fast-copy@^4.0.0: + version "4.0.2" + resolved "https://registry.yarnpkg.com/fast-copy/-/fast-copy-4.0.2.tgz#57f14115e1edbec274f69090072a480aa29cbedd" + integrity sha512-ybA6PDXIXOXivLJK/z9e+Otk7ve13I4ckBvGO5I2RRmBU1gMHLVDJYEuJYhGwez7YNlYji2M2DvVU+a9mSFDlw== + fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: version "3.1.3" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" @@ -1918,6 +2013,11 @@ fast-levenshtein@^2.0.6: resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw== +fast-safe-stringify@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz#c406a83b6e70d9e35ce3b30a81141df30aeba884" + integrity sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA== + fast-uri@^3.0.1: version "3.1.0" resolved "https://registry.yarnpkg.com/fast-uri/-/fast-uri-3.1.0.tgz#66eecff6c764c0df9b762e62ca7edcfb53b4edfa" @@ -1942,12 +2042,12 @@ fflate@^0.8.2: resolved "https://registry.yarnpkg.com/fflate/-/fflate-0.8.2.tgz#fc8631f5347812ad6028bbe4a2308b2792aa1dea" integrity sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A== -file-entry-cache@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz#211b2dd9659cb0394b073e7323ac3c933d522027" - integrity sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg== +file-entry-cache@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-8.0.0.tgz#7787bddcf1131bffb92636c69457bbc0edd6d81f" + integrity sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ== dependencies: - flat-cache "^3.0.4" + flat-cache "^4.0.0" fill-range@^7.1.1: version "7.1.1" @@ -1984,14 +2084,13 @@ find-up@^5.0.0: locate-path "^6.0.0" path-exists "^4.0.0" -flat-cache@^3.0.4: - version "3.2.0" - resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-3.2.0.tgz#2c0c2d5040c99b1632771a9d105725c0115363ee" - integrity sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw== +flat-cache@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-4.0.1.tgz#0ece39fcb14ee012f4b0410bd33dd9c1f011127c" + integrity sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw== dependencies: flatted "^3.2.9" - keyv "^4.5.3" - rimraf "^3.0.2" + keyv "^4.5.4" flatted@^3.2.9: version "3.3.3" @@ -2129,12 +2228,10 @@ glob@^7.1.3, glob@^7.1.4: once "^1.3.0" path-is-absolute "^1.0.0" -globals@^13.19.0: - version "13.24.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-13.24.0.tgz#8432a19d78ce0c1e833949c36adb345400bb1171" - integrity sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ== - dependencies: - type-fest "^0.20.2" +globals@^14.0.0: + version "14.0.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-14.0.0.tgz#898d7413c29babcf6bafe56fcadded858ada724e" + integrity sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ== gopd@^1.2.0: version "1.2.0" @@ -2180,6 +2277,16 @@ hasown@^2.0.2: dependencies: function-bind "^1.1.2" +help-me@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/help-me/-/help-me-5.0.0.tgz#b1ebe63b967b74060027c2ac61f9be12d354a6f6" + integrity sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg== + +hono@^4.11.4, hono@^4.12.4: + version "4.12.7" + resolved "https://registry.yarnpkg.com/hono/-/hono-4.12.7.tgz#ca000956e965c2b3d791e43540498e616d6c6442" + integrity sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw== + html-escaper@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" @@ -2264,6 +2371,11 @@ inherits@2, inherits@^2.0.3, inherits@~2.0.4: resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== +ip-address@10.1.0: + version "10.1.0" + resolved "https://registry.yarnpkg.com/ip-address/-/ip-address-10.1.0.tgz#d8dcffb34d0e02eb241427444a6e23f5b0595aa4" + integrity sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q== + ipaddr.js@1.9.1: version "1.9.1" resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3" @@ -2308,11 +2420,6 @@ is-number@^7.0.0: resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== -is-path-inside@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" - integrity sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ== - is-promise@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-4.0.0.tgz#42ff9f84206c1991d26debf520dd5c01042dd2f3" @@ -2739,10 +2846,15 @@ jest@^29.4.0: import-local "^3.0.2" jest-cli "^29.7.0" -jose@^6.1.1: - version "6.1.3" - resolved "https://registry.yarnpkg.com/jose/-/jose-6.1.3.tgz#8453d7be88af7bb7d64a0481d6a35a0145ba3ea5" - integrity sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ== +jose@^6.1.3: + version "6.2.1" + resolved "https://registry.yarnpkg.com/jose/-/jose-6.2.1.tgz#7a6b1de83816deaee9055a558e1278a7b2b9ea1b" + integrity sha512-jUaKr1yrbfaImV7R2TN/b3IcZzsw38/chqMpo2XJ7i2F8AfM/lA4G1goC3JVEwg0H7UldTmSt3P68nt31W7/mw== + +joycon@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/joycon/-/joycon-3.1.1.tgz#bce8596d6ae808f8b68168f5fc69280996894f03" + integrity sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw== "jq-web@https://github.com/stainless-api/jq-web/releases/download/v0.8.8/jq-web.tar.gz": version "0.8.8" @@ -2761,7 +2873,7 @@ js-yaml@^3.13.1: argparse "^1.0.7" esprima "^4.0.0" -js-yaml@^4.1.0: +js-yaml@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.1.tgz#854c292467705b699476e1a2decc0c8a3458806b" integrity sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA== @@ -2817,7 +2929,7 @@ jsonfile@^6.0.1: optionalDependencies: graceful-fs "^4.1.6" -keyv@^4.5.3: +keyv@^4.5.4: version "4.5.4" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.5.4.tgz#a879a99e29452f942439f2a405e3af8b31d4de93" integrity sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw== @@ -2947,10 +3059,10 @@ mimic-fn@^2.1.0: resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== -minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" - integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== +minimatch@^3.0.4, minimatch@^3.1.1, minimatch@^3.1.5: + version "3.1.5" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.5.tgz#580c88f8d5445f2bd6aa8f3cadefa0de79fbd69e" + integrity sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w== dependencies: brace-expansion "^1.1.7" @@ -3040,6 +3152,11 @@ object-inspect@^1.13.3: resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.4.tgz#8375265e21bc20d0fa582c22e1b13485d6e00213" integrity sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew== +on-exit-leak-free@^2.1.0: + version "2.1.2" + resolved "https://registry.yarnpkg.com/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz#fed195c9ebddb7d9e4c3842f93f281ac8dadd3b8" + integrity sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA== + on-finished@^2.4.1: version "2.4.1" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" @@ -3047,7 +3164,7 @@ on-finished@^2.4.1: dependencies: ee-first "1.1.1" -once@^1.3.0, once@^1.4.0: +once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w== @@ -3187,6 +3304,64 @@ picomatch@^2.0.4, picomatch@^2.2.3, picomatch@^2.3.1: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== +pino-abstract-transport@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz#b21e5f33a297e8c4c915c62b3ce5dd4a87a52c23" + integrity sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg== + dependencies: + split2 "^4.0.0" + +pino-http@^11.0.0: + version "11.0.0" + resolved "https://registry.yarnpkg.com/pino-http/-/pino-http-11.0.0.tgz#ebadef4694fc59aadab9be7e5939aea625b4615f" + integrity sha512-wqg5XIAGRRIWtTk8qPGxkbrfiwEWz1lgedVLvhLALudKXvg1/L2lTFgTGPJ4Z2e3qcRmxoFxDuSdMdMGNM6I1g== + dependencies: + get-caller-file "^2.0.5" + pino "^10.0.0" + pino-std-serializers "^7.0.0" + process-warning "^5.0.0" + +pino-pretty@^13.1.3: + version "13.1.3" + resolved "https://registry.yarnpkg.com/pino-pretty/-/pino-pretty-13.1.3.tgz#2274cccda925dd355c104079a5029f6598d0381b" + integrity sha512-ttXRkkOz6WWC95KeY9+xxWL6AtImwbyMHrL1mSwqwW9u+vLp/WIElvHvCSDg0xO/Dzrggz1zv3rN5ovTRVowKg== + dependencies: + colorette "^2.0.7" + dateformat "^4.6.3" + fast-copy "^4.0.0" + fast-safe-stringify "^2.1.1" + help-me "^5.0.0" + joycon "^3.1.1" + minimist "^1.2.6" + on-exit-leak-free "^2.1.0" + pino-abstract-transport "^3.0.0" + pump "^3.0.0" + secure-json-parse "^4.0.0" + sonic-boom "^4.0.1" + strip-json-comments "^5.0.2" + +pino-std-serializers@^7.0.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz#a7b0cd65225f29e92540e7853bd73b07479893fc" + integrity sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw== + +pino@^10.0.0, pino@^10.3.1: + version "10.3.1" + resolved "https://registry.yarnpkg.com/pino/-/pino-10.3.1.tgz#6552c8f8d8481844c9e452e7bf0be90bff1939ce" + integrity sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg== + dependencies: + "@pinojs/redact" "^0.4.0" + atomic-sleep "^1.0.0" + on-exit-leak-free "^2.1.0" + pino-abstract-transport "^3.0.0" + pino-std-serializers "^7.0.0" + process-warning "^5.0.0" + quick-format-unescaped "^4.0.3" + real-require "^0.2.0" + safe-stable-stringify "^2.3.1" + sonic-boom "^4.0.1" + thread-stream "^4.0.0" + pirates@^4.0.4: version "4.0.7" resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.7.tgz#643b4a18c4257c8a65104b73f3049ce9a0a15e22" @@ -3235,6 +3410,11 @@ pretty-format@^29.0.0, pretty-format@^29.7.0: ansi-styles "^5.0.0" react-is "^18.0.0" +process-warning@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/process-warning/-/process-warning-5.0.0.tgz#566e0bf79d1dff30a72d8bbbe9e8ecefe8d378d7" + integrity sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA== + prompts@^2.0.1: version "2.4.2" resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.4.2.tgz#7b57e73b3a48029ad10ebd44f74b01722a4cb069" @@ -3251,6 +3431,14 @@ proxy-addr@^2.0.7: forwarded "0.2.0" ipaddr.js "1.9.1" +pump@^3.0.0: + version "3.0.4" + resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.4.tgz#1f313430527fa8b905622ebd22fe1444e757ab3c" + integrity sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA== + dependencies: + end-of-stream "^1.1.0" + once "^1.3.1" + punycode@^2.1.0: version "2.3.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5" @@ -3273,6 +3461,11 @@ queue-microtask@^1.2.2: resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243" integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A== +quick-format-unescaped@^4.0.3: + version "4.0.4" + resolved "https://registry.yarnpkg.com/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz#93ef6dd8d3453cbc7970dd614fad4c5954d6b5a7" + integrity sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg== + range-parser@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" @@ -3302,6 +3495,11 @@ readable-stream@^3.4.0: string_decoder "^1.1.1" util-deprecate "^1.0.1" +real-require@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/real-require/-/real-require-0.2.0.tgz#209632dea1810be2ae063a6ac084fee7e33fba78" + integrity sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg== + require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" @@ -3348,13 +3546,6 @@ reusify@^1.0.4: resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.1.0.tgz#0fe13b9522e1473f51b558ee796e08f11f9b489f" integrity sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw== -rimraf@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a" - integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA== - dependencies: - glob "^7.1.3" - router@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/router/-/router-2.2.0.tgz#019be620b711c87641167cc79b99090f00b146ef" @@ -3378,11 +3569,21 @@ safe-buffer@~5.2.0: resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== +safe-stable-stringify@^2.3.1: + version "2.5.0" + resolved "https://registry.yarnpkg.com/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz#4ca2f8e385f2831c432a719b108a3bf7af42a1dd" + integrity sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA== + "safer-buffer@>= 2.1.2 < 3", "safer-buffer@>= 2.1.2 < 3.0.0": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== +secure-json-parse@^4.0.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/secure-json-parse/-/secure-json-parse-4.1.0.tgz#4f1ab41c67a13497ea1b9131bb4183a22865477c" + integrity sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA== + semver@^6.3.0, semver@^6.3.1: version "6.3.1" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.1.tgz#556d2ef8689146e46dcea4bfdd095f3434dffcb4" @@ -3497,6 +3698,13 @@ slash@^3.0.0: resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== +sonic-boom@^4.0.1: + version "4.2.1" + resolved "https://registry.yarnpkg.com/sonic-boom/-/sonic-boom-4.2.1.tgz#28598250df4899c0ac572d7e2f0460690ba6a030" + integrity sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q== + dependencies: + atomic-sleep "^1.0.0" + source-map-support@0.5.13: version "0.5.13" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.13.tgz#31b24a9c2e73c2de85066c0feb7d44767ed52932" @@ -3510,6 +3718,11 @@ source-map@^0.6.0, source-map@^0.6.1: resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== +split2@^4.0.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/split2/-/split2-4.2.0.tgz#c9c5920904d148bab0b9f67145f245a86aadbfa4" + integrity sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg== + sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" @@ -3585,6 +3798,11 @@ strip-json-comments@^3.1.1: resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== +strip-json-comments@^5.0.2: + version "5.0.3" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-5.0.3.tgz#b7304249dd402ee67fd518ada993ab3593458bcf" + integrity sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw== + superstruct@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/superstruct/-/superstruct-1.0.4.tgz#0adb99a7578bd2f1c526220da6571b2d485d91ca" @@ -3625,10 +3843,12 @@ test-exclude@^6.0.0: glob "^7.1.4" minimatch "^3.0.4" -text-table@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" - integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw== +thread-stream@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/thread-stream/-/thread-stream-4.0.0.tgz#732f007c24da7084f729d6e3a7e3f5934a7380b7" + integrity sha512-4iMVL6HAINXWf1ZKZjIPcz5wYaOdPhtO8ATvZ+Xqp3BTdaqtAwQkNmKORqcIo5YkQqGXq5cwfswDwMqqQNrpJA== + dependencies: + real-require "^0.2.0" tmp@^0.0.33: version "0.0.33" @@ -3742,11 +3962,6 @@ type-detect@4.0.8: resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== -type-fest@^0.20.2: - version "0.20.2" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4" - integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ== - type-fest@^0.21.3: version "0.21.3" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.21.3.tgz#d260a24b0198436e133fa26a524a6d65fa3b2e37" @@ -3933,7 +4148,7 @@ yoctocolors-cjs@^2.1.2: resolved "https://registry.yarnpkg.com/yoctocolors-cjs/-/yoctocolors-cjs-2.1.3.tgz#7e4964ea8ec422b7a40ac917d3a344cfd2304baa" integrity sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw== -zod-to-json-schema@^3.24.5, zod-to-json-schema@^3.24.6, zod-to-json-schema@^3.25.0: +zod-to-json-schema@^3.24.5, zod-to-json-schema@^3.24.6, zod-to-json-schema@^3.25.1: version "3.25.1" resolved "https://registry.yarnpkg.com/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz#7f24962101a439ddade2bf1aeab3c3bfec7d84ba" integrity sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA== diff --git a/release-please-config.json b/release-please-config.json index b1909804..9b042792 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -68,6 +68,11 @@ "type": "json", "path": "packages/mcp-server/package.json", "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/mcp-server/manifest.json", + "jsonpath": "$.version" } ] } diff --git a/scripts/mock b/scripts/mock deleted file mode 100755 index 0b28f6ea..00000000 --- a/scripts/mock +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash - -set -e - -cd "$(dirname "$0")/.." - -if [[ -n "$1" && "$1" != '--'* ]]; then - URL="$1" - shift -else - URL="$(grep 'openapi_spec_url' .stats.yml | cut -d' ' -f2)" -fi - -# Check if the URL is empty -if [ -z "$URL" ]; then - echo "Error: No OpenAPI spec path/url provided or found in .stats.yml" - exit 1 -fi - -echo "==> Starting mock server with URL ${URL}" - -# Run prism mock on the given spec -if [ "$1" == "--daemon" ]; then - npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log & - - # Wait for server to come online - echo -n "Waiting for server" - while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do - echo -n "." - sleep 0.1 - done - - if grep -q "✖ fatal" ".prism.log"; then - cat .prism.log - exit 1 - fi - - echo -else - npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" -fi diff --git a/scripts/test b/scripts/test index 7bce0516..548da9bb 100755 --- a/scripts/test +++ b/scripts/test @@ -4,53 +4,7 @@ set -e cd "$(dirname "$0")/.." -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[0;33m' -NC='\033[0m' # No Color -function prism_is_running() { - curl --silent "http://localhost:4010" >/dev/null 2>&1 -} - -kill_server_on_port() { - pids=$(lsof -t -i tcp:"$1" || echo "") - if [ "$pids" != "" ]; then - kill "$pids" - echo "Stopped $pids." - fi -} - -function is_overriding_api_base_url() { - [ -n "$TEST_API_BASE_URL" ] -} - -if ! is_overriding_api_base_url && ! prism_is_running ; then - # When we exit this script, make sure to kill the background mock server process - trap 'kill_server_on_port 4010' EXIT - - # Start the dev server - ./scripts/mock --daemon -fi - -if is_overriding_api_base_url ; then - echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" - echo -elif ! prism_is_running ; then - echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" - echo -e "running against your OpenAPI spec." - echo - echo -e "To run the server, pass in the path or url of your OpenAPI" - echo -e "spec to the prism command:" - echo - echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}" - echo - - exit 1 -else - echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" - echo -fi echo "==> Running tests" ./node_modules/.bin/jest "$@" diff --git a/src/client.ts b/src/client.ts index ef1cc2fb..7be4e749 100644 --- a/src/client.ts +++ b/src/client.ts @@ -11,6 +11,7 @@ import type { APIResponseProps } from './internal/parse'; import { getPlatformHeaders } from './internal/detect-platform'; import * as Shims from './internal/shims'; import * as Opts from './internal/request-options'; +import { stringifyQuery } from './internal/utils/query'; import { VERSION } from './version'; import * as Errors from './core/error'; import * as Uploads from './core/uploads'; @@ -323,21 +324,8 @@ export class ImageKit { /** * Basic re-implementation of `qs.stringify` for primitive types. */ - protected stringifyQuery(query: Record): string { - return Object.entries(query) - .filter(([_, value]) => typeof value !== 'undefined') - .map(([key, value]) => { - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - } - if (value === null) { - return `${encodeURIComponent(key)}=`; - } - throw new Errors.ImageKitError( - `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`, - ); - }) - .join('&'); + protected stringifyQuery(query: object | Record): string { + return stringifyQuery(query); } private getUserAgent(): string { @@ -369,12 +357,13 @@ export class ImageKit { : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); const defaultQuery = this.defaultQuery(); - if (!isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; + const pathQuery = Object.fromEntries(url.searchParams); + if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) { + query = { ...pathQuery, ...defaultQuery, ...query }; } if (typeof query === 'object' && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query as Record); + url.search = this.stringifyQuery(query); } return url.toString(); @@ -558,7 +547,7 @@ export class ImageKit { loggerFor(this).info(`${responseInfo} - ${retryMessage}`); const errText = await response.text().catch((err: any) => castToError(err).message); - const errJSON = safeJSON(errText); + const errJSON = safeJSON(errText) as any; const errMessage = errJSON ? undefined : errText; loggerFor(this).debug( @@ -599,9 +588,10 @@ export class ImageKit { controller: AbortController, ): Promise { const { signal, method, ...options } = init || {}; - if (signal) signal.addEventListener('abort', () => controller.abort()); + const abort = this._makeAbort(controller); + if (signal) signal.addEventListener('abort', abort, { once: true }); - const timeout = setTimeout(() => controller.abort(), ms); + const timeout = setTimeout(abort, ms); const isReadableBody = ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) || @@ -678,9 +668,9 @@ export class ImageKit { } } - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says, but otherwise calculate a default - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + // If the API asks us to wait a certain amount of time, just do what it + // says, but otherwise calculate a default + if (timeoutMillis === undefined) { const maxRetries = options.maxRetries ?? this.maxRetries; timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } @@ -768,6 +758,12 @@ export class ImageKit { return headers.values; } + private _makeAbort(controller: AbortController) { + // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure + // would capture all request options, and cause a memory leak. + return () => controller.abort(); + } + private buildBody({ options: { body, headers: rawHeaders } }: { options: FinalRequestOptions }): { bodyHeaders: HeadersLike; body: BodyInit | undefined; @@ -800,6 +796,14 @@ export class ImageKit { (Symbol.iterator in body && 'next' in body && typeof body.next === 'function')) ) { return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable) }; + } else if ( + typeof body === 'object' && + headers.values.get('content-type') === 'application/x-www-form-urlencoded' + ) { + return { + bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' }, + body: this.stringifyQuery(body), + }; } else { return this.#encoder({ body, headers }); } diff --git a/src/internal/parse.ts b/src/internal/parse.ts index 10d1ca90..611cd86d 100644 --- a/src/internal/parse.ts +++ b/src/internal/parse.ts @@ -29,6 +29,12 @@ export async function defaultParseResponse(client: ImageKit, props: APIRespon const mediaType = contentType?.split(';')[0]?.trim(); const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); if (isJSON) { + const contentLength = response.headers.get('content-length'); + if (contentLength === '0') { + // if there is no content we can't do anything + return undefined as T; + } + const json = await response.json(); return json as T; } diff --git a/src/internal/utils.ts b/src/internal/utils.ts index 3cbfacce..c591353b 100644 --- a/src/internal/utils.ts +++ b/src/internal/utils.ts @@ -6,3 +6,4 @@ export * from './utils/env'; export * from './utils/log'; export * from './utils/uuid'; export * from './utils/sleep'; +export * from './utils/query'; diff --git a/src/internal/utils/query.ts b/src/internal/utils/query.ts new file mode 100644 index 00000000..530162a7 --- /dev/null +++ b/src/internal/utils/query.ts @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { ImageKitError } from '../../core/error'; + +/** + * Basic re-implementation of `qs.stringify` for primitive types. + */ +export function stringifyQuery(query: object | Record) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new ImageKitError( + `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`, + ); + }) + .join('&'); +} diff --git a/src/resources/beta/v2/files.ts b/src/resources/beta/v2/files.ts index 09d55b2c..f3003db6 100644 --- a/src/resources/beta/v2/files.ts +++ b/src/resources/beta/v2/files.ts @@ -22,10 +22,11 @@ export class Files extends APIResource { * about how to implement secure client-side file upload. * * **File size limit** \ - * On the free plan, the maximum upload file sizes are 20MB for images, audio, and raw - * files, and 100MB for videos. On the paid plan, these limits increase to 40MB for - * images, audio, and raw files, and 2GB for videos. These limits can be further increased - * with higher-tier plans. + * On the free plan, the maximum upload file sizes are 25MB for images, audio, and raw + * files, and 100MB for videos. On the Lite paid plan, these limits increase to 40MB + * for images, audio, and raw files and 300MB for videos, whereas on the Pro paid plan, + * these limits increase to 50MB for images, audio, and raw files and 2GB for videos. + * These limits can be further increased with enterprise plans. * * **Version limit** \ * A file can have a maximum of 100 versions. diff --git a/src/resources/files/files.ts b/src/resources/files/files.ts index 229a3cfe..1025de95 100644 --- a/src/resources/files/files.ts +++ b/src/resources/files/files.ts @@ -152,10 +152,11 @@ export class Files extends APIResource { * by verifying the entire payload using JWT. * * **File size limit** \ - * On the free plan, the maximum upload file sizes are 20MB for images, audio, and raw - * files and 100MB for videos. On the paid plan, these limits increase to 40MB for images, - * audio, and raw files and 2GB for videos. These limits can be further increased with - * higher-tier plans. + * On the free plan, the maximum upload file sizes are 25MB for images, audio, and raw + * files and 100MB for videos. On the Lite paid plan, these limits increase to 40MB + * for images, audio, and raw files and 300MB for videos, whereas on the Pro paid plan, + * these limits increase to 50MB for images, audio, and raw files and 2GB for videos. + * These limits can be further increased with enterprise plans. * * **Version limit** \ * A file can have a maximum of 100 versions. diff --git a/src/version.ts b/src/version.ts index 3f5548b7..06a61128 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '7.3.0'; // x-release-please-version +export const VERSION = '7.4.0'; // x-release-please-version diff --git a/tests/api-resources/accounts/origins.test.ts b/tests/api-resources/accounts/origins.test.ts index f912c7ea..2be57f09 100644 --- a/tests/api-resources/accounts/origins.test.ts +++ b/tests/api-resources/accounts/origins.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource origins', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.accounts.origins.create({ accessKey: 'AKIAIOSFODNN7EXAMPLE', @@ -27,7 +27,7 @@ describe('resource origins', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.accounts.origins.create({ accessKey: 'AKIAIOSFODNN7EXAMPLE', @@ -41,7 +41,7 @@ describe('resource origins', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('update: only required params', async () => { const responsePromise = client.accounts.origins.update('id', { accessKey: 'AKIAIOSFODNN7EXAMPLE', @@ -59,7 +59,7 @@ describe('resource origins', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.accounts.origins.update('id', { accessKey: 'AKIAIOSFODNN7EXAMPLE', @@ -73,7 +73,7 @@ describe('resource origins', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('list', async () => { const responsePromise = client.accounts.origins.list(); const rawResponse = await responsePromise.asResponse(); @@ -85,7 +85,7 @@ describe('resource origins', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete', async () => { const responsePromise = client.accounts.origins.delete('id'); const rawResponse = await responsePromise.asResponse(); @@ -97,7 +97,7 @@ describe('resource origins', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get', async () => { const responsePromise = client.accounts.origins.get('id'); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/accounts/url-endpoints.test.ts b/tests/api-resources/accounts/url-endpoints.test.ts index eea18604..b53af030 100644 --- a/tests/api-resources/accounts/url-endpoints.test.ts +++ b/tests/api-resources/accounts/url-endpoints.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource urlEndpoints', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.accounts.urlEndpoints.create({ description: 'My custom URL endpoint' }); const rawResponse = await responsePromise.asResponse(); @@ -21,7 +21,7 @@ describe('resource urlEndpoints', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.accounts.urlEndpoints.create({ description: 'My custom URL endpoint', @@ -31,7 +31,7 @@ describe('resource urlEndpoints', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('update: only required params', async () => { const responsePromise = client.accounts.urlEndpoints.update('id', { description: 'My custom URL endpoint', @@ -45,7 +45,7 @@ describe('resource urlEndpoints', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('update: required and optional params', async () => { const response = await client.accounts.urlEndpoints.update('id', { description: 'My custom URL endpoint', @@ -55,7 +55,7 @@ describe('resource urlEndpoints', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('list', async () => { const responsePromise = client.accounts.urlEndpoints.list(); const rawResponse = await responsePromise.asResponse(); @@ -67,7 +67,7 @@ describe('resource urlEndpoints', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete', async () => { const responsePromise = client.accounts.urlEndpoints.delete('id'); const rawResponse = await responsePromise.asResponse(); @@ -79,7 +79,7 @@ describe('resource urlEndpoints', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get', async () => { const responsePromise = client.accounts.urlEndpoints.get('id'); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/accounts/usage.test.ts b/tests/api-resources/accounts/usage.test.ts index 98f51e3f..161cdc71 100644 --- a/tests/api-resources/accounts/usage.test.ts +++ b/tests/api-resources/accounts/usage.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource usage', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('get: only required params', async () => { const responsePromise = client.accounts.usage.get({ endDate: '2019-12-27', startDate: '2019-12-27' }); const rawResponse = await responsePromise.asResponse(); @@ -21,7 +21,7 @@ describe('resource usage', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get: required and optional params', async () => { const response = await client.accounts.usage.get({ endDate: '2019-12-27', startDate: '2019-12-27' }); }); diff --git a/tests/api-resources/assets.test.ts b/tests/api-resources/assets.test.ts index 4688d817..bf41276e 100644 --- a/tests/api-resources/assets.test.ts +++ b/tests/api-resources/assets.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource assets', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('list', async () => { const responsePromise = client.assets.list(); const rawResponse = await responsePromise.asResponse(); @@ -21,7 +21,7 @@ describe('resource assets', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('list: request options and params are passed correctly', async () => { // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error await expect( diff --git a/tests/api-resources/beta/v2/files.test.ts b/tests/api-resources/beta/v2/files.test.ts index c3fc2bc0..69af3768 100644 --- a/tests/api-resources/beta/v2/files.test.ts +++ b/tests/api-resources/beta/v2/files.test.ts @@ -9,10 +9,10 @@ const client = new ImageKit({ }); describe('resource files', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('upload: only required params', async () => { const responsePromise = client.beta.v2.files.upload({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), + file: await toFile(Buffer.from('Example data'), 'README.md'), fileName: 'fileName', }); const rawResponse = await responsePromise.asResponse(); @@ -24,10 +24,10 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('upload: required and optional params', async () => { const response = await client.beta.v2.files.upload({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), + file: await toFile(Buffer.from('Example data'), 'README.md'), fileName: 'fileName', token: 'token', checks: '"request.folder" : "marketing/"\n', diff --git a/tests/api-resources/cache/invalidation.test.ts b/tests/api-resources/cache/invalidation.test.ts index 02f3d4cc..d804f743 100644 --- a/tests/api-resources/cache/invalidation.test.ts +++ b/tests/api-resources/cache/invalidation.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource invalidation', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.cache.invalidation.create({ url: 'https://ik.imagekit.io/your_imagekit_id/default-image.jpg', @@ -23,14 +23,14 @@ describe('resource invalidation', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.cache.invalidation.create({ url: 'https://ik.imagekit.io/your_imagekit_id/default-image.jpg', }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get', async () => { const responsePromise = client.cache.invalidation.get('requestId'); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/custom-metadata-fields.test.ts b/tests/api-resources/custom-metadata-fields.test.ts index 5f36ce66..3fbf78f7 100644 --- a/tests/api-resources/custom-metadata-fields.test.ts +++ b/tests/api-resources/custom-metadata-fields.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource customMetadataFields', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.customMetadataFields.create({ label: 'price', @@ -25,7 +25,7 @@ describe('resource customMetadataFields', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.customMetadataFields.create({ label: 'price', @@ -43,7 +43,7 @@ describe('resource customMetadataFields', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('update', async () => { const responsePromise = client.customMetadataFields.update('id'); const rawResponse = await responsePromise.asResponse(); @@ -55,7 +55,7 @@ describe('resource customMetadataFields', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('update: request options and params are passed correctly', async () => { // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error await expect( @@ -78,7 +78,7 @@ describe('resource customMetadataFields', () => { ).rejects.toThrow(ImageKit.NotFoundError); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('list', async () => { const responsePromise = client.customMetadataFields.list(); const rawResponse = await responsePromise.asResponse(); @@ -90,7 +90,7 @@ describe('resource customMetadataFields', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('list: request options and params are passed correctly', async () => { // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error await expect( @@ -101,7 +101,7 @@ describe('resource customMetadataFields', () => { ).rejects.toThrow(ImageKit.NotFoundError); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete', async () => { const responsePromise = client.customMetadataFields.delete('id'); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/files/bulk.test.ts b/tests/api-resources/files/bulk.test.ts index c5c290a7..1c417b90 100644 --- a/tests/api-resources/files/bulk.test.ts +++ b/tests/api-resources/files/bulk.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource bulk', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete: only required params', async () => { const responsePromise = client.files.bulk.delete({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], @@ -23,14 +23,14 @@ describe('resource bulk', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete: required and optional params', async () => { const response = await client.files.bulk.delete({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('addTags: only required params', async () => { const responsePromise = client.files.bulk.addTags({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], @@ -45,7 +45,7 @@ describe('resource bulk', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('addTags: required and optional params', async () => { const response = await client.files.bulk.addTags({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], @@ -53,7 +53,7 @@ describe('resource bulk', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('removeAITags: only required params', async () => { const responsePromise = client.files.bulk.removeAITags({ AITags: ['t-shirt', 'round-neck', 'sale2019'], @@ -68,7 +68,7 @@ describe('resource bulk', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('removeAITags: required and optional params', async () => { const response = await client.files.bulk.removeAITags({ AITags: ['t-shirt', 'round-neck', 'sale2019'], @@ -76,7 +76,7 @@ describe('resource bulk', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('removeTags: only required params', async () => { const responsePromise = client.files.bulk.removeTags({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], @@ -91,7 +91,7 @@ describe('resource bulk', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('removeTags: required and optional params', async () => { const response = await client.files.bulk.removeTags({ fileIds: ['598821f949c0a938d57563bd', '598821f949c0a938d57563be'], diff --git a/tests/api-resources/files/files.test.ts b/tests/api-resources/files/files.test.ts index c744c6f6..aeb90697 100644 --- a/tests/api-resources/files/files.test.ts +++ b/tests/api-resources/files/files.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource files', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('update', async () => { const responsePromise = client.files.update('fileId', {}); const rawResponse = await responsePromise.asResponse(); @@ -21,7 +21,7 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete', async () => { const responsePromise = client.files.delete('fileId'); const rawResponse = await responsePromise.asResponse(); @@ -33,7 +33,7 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('copy: only required params', async () => { const responsePromise = client.files.copy({ destinationPath: '/folder/to/copy/into/', @@ -48,7 +48,7 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('copy: required and optional params', async () => { const response = await client.files.copy({ destinationPath: '/folder/to/copy/into/', @@ -57,7 +57,7 @@ describe('resource files', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get', async () => { const responsePromise = client.files.get('fileId'); const rawResponse = await responsePromise.asResponse(); @@ -69,7 +69,7 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('move: only required params', async () => { const responsePromise = client.files.move({ destinationPath: '/folder/to/move/into/', @@ -84,7 +84,7 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('move: required and optional params', async () => { const response = await client.files.move({ destinationPath: '/folder/to/move/into/', @@ -92,7 +92,7 @@ describe('resource files', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('rename: only required params', async () => { const responsePromise = client.files.rename({ filePath: '/path/to/file.jpg', @@ -107,7 +107,7 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('rename: required and optional params', async () => { const response = await client.files.rename({ filePath: '/path/to/file.jpg', @@ -116,10 +116,10 @@ describe('resource files', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('upload: only required params', async () => { const responsePromise = client.files.upload({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), + file: await toFile(Buffer.from('Example data'), 'README.md'), fileName: 'fileName', }); const rawResponse = await responsePromise.asResponse(); @@ -131,10 +131,10 @@ describe('resource files', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('upload: required and optional params', async () => { const response = await client.files.upload({ - file: await toFile(Buffer.from('# my file contents'), 'README.md'), + file: await toFile(Buffer.from('Example data'), 'README.md'), fileName: 'fileName', token: 'token', checks: '"request.folder" : "marketing/"\n', diff --git a/tests/api-resources/files/metadata.test.ts b/tests/api-resources/files/metadata.test.ts index b7da8ebf..fd318072 100644 --- a/tests/api-resources/files/metadata.test.ts +++ b/tests/api-resources/files/metadata.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource metadata', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('get', async () => { const responsePromise = client.files.metadata.get('fileId'); const rawResponse = await responsePromise.asResponse(); @@ -21,7 +21,7 @@ describe('resource metadata', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('getFromURL: only required params', async () => { const responsePromise = client.files.metadata.getFromURL({ url: 'https://example.com' }); const rawResponse = await responsePromise.asResponse(); @@ -33,7 +33,7 @@ describe('resource metadata', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('getFromURL: required and optional params', async () => { const response = await client.files.metadata.getFromURL({ url: 'https://example.com' }); }); diff --git a/tests/api-resources/files/versions.test.ts b/tests/api-resources/files/versions.test.ts index c1bb6d4c..873ec8cc 100644 --- a/tests/api-resources/files/versions.test.ts +++ b/tests/api-resources/files/versions.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource versions', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('list', async () => { const responsePromise = client.files.versions.list('fileId'); const rawResponse = await responsePromise.asResponse(); @@ -21,7 +21,7 @@ describe('resource versions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete: only required params', async () => { const responsePromise = client.files.versions.delete('versionId', { fileId: 'fileId' }); const rawResponse = await responsePromise.asResponse(); @@ -33,12 +33,12 @@ describe('resource versions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete: required and optional params', async () => { const response = await client.files.versions.delete('versionId', { fileId: 'fileId' }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get: only required params', async () => { const responsePromise = client.files.versions.get('versionId', { fileId: 'fileId' }); const rawResponse = await responsePromise.asResponse(); @@ -50,12 +50,12 @@ describe('resource versions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get: required and optional params', async () => { const response = await client.files.versions.get('versionId', { fileId: 'fileId' }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('restore: only required params', async () => { const responsePromise = client.files.versions.restore('versionId', { fileId: 'fileId' }); const rawResponse = await responsePromise.asResponse(); @@ -67,7 +67,7 @@ describe('resource versions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('restore: required and optional params', async () => { const response = await client.files.versions.restore('versionId', { fileId: 'fileId' }); }); diff --git a/tests/api-resources/folders/folders.test.ts b/tests/api-resources/folders/folders.test.ts index a983ec4a..c4672ba4 100644 --- a/tests/api-resources/folders/folders.test.ts +++ b/tests/api-resources/folders/folders.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource folders', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.folders.create({ folderName: 'summer', @@ -24,7 +24,7 @@ describe('resource folders', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.folders.create({ folderName: 'summer', @@ -32,7 +32,7 @@ describe('resource folders', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete: only required params', async () => { const responsePromise = client.folders.delete({ folderPath: '/folder/to/delete/' }); const rawResponse = await responsePromise.asResponse(); @@ -44,12 +44,12 @@ describe('resource folders', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete: required and optional params', async () => { const response = await client.folders.delete({ folderPath: '/folder/to/delete/' }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('copy: only required params', async () => { const responsePromise = client.folders.copy({ destinationPath: '/path/of/destination/folder', @@ -64,7 +64,7 @@ describe('resource folders', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('copy: required and optional params', async () => { const response = await client.folders.copy({ destinationPath: '/path/of/destination/folder', @@ -73,7 +73,7 @@ describe('resource folders', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('move: only required params', async () => { const responsePromise = client.folders.move({ destinationPath: '/path/of/destination/folder', @@ -88,7 +88,7 @@ describe('resource folders', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('move: required and optional params', async () => { const response = await client.folders.move({ destinationPath: '/path/of/destination/folder', @@ -96,7 +96,7 @@ describe('resource folders', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('rename: only required params', async () => { const responsePromise = client.folders.rename({ folderPath: '/path/of/folder', @@ -111,7 +111,7 @@ describe('resource folders', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('rename: required and optional params', async () => { const response = await client.folders.rename({ folderPath: '/path/of/folder', diff --git a/tests/api-resources/folders/job.test.ts b/tests/api-resources/folders/job.test.ts index e15071f7..7ab1e5ac 100644 --- a/tests/api-resources/folders/job.test.ts +++ b/tests/api-resources/folders/job.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource job', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('get', async () => { const responsePromise = client.folders.job.get('jobId'); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/saved-extensions.test.ts b/tests/api-resources/saved-extensions.test.ts index 07d9d782..5b4a731e 100644 --- a/tests/api-resources/saved-extensions.test.ts +++ b/tests/api-resources/saved-extensions.test.ts @@ -9,7 +9,7 @@ const client = new ImageKit({ }); describe('resource savedExtensions', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: only required params', async () => { const responsePromise = client.savedExtensions.create({ config: { name: 'remove-bg' }, @@ -25,7 +25,7 @@ describe('resource savedExtensions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: required and optional params', async () => { const response = await client.savedExtensions.create({ config: { @@ -42,7 +42,7 @@ describe('resource savedExtensions', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('update', async () => { const responsePromise = client.savedExtensions.update('id', {}); const rawResponse = await responsePromise.asResponse(); @@ -54,7 +54,7 @@ describe('resource savedExtensions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('list', async () => { const responsePromise = client.savedExtensions.list(); const rawResponse = await responsePromise.asResponse(); @@ -66,7 +66,7 @@ describe('resource savedExtensions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('delete', async () => { const responsePromise = client.savedExtensions.delete('id'); const rawResponse = await responsePromise.asResponse(); @@ -78,7 +78,7 @@ describe('resource savedExtensions', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('get', async () => { const responsePromise = client.savedExtensions.get('id'); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/webhooks.test.ts b/tests/api-resources/webhooks.test.ts index 8fd83de9..e5547f28 100644 --- a/tests/api-resources/webhooks.test.ts +++ b/tests/api-resources/webhooks.test.ts @@ -11,13 +11,13 @@ const client = new ImageKit({ }); describe('resource webhooks', () => { - test.skip('unwrap', async () => { + test.skip('unwrap', () => { const key = 'whsec_c2VjcmV0Cg=='; const payload = '{"id":"id","type":"video.transformation.accepted","created_at":"2019-12-27T18:11:19.117Z","data":{"asset":{"url":"https://example.com"},"transformation":{"type":"video-transformation","options":{"audio_codec":"aac","auto_rotate":true,"format":"mp4","quality":0,"stream_protocol":"HLS","variants":["string"],"video_codec":"h264"}}},"request":{"url":"https://example.com","x_request_id":"x_request_id","user_agent":"user_agent"}}'; const msgID = '1'; const timestamp = new Date(); - const wh = new Webhook(key); + const wh = new Webhook('whsec_c2VjcmV0Cg=='); const signature = wh.sign(msgID, timestamp, payload); const headers: Record = { 'webhook-signature': signature, @@ -25,19 +25,41 @@ describe('resource webhooks', () => { 'webhook-timestamp': String(Math.floor(timestamp.getTime() / 1000)), }; client.webhooks.unwrap(payload, { headers, key }); + client.withOptions({ webhookSecret: key }).webhooks.unwrap(payload, { headers }); + client.withOptions({ webhookSecret: 'whsec_aaaaaaaaaa==' }).webhooks.unwrap(payload, { headers, key }); expect(() => { const wrongKey = 'whsec_aaaaaaaaaa=='; client.webhooks.unwrap(payload, { headers, key: wrongKey }); }).toThrow('No matching signature found'); + expect(() => { + const wrongKey = 'whsec_aaaaaaaaaa=='; + client.withOptions({ webhookSecret: wrongKey }).webhooks.unwrap(payload, { headers }); + }).toThrow('No matching signature found'); expect(() => { const badSig = wh.sign(msgID, timestamp, 'some other payload'); client.webhooks.unwrap(payload, { headers: { ...headers, 'webhook-signature': badSig }, key }); }).toThrow('No matching signature found'); + expect(() => { + const badSig = wh.sign(msgID, timestamp, 'some other payload'); + client + .withOptions({ webhookSecret: key }) + .webhooks.unwrap(payload, { headers: { ...headers, 'webhook-signature': badSig } }); + }).toThrow('No matching signature found'); expect(() => { client.webhooks.unwrap(payload, { headers: { ...headers, 'webhook-timestamp': '5' }, key }); }).toThrow('Message timestamp too old'); + expect(() => { + client + .withOptions({ webhookSecret: key }) + .webhooks.unwrap(payload, { headers: { ...headers, 'webhook-timestamp': '5' } }); + }).toThrow('Message timestamp too old'); expect(() => { client.webhooks.unwrap(payload, { headers: { ...headers, 'webhook-id': 'wrong' }, key }); }).toThrow('No matching signature found'); + expect(() => { + client + .withOptions({ webhookSecret: key }) + .webhooks.unwrap(payload, { headers: { ...headers, 'webhook-id': 'wrong' } }); + }).toThrow('No matching signature found'); }); }); diff --git a/tests/stringifyQuery.test.ts b/tests/stringifyQuery.test.ts index c3193151..4fa1d747 100644 --- a/tests/stringifyQuery.test.ts +++ b/tests/stringifyQuery.test.ts @@ -1,8 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { ImageKit } from '@imagekit/nodejs'; - -const { stringifyQuery } = ImageKit.prototype as any; +import { stringifyQuery } from '@imagekit/nodejs/internal/utils/query'; describe(stringifyQuery, () => { for (const [input, expected] of [ @@ -15,7 +13,7 @@ describe(stringifyQuery, () => { 'e=f', )}=${encodeURIComponent('g&h')}`, ], - ]) { + ] as const) { it(`${JSON.stringify(input)} -> ${expected}`, () => { expect(stringifyQuery(input)).toEqual(expected); }); diff --git a/yarn.lock b/yarn.lock index 2dc54a9d..b1a483e1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1224,18 +1224,10 @@ baseline-browser-mapping@^2.9.0: resolved "https://registry.yarnpkg.com/baseline-browser-mapping/-/baseline-browser-mapping-2.9.14.tgz#3b6af0bc032445bca04de58caa9a87cfe921cbb3" integrity sha512-B0xUquLkiGLgHhpPBqvl7GWegWBUNuujQ6kXd/r1U38ElPT6Ok8KZ8e+FpUGEc2ZoRQUzq/aUnaKFc/svWUGSg== -brace-expansion@^1.1.7: - version "1.1.12" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.12.tgz#ab9b454466e5a8cc3a187beaad580412a9c5b843" - integrity sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -brace-expansion@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.2.tgz#54fc53237a613d854c7bd37463aad17df87214e7" - integrity sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ== +brace-expansion@^2.0.2: + version "2.0.3" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.3.tgz#0493338bdd58e319b1039c67cf7ee439892c01d9" + integrity sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA== dependencies: balanced-match "^1.0.0" @@ -1400,11 +1392,6 @@ commander@^10.0.1: resolved "https://registry.yarnpkg.com/commander/-/commander-10.0.1.tgz#881ee46b4f77d1c1dccc5823433aa39b022cbe06" integrity sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug== -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== - convert-source-map@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-2.0.0.tgz#4b560f649fc4e918dd0ab75cf4961e8bc882d82a" @@ -2610,26 +2597,12 @@ mimic-fn@^2.1.0: resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== -minimatch@^3.0.4, minimatch@^3.1.1, minimatch@^3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" - integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== - dependencies: - brace-expansion "^1.1.7" - -minimatch@^5.0.1: - version "5.1.6" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.6.tgz#1cfcb8cf5522ea69952cd2af95ae09477f122a96" - integrity sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g== - dependencies: - brace-expansion "^2.0.1" - -minimatch@^9.0.4: - version "9.0.5" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.5.tgz#d74f9dd6b57d83d8e98cfb82133b03978bc929e5" - integrity sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow== +minimatch@^3.0.4, minimatch@^3.1.1, minimatch@^3.1.2, minimatch@^5.0.1, minimatch@^9.0.4, minimatch@^9.0.5: + version "9.0.9" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.9.tgz#9b0cb9fcb78087f6fd7eababe2511c4d3d60574e" + integrity sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg== dependencies: - brace-expansion "^2.0.1" + brace-expansion "^2.0.2" minimist@^1.2.6: version "1.2.6"