import { raiseError } from 'analytics' ; import { errors } from 'platforms' ; function isEmptyProject ( content ) { return content ?. [ 'message' ] === 'Git Repository is empty.' ; } function isBlockedProject ( content ) { return content ?. [ 'message' ] === 'Repository access blocked' ; } async function request ( url , { accessToken , } = { } ) { const headers = { } as HeadersInit & { Authorization ? : string ; } ; if ( accessToken ) { headers . Authorization = `token ${ accessToken }` ; } try { const res = await fetch ( url , { headers } ) ; const contentType = res . headers . get ( 'Content-Type' ) || res . headers . get ( 'content-type' ) ; if ( ! contentType ) { throw new Error ( `Response has no content type` ) ; } else if ( ! contentType . includes ( 'application/json' ) ) { throw new Error ( `Response content type is ${ contentType }` ) ; } if ( res . ok ) { return res . json ( ) ; } else { if ( res . status === 404 || res . status === 401 ) throw new Error ( errors . NOT_FOUND ) ; else if ( res . status === 500 ) throw new Error ( errors . SERVER_FAULT ) ; else { const content = await res . json ( ) ; if ( isEmptyProject ( content ) ) throw new Error ( errors . EMPTY_PROJECT ) ; if ( isBlockedProject ( content ) ) throw new Error ( errors . BLOCKED_PROJECT ) ; raiseError ( new Error ( res . statusText ) ) ; throw new Error ( content && content . message ) ; } } } catch ( err ) { throw new Error ( errors . CONNECTION_BLOCKED ) ; } } export async function getRepoMeta ( userName , repoName , accessToken ? ) { const url = `https://gitee.com/api/v5/repos/${ encodeURIComponent ( userName ) }/${ encodeURIComponent ( repoName ) }` ; return await request ( url , { accessToken } ) ; } export async function getTreeData ( userName , repoName , branchName , accessToken ? ) { const url = `https://gitee.com/api/v5/repos/${ encodeURIComponent ( userName ) }/${ encodeURIComponent ( repoName ) }/git/trees/${ encodeURIComponent ( branchName ) }?recursive=1` ; return await request ( url , { accessToken } ) ; } export async function getBlobData ( userName , repoName , sha , accessToken ? ) { const url = `https://gitee.com/api/v5/repos/${ encodeURIComponent ( userName ) }/${ encodeURIComponent ( repoName ) }/git/blobs/${ encodeURIComponent ( sha ) }` ; return await request ( url , { accessToken } ) ; } export async function OAuth ( code ) { const endpoint = 'https://gitako.now.sh/oauth/gitee?' ; const res = await fetch ( endpoint + new URLSearchParams ( { code } ) . toString ( ) , { method : 'post' , } ) ; if ( res . ok ) { const body = await res . json ( ) ; const accessToken = body ?. accessToken ; if ( typeof accessToken === 'string' ) return accessToken ; } return null ; }