import { isNonEmptyString } from '@sindresorhus/is'; import { logger } from '../../../logger/index.ts'; import { ExternalHostError } from '../../../types/errors/external-host-error.ts'; import type { Nullish } from '../../../types/index.ts'; import type { GitlabProject } from '../../../types/platform/gitlab/index.ts'; import { GitlabHttp } from '../../../util/http/gitlab.ts'; import type { HttpResponse } from '../../../util/http/types.ts'; import type { Preset, PresetConfig } from '../types.ts'; import { PRESET_DEP_NOT_FOUND, fetchPreset, parsePreset } from '../util.ts'; const gitlabApi = new GitlabHttp(); export const Endpoint = 'https://gitlab.com/api/v4/'; async function getDefaultBranchName( urlEncodedPkgName: string, endpoint: string, ): Promise { const res = await gitlabApi.getJsonUnchecked( `${endpoint}projects/${urlEncodedPkgName}`, ); return res.body.default_branch ?? 'master'; // should never happen, but we keep this to ensure the current behavior } export async function fetchJSONFile( repo: string, fileName: string, endpoint: string, tag?: string, ): Promise> { let url = endpoint; let ref = ''; let res: HttpResponse; try { const urlEncodedRepo = encodeURIComponent(repo); const urlEncodedPkgName = encodeURIComponent(fileName); if (isNonEmptyString(tag)) { ref = `?ref=${tag}`; } else { const defaultBranchName = await getDefaultBranchName( urlEncodedRepo, endpoint, ); ref = `?ref=${defaultBranchName}`; } url += `projects/${urlEncodedRepo}/repository/files/${urlEncodedPkgName}/raw${ref}`; logger.trace({ url }, `Preset URL`); res = await gitlabApi.getText(url); } catch (err) { if (err instanceof ExternalHostError) { throw err; } logger.debug( `Preset file ${fileName} not found in ${repo}: ${err.message}`, ); throw new Error(PRESET_DEP_NOT_FOUND); } return parsePreset(res.body, fileName); } export function getPresetFromEndpoint( repo: string, presetName: string, presetPath?: string, endpoint = Endpoint, tag?: string, ): Promise> { return fetchPreset({ repo, filePreset: presetName, presetPath, endpoint, tag, fetch: fetchJSONFile, }); } export function getPreset({ repo, presetPath, presetName = 'default', tag, }: PresetConfig): Promise> { return getPresetFromEndpoint(repo, presetName, presetPath, Endpoint, tag); }