import { URLSearchParams } from "url" ; import fetch from "node-fetch" ; import { MixpanelConnectionParams } from "../../types/integrations/mixpanel" ; const encodedParams = new URLSearchParams ( ) ; type MixpanelResultRow = any ; function indentJs ( js ) { let indent = 0 ; return ( js . replace ( /^\s+/gm , "" ) . split ( /\n/g ) . map ( ( line ) => { if ( line . match ( /^[})\]\s]+;?\s*$/ ) ) indent -- ; line = "  " . repeat ( Math . max ( 0 , indent ) ) + line ; if ( line . match ( /[{([]+\s*$/ ) ) indent ++ ; return line ; } ) . join ( "\n" ) . replace ( /\n[ ]*\n[ ]*\n/g , "\n\n" ) . trim ( ) ) ; } export function formatQuery ( js , params ? , extraJs ? ) { return indentJs ( `
    ${ params ? `var params = ${ JSON . stringify ( params , null , 2 ) };` : "" }
    ${ extraJs ? extraJs : "" }
    function main() {
      ${ js }
    }
  ` ) ; } export async function runQuery < T extends MixpanelResultRow > ( conn , query ) { encodedParams . set ( "script" , query ) ; encodedParams . set ( "project_id" , conn . projectId ) ; const url = "https://mixpanel.com/api/2.0/jql" ; const options = { method : "POST" , headers : { Accept : "application/json" , "Content-Type" : "application/x-www-form-urlencoded" , Authorization : `Basic ${ Buffer . from ( `${ conn . username }:${ conn . secret }` ) . toString ( "base64" ) }` , } , body : encodedParams , } ; const res = await fetch ( url , options ) ; const json = await res . json ( ) ; if ( json . error ) { throw new Error ( json . error ) ; } return json ; }