import * as oauth from 'oauth4webapi'

// Prerequisites

let issuer!: URL // Authorization server's Issuer Identifier URL
let algorithm!:
  | 'oauth2' /* For .well-known/oauth-authorization-server discovery */
  | 'oidc' /* For .well-known/openid-configuration discovery */
  | undefined /* Defaults to 'oidc' */
let client_id!: string
let client_secret!: string

// End of prerequisites

const as = await oauth
  .discoveryRequest(issuer, { algorithm })
  .then((response) => oauth.processDiscoveryResponse(issuer, response))

const client: oauth.Client = { client_id }
const clientAuth = oauth.ClientSecretPost(client_secret)

// Client Credentials Grant Request & Response
let access_token: string
{
  const parameters = new URLSearchParams()
  parameters.set('scope', 'api:read')

  const response = await oauth.clientCredentialsGrantRequest(as, client, clientAuth, parameters)

  const result = await oauth.processClientCredentialsResponse(as, client, response)

  console.log('Access Token Response', result)
  ;({ access_token } = result)
}

// Protected Resource Request
{
  const response = await oauth.protectedResourceRequest(
    access_token,
    'GET',
    new URL('https://rs.example.com/api'),
  )

  console.log('Protected Resource Response', await response.json())
}
