LCOV - code coverage report
Current view: top level - src/services - comfyRegistryService.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 72.1 % 86 62
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { AxiosError, AxiosResponse } from 'axios'
       2              : import axios from 'axios'
       3              : import { ref } from 'vue'
       4              : 
       5              : import type { components, operations } from '@/types/comfyRegistryTypes'
       6              : import { isAbortError } from '@/utils/typeGuardUtil'
       7              : 
       8              : const API_BASE_URL = 'https://api.comfy.org'
       9              : 
      10         2356 : const registryApiClient = axios.create({
      11              :   baseURL: API_BASE_URL,
      12              :   headers: {
      13              :     'Content-Type': 'application/json'
      14              :   },
      15              :   paramsSerializer: {
      16              :     // Disables PHP-style notation (e.g. param[]=value) in favor of repeated params (e.g. param=value1&param=value2)
      17              :     indexes: null
      18              :   }
      19              : })
      20              : 
      21              : /**
      22              :  * Service for interacting with the Comfy Registry API
      23              :  */
      24         2356 : export const useComfyRegistryService = () => {
      25         2371 :   const isLoading = ref(false)
      26         2371 :   const error = ref<string | null>(null)
      27              : 
      28         2371 :   const handleApiError = (
      29              :     err: unknown,
      30              :     context: string,
      31              :     routeSpecificErrors?: Record<number, string>
      32              :   ): string => {
      33          143 :     if (!axios.isAxiosError(err))
      34            0 :       return err instanceof Error
      35              :         ? `${context}: ${err.message}`
      36              :         : `${context}: Unknown error occurred`
      37              : 
      38          143 :     const axiosError = err as AxiosError<components['schemas']['ErrorResponse']>
      39              : 
      40          143 :     if (axiosError.response) {
      41          140 :       const { status, data } = axiosError.response
      42              : 
      43          140 :       if (routeSpecificErrors && routeSpecificErrors[status])
      44           62 :         return routeSpecificErrors[status]
      45              : 
      46          140 :       switch (status) {
      47              :         case 400:
      48            0 :           return `Bad request: ${data.message || 'Invalid input'}`
      49              :         case 401:
      50            0 :           return 'Unauthorized: Authentication required'
      51              :         case 403:
      52            0 :           return `Forbidden: ${data.message || 'Access denied'}`
      53              :         case 404:
      54           77 :           return `Not found: ${data.message || 'Resource not found'}`
      55              :         case 409:
      56            0 :           return `Conflict: ${data.message || 'Resource conflict'}`
      57              :         case 500:
      58            0 :           return `Server error: ${data.message || 'Internal server error'}`
      59              :         default:
      60            1 :           return `${context}: ${data.message || axiosError.message}`
      61              :       }
      62              :     }
      63              : 
      64            3 :     return `${context}: ${axiosError.message}`
      65              :   }
      66              : 
      67              :   /**
      68              :    * Execute an API request with error and loading state handling
      69              :    * @param apiCall - Function that returns a promise with the API call
      70              :    * @param errorContext - Context description for error messages
      71              :    * @param routeSpecificErrors - Optional map of status codes to custom error messages
      72              :    * @returns Promise with the API response data or null if the request failed
      73              :    */
      74         2371 :   const executeApiRequest = async <T>(
      75              :     apiCall: () => Promise<AxiosResponse<T>>,
      76              :     errorContext: string,
      77              :     routeSpecificErrors?: Record<number, string>
      78              :   ): Promise<T | null> => {
      79          210 :     isLoading.value = true
      80          210 :     error.value = null
      81              : 
      82          210 :     try {
      83              :       const response = await apiCall()
      84          210 :       return response.data
      85              :     } catch (err) {
      86              :       // Don't treat cancellations as errors
      87          143 :       if (isAbortError(err)) return null
      88              : 
      89          143 :       error.value = handleApiError(err, errorContext, routeSpecificErrors)
      90          143 :       return null
      91              :     } finally {
      92          210 :       isLoading.value = false
      93              :     }
      94              :   }
      95              : 
      96              :   /**
      97              :    * Get the Comfy Node definitions in a specific version of a node pack
      98              :    * @param packId - The ID of the node pack
      99              :    * @param versionId - The version of the node pack
     100              :    * @returns The node definitions or null if not found or an error occurred
     101              :    */
     102         2371 :   const getNodeDefs = async (
     103              :     params: {
     104              :       packId: components['schemas']['Node']['id']
     105              :       version: components['schemas']['NodeVersion']['version']
     106              :     } & operations['ListComfyNodes']['parameters']['query'],
     107              :     signal?: AbortSignal
     108              :   ) => {
     109            3 :     const { packId, version: versionId, ...queryParams } = params
     110            3 :     if (!packId || !versionId) return null
     111              : 
     112            3 :     const endpoint = `/nodes/${packId}/versions/${versionId}/comfy-nodes`
     113              :     const errorContext = 'Failed to get node definitions'
     114              :     const routeSpecificErrors = {
     115              :       403: 'This pack has been banned and its definition is not available',
     116              :       404: 'The requested node, version, or comfy node does not exist'
     117              :     }
     118              : 
     119            3 :     return executeApiRequest(
     120              :       () =>
     121              :         registryApiClient.get<
     122              :           operations['ListComfyNodes']['responses'][200]['content']['application/json']
     123              :         >(endpoint, {
     124              :           params: queryParams,
     125              :           signal
     126              :         }),
     127              :       errorContext,
     128              :       routeSpecificErrors
     129              :     )
     130              :   }
     131              : 
     132              :   /**
     133              :    * Get a paginated list of packs matching specific criteria.
     134              :    * Search packs using `search` param. Search individual nodes using `comfy_node_search` param.
     135              :    */
     136         2371 :   const search = async (
     137              :     params?: operations['searchNodes']['parameters']['query'],
     138              :     signal?: AbortSignal
     139              :   ) => {
     140            2 :     const endpoint = '/nodes/search'
     141              :     const errorContext = 'Failed to perform search'
     142              : 
     143            2 :     return executeApiRequest(
     144              :       () =>
     145              :         registryApiClient.get<
     146              :           operations['searchNodes']['responses'][200]['content']['application/json']
     147              :         >(endpoint, { params, signal }),
     148              :       errorContext
     149              :     )
     150              :   }
     151              : 
     152              :   /**
     153              :    * Get publisher information
     154              :    */
     155         2371 :   const getPublisherById = async (
     156              :     publisherId: components['schemas']['Publisher']['id'],
     157              :     signal?: AbortSignal
     158              :   ) => {
     159            0 :     const endpoint = `/publishers/${publisherId}`
     160            0 :     const errorContext = 'Failed to get publisher'
     161            0 :     const routeSpecificErrors = {
     162              :       404: `Publisher not found: The publisher with ID ${publisherId} does not exist`
     163              :     }
     164              : 
     165            0 :     return executeApiRequest(
     166              :       () =>
     167              :         registryApiClient.get<components['schemas']['Publisher']>(endpoint, {
     168              :           signal
     169              :         }),
     170              :       errorContext,
     171              :       routeSpecificErrors
     172              :     )
     173              :   }
     174              : 
     175              :   /**
     176              :    * List all packs associated with a specific publisher
     177              :    */
     178         2371 :   const listPacksForPublisher = async (
     179              :     publisherId: components['schemas']['Publisher']['id'],
     180              :     includeBanned?: boolean,
     181              :     signal?: AbortSignal
     182              :   ) => {
     183            0 :     const params = includeBanned ? { include_banned: true } : undefined
     184            0 :     const endpoint = `/publishers/${publisherId}/nodes`
     185            0 :     const errorContext = 'Failed to list packs for publisher'
     186            0 :     const routeSpecificErrors = {
     187              :       400: 'Bad request: Invalid input data',
     188              :       404: `Publisher not found: The publisher with ID ${publisherId} does not exist`
     189              :     }
     190              : 
     191            0 :     return executeApiRequest(
     192              :       () =>
     193              :         registryApiClient.get<components['schemas']['Node'][]>(endpoint, {
     194              :           params,
     195              :           signal
     196              :         }),
     197              :       errorContext,
     198              :       routeSpecificErrors
     199              :     )
     200              :   }
     201              : 
     202              :   /**
     203              :    * Add a review for a pack
     204              :    */
     205         2371 :   const postPackReview = async (
     206              :     packId: components['schemas']['Node']['id'],
     207              :     star: number,
     208              :     signal?: AbortSignal
     209              :   ) => {
     210            0 :     const endpoint = `/nodes/${packId}/reviews`
     211            0 :     const params = { star }
     212            0 :     const errorContext = 'Failed to add review'
     213            0 :     const routeSpecificErrors = {
     214              :       400: 'Bad request: Invalid review',
     215              :       404: `Pack not found: Pack with ID ${packId} does not exist`
     216              :     }
     217              : 
     218            0 :     return executeApiRequest(
     219              :       () =>
     220              :         registryApiClient.post<components['schemas']['Node']>(endpoint, null, {
     221              :           params,
     222              :           signal
     223              :         }),
     224              :       errorContext,
     225              :       routeSpecificErrors
     226              :     )
     227              :   }
     228              : 
     229              :   /**
     230              :    * Get a paginated list of all packs on the registry
     231              :    */
     232         2371 :   const listAllPacks = async (
     233              :     params?: operations['listAllNodes']['parameters']['query'],
     234              :     signal?: AbortSignal
     235              :   ) => {
     236          124 :     const endpoint = '/nodes'
     237              :     const errorContext = 'Failed to list packs'
     238              : 
     239          124 :     return executeApiRequest(
     240              :       () =>
     241              :         registryApiClient.get<
     242              :           operations['listAllNodes']['responses'][200]['content']['application/json']
     243              :         >(endpoint, { params, signal }),
     244              :       errorContext
     245              :     )
     246              :   }
     247              : 
     248              :   /**
     249              :    * Get a list of all pack versions
     250              :    */
     251         2371 :   const getPackVersions = async (
     252              :     packId: components['schemas']['Node']['id'],
     253              :     params?: operations['listNodeVersions']['parameters']['query'],
     254              :     signal?: AbortSignal
     255              :   ) => {
     256            1 :     const endpoint = `/nodes/${packId}/versions`
     257            1 :     const errorContext = 'Failed to get pack versions'
     258            1 :     const routeSpecificErrors = {
     259              :       403: 'This pack has been banned and its versions are not available',
     260              :       404: `Pack not found: Pack with ID ${packId} does not exist`
     261              :     }
     262              : 
     263            1 :     return executeApiRequest(
     264              :       () =>
     265              :         registryApiClient.get<components['schemas']['NodeVersion'][]>(
     266              :           endpoint,
     267              :           { params, signal }
     268              :         ),
     269              :       errorContext,
     270              :       routeSpecificErrors
     271              :     )
     272              :   }
     273              : 
     274              :   /**
     275              :    * Get a specific pack by ID and version
     276              :    */
     277         2371 :   const getPackByVersion = async (
     278              :     packId: components['schemas']['Node']['id'],
     279              :     versionId: components['schemas']['NodeVersion']['id'],
     280              :     signal?: AbortSignal
     281              :   ) => {
     282            0 :     const endpoint = `/nodes/${packId}/versions/${versionId}`
     283            0 :     const errorContext = 'Failed to get pack version'
     284            0 :     const routeSpecificErrors = {
     285              :       403: 'This pack has been banned and its versions are not available',
     286              :       404: `Pack not found: Pack with ID ${packId} does not exist`
     287              :     }
     288              : 
     289            0 :     return executeApiRequest(
     290              :       () =>
     291              :         registryApiClient.get<components['schemas']['NodeVersion']>(endpoint, {
     292              :           signal
     293              :         }),
     294              :       errorContext,
     295              :       routeSpecificErrors
     296              :     )
     297              :   }
     298              : 
     299              :   /**
     300              :    * Get a specific pack by ID
     301              :    */
     302         2371 :   const getPackById = async (
     303              :     packId: operations['getNode']['parameters']['path']['nodeId'],
     304              :     signal?: AbortSignal
     305              :   ) => {
     306            3 :     const endpoint = `/nodes/${packId}`
     307            3 :     const errorContext = 'Failed to get pack'
     308            3 :     const routeSpecificErrors = {
     309              :       404: `Pack not found: The pack with ID ${packId} does not exist`
     310              :     }
     311              : 
     312            3 :     return executeApiRequest(
     313              :       () =>
     314              :         registryApiClient.get<components['schemas']['Node']>(endpoint, {
     315              :           signal
     316              :         }),
     317              :       errorContext,
     318              :       routeSpecificErrors
     319              :     )
     320              :   }
     321              : 
     322              :   /**
     323              :    * Get the node pack that contains a specific ComfyUI node by its name.
     324              :    * This method queries the registry to find which pack provides the given node.
     325              :    *
     326              :    * When multiple packs contain a node with the same name, the API returns the best match based on:
     327              :    * 1. Preemption match - If the node name matches any in the pack's preempted_comfy_node_names array
     328              :    * 2. Search ranking - Lower search_ranking values are preferred
     329              :    * 3. Total installs - Higher installation counts are preferred as a tiebreaker
     330              :    *
     331              :    * @param nodeName - The name of the ComfyUI node (e.g., 'KSampler', 'CLIPTextEncode')
     332              :    * @param signal - Optional AbortSignal for request cancellation
     333              :    * @returns The node pack containing the specified node, or null if not found or on error
     334              :    *
     335              :    * @example
     336              :    * ```typescript
     337              :    * const pack = await inferPackFromNodeName('KSampler')
     338              :    * if (pack) {
     339              :    *   console.log(`Node found in pack: ${pack.name}`)
     340              :    * }
     341              :    * ```
     342              :    */
     343         2371 :   const inferPackFromNodeName = async (
     344              :     nodeName:
     345              :       | operations['getNodeByComfyNodeName']['parameters']['path']['comfyNodeName']
     346              :       | null
     347              :       | undefined,
     348              :     signal?: AbortSignal
     349              :   ) => {
     350           62 :     if (!nodeName || nodeName === 'undefined') return null
     351              : 
     352           62 :     const endpoint = `/comfy-nodes/${nodeName}/node`
     353           62 :     const errorContext = 'Failed to infer pack from comfy node name'
     354           62 :     const routeSpecificErrors = {
     355              :       404: `Comfy node not found: The node with name ${nodeName} does not exist in the registry`
     356              :     }
     357              : 
     358           62 :     return executeApiRequest(
     359              :       () =>
     360              :         registryApiClient.get<components['schemas']['Node']>(endpoint, {
     361              :           signal
     362              :         }),
     363              :       errorContext,
     364              :       routeSpecificErrors
     365              :     )
     366              :   }
     367              : 
     368              :   /**
     369              :    * Get multiple pack versions in a single bulk request.
     370              :    * This is more efficient than making individual requests for each pack version.
     371              :    *
     372              :    * @param nodeVersions - Array of node ID and version pairs to retrieve
     373              :    * @param signal - Optional AbortSignal for request cancellation
     374              :    * @returns Bulk response containing the requested node versions or null on error
     375              :    *
     376              :    * @example
     377              :    * ```typescript
     378              :    * const versions = await getBulkNodeVersions([
     379              :    *   { node_id: 'ComfyUI-Manager', version: '1.0.0' },
     380              :    *   { node_id: 'ComfyUI-Impact-Pack', version: '2.0.0' }
     381              :    * ])
     382              :    * if (versions) {
     383              :    *   versions.node_versions.forEach(result => {
     384              :    *     if (result.status === 'success' && result.node_version) {
     385              :    *       console.log(`Retrieved ${result.identifier.node_id}@${result.identifier.version}`)
     386              :    *     }
     387              :    *   })
     388              :    * }
     389              :    * ```
     390              :    */
     391         2371 :   const getBulkNodeVersions = async (
     392              :     nodeVersions: components['schemas']['NodeVersionIdentifier'][],
     393              :     signal?: AbortSignal
     394              :   ) => {
     395           15 :     const endpoint = '/bulk/nodes/versions'
     396           15 :     const errorContext = 'Failed to get bulk node versions'
     397           15 :     const routeSpecificErrors = {
     398              :       400: 'Bad request: Invalid node version identifiers provided'
     399              :     }
     400              : 
     401           15 :     const requestBody: components['schemas']['BulkNodeVersionsRequest'] = {
     402              :       node_versions: nodeVersions
     403              :     }
     404              : 
     405           15 :     return executeApiRequest(
     406              :       () =>
     407              :         registryApiClient.post<
     408              :           components['schemas']['BulkNodeVersionsResponse']
     409              :         >(endpoint, requestBody, {
     410              :           signal
     411              :         }),
     412              :       errorContext,
     413              :       routeSpecificErrors
     414              :     )
     415              :   }
     416              : 
     417         2371 :   return {
     418              :     isLoading,
     419              :     error,
     420              : 
     421              :     listAllPacks,
     422              :     search,
     423              :     getPackById,
     424              :     getPackVersions,
     425              :     getPackByVersion,
     426              :     getPublisherById,
     427              :     listPacksForPublisher,
     428              :     getNodeDefs,
     429              :     postPackReview,
     430              :     inferPackFromNodeName,
     431              :     getBulkNodeVersions
     432              :   }
     433              : }
        

Generated by: LCOV version 2.0-1