All files / src app-configuration.ts

97.05% Statements 99/102
88.88% Branches 88/99
100% Functions 19/19
96.96% Lines 96/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305                      2x 2x 2x 2x 2x 2x 2x                                                                                                           17x             17x 17x   17x 17x 17x 17x                         4x 4x 4x 4x 4x 1x     3x                 19x 24x 24x 15x     9x 9x 1x   8x 8x 6x                 9x 9x 8x               3x 3x 3x             3x 3x             1x 1x 1x           3x 3x   3x 3x 4x 4x 4x 4x 3x   4x 2x     4x 4x 4x   4x     4x 4x           13x 13x 13x 13x 2x     13x       16x       16x         4x       4x 2x     2x       14x 14x       14x 14x 14x                                     17x   17x 17x 17x 17x 3x     17x 17x 4x     17x             17x 17x 1x           16x         3x       15x 15x 29x 1x       14x    
import { AzureClient } from './client'
import type { AzureClientCredential, AzureRequestInit, AzureRequestOverrides } from './client'
import { AppConfigurationKeyCredential } from './internal/app-configuration-credential'
import { jsonProperty, readBoolean, readString, readStringRecord } from './internal/json'
import { pagedItems, paginate } from './internal/paging'
import type { PagedAsyncIterableIterator, PageSettings } from './internal/paging'
import { appConfigurationOAuthScope } from './internal/request-core'
import { jsonRequestError } from './internal/request-error'
import { parseConnectionString, stripSurrounding } from './internal/text'
import { encodeResourceSegment, normalizeServiceUrl } from './internal/url'
 
const defaultApiVersion = '2023-11-01'
const settingContentType = 'application/vnd.microsoft.appconfig.kv+json'
const settingAccept = 'application/vnd.microsoft.appconfig.kv+json, application/problem+json'
const listAccept = 'application/vnd.microsoft.appconfig.kvset+json, application/problem+json'
const syncTokenPattern = /^([^=]+)=([^;]+);sn=(\d+)$/u
const syncTokenHeaderValue = /^[\u0020-\u007E\u0080-\u00FF]+$/u
const reservedFilterCharacter = /([\\*,])/gu
 
export interface AppConfigurationClientOptions extends Omit<AzureRequestOverrides, 'credential'> {
  fetch?: typeof globalThis.fetch
  apiVersion?: string
  /** Prepended to keys as `prefix:key` and removed from returned keys. */
  prefix?: string
  /** Default label; `null` selects settings without a label. */
  label?: string | null
}
 
export type AppConfigurationRequestOptions = Omit<AzureRequestInit, 'method' | 'body'>
 
export interface ConfigurationSetting {
  key: string
  label?: string
  contentType?: string
  value?: string
  lastModified?: Date
  tags?: Record<string, string>
  isReadOnly: boolean
  etag?: string
}
 
export interface ConfigurationSettingPage {
  value: ConfigurationSetting[]
  continuationToken?: string
}
 
export interface GetConfigurationSettingOptions extends AppConfigurationRequestOptions {
  label?: string | null
}
 
export type DeleteConfigurationSettingOptions = GetConfigurationSettingOptions
 
export interface SetConfigurationSettingOptions extends AppConfigurationRequestOptions {
  label?: string | null
  contentType?: string
  tags?: Record<string, string>
}
 
export interface ListConfigurationSettingsOptions extends AppConfigurationRequestOptions {
  /** Full store key filter. When provided, it replaces the default filter derived from `prefix`. */
  keyFilter?: string
  /** `null` selects settings without a label. */
  labelFilter?: string | null
}
 
export class AppConfigurationClient {
  public readonly url: string
  private readonly client: AzureClient
  private readonly apiVersion: string
  private readonly prefix: string | undefined
  private readonly defaultLabel: string | null | undefined
  private readonly syncTokens = new Map<string, { token: string; sequenceNumber: bigint }>()
 
  public constructor(
    endpoint: string,
    credential?: AzureClientCredential,
    options: AppConfigurationClientOptions = {},
  ) {
    this.url = normalizeServiceUrl(endpoint, 'endpoint')
    this.apiVersion = options.apiVersion ?? defaultApiVersion
    const prefix =
      options.prefix === undefined ? undefined : stripSurrounding(options.prefix.trim(), ':')
    this.prefix = prefix === '' ? undefined : prefix
    this.defaultLabel = options.label
    this.client = new AzureClient({
      credential,
      fetch: options.fetch,
      retryOptions: options.retryOptions,
      scope: options.scope ?? appConfigurationScope(this.url),
      authorityHost: options.authorityHost,
    })
  }
 
  public static fromConnectionString(
    connectionString: string,
    options: Omit<AppConfigurationClientOptions, 'scope' | 'authorityHost'> = {},
  ): AppConfigurationClient {
    const parts = parseConnectionString(connectionString)
    const endpoint = parts.get('Endpoint') ?? ''
    const id = parts.get('Id')
    const secret = parts.get('Secret')
    if (endpoint === '' || id === undefined || secret === undefined) {
      throw new Error('Invalid connection string. Expected Endpoint=…;Id=…;Secret=…')
    }
 
    return new AppConfigurationClient(
      endpoint,
      new AppConfigurationKeyCredential(id, secret),
      options,
    )
  }
 
  /** Adds sync tokens, for example from Event Grid notifications; malformed tokens are ignored. */
  public updateSyncToken(syncToken: string): void {
    for (const token of syncToken.split(',')) {
      const [, id, value, sequence] = syncTokenPattern.exec(token.trim()) ?? []
      if (id === undefined || value === undefined || sequence === undefined) {
        continue
      }
 
      const headerValue = `${id}=${value}`
      if (!syncTokenHeaderValue.test(headerValue)) {
        continue
      }
      const sequenceNumber = BigInt(sequence)
      if ((this.syncTokens.get(id)?.sequenceNumber ?? -1n) < sequenceNumber) {
        this.syncTokens.set(id, { token: headerValue, sequenceNumber })
      }
    }
  }
 
  public async getConfigurationSetting(
    key: string,
    options: GetConfigurationSettingOptions = {},
  ): Promise<ConfigurationSetting> {
    const { label, ...init } = options
    const response = await this.send('GET', this.settingUrl(key, label), init, settingAccept)
    return this.parseSetting(await response.json())
  }
 
  public async setConfigurationSetting(
    key: string,
    value: string,
    options: SetConfigurationSettingOptions = {},
  ): Promise<ConfigurationSetting> {
    const { label, contentType, tags, ...init } = options
    const url = this.settingUrl(key, label)
    const body = JSON.stringify({
      key: this.resolveKey(key),
      label: url.searchParams.get('label') ?? undefined,
      value,
      content_type: contentType,
      tags,
    })
    const response = await this.send('PUT', url, init, settingAccept, body)
    return this.parseSetting(await response.json())
  }
 
  public async deleteConfigurationSetting(
    key: string,
    options: DeleteConfigurationSettingOptions = {},
  ): Promise<ConfigurationSetting | undefined> {
    const { label, ...init } = options
    const response = await this.send('DELETE', this.settingUrl(key, label), init, settingAccept)
    return response.status === 204 ? undefined : this.parseSetting(await response.json())
  }
 
  public listConfigurationSettings(
    options: ListConfigurationSettingsOptions = {},
  ): PagedAsyncIterableIterator<ConfigurationSetting, ConfigurationSettingPage> {
    const { keyFilter, labelFilter, ...init } = options
    const defaultKeyFilter = this.prefix === undefined ? '*' : `${escapeFilter(this.prefix)}:*`
 
    return pagedItems((settings: PageSettings = {}) =>
      paginate(async (after) => {
        const url = new URL('kv', `${this.url}/`)
        url.searchParams.set('key', keyFilter ?? defaultKeyFilter)
        const label = this.resolveLabelFilter(labelFilter)
        if (label !== undefined) {
          url.searchParams.set('label', label)
        }
        if (after !== undefined) {
          url.searchParams.set('after', after)
        }
 
        const payload: unknown = await (await this.send('GET', url, init, listAccept)).json()
        const items = jsonProperty(payload, 'items')
        const nextLink = readString(payload, '@nextLink')
        const continuationToken =
          nextLink === undefined
            ? undefined
            : (new URL(nextLink, this.url).searchParams.get('after') ?? undefined)
        const value = Array.isArray(items) ? items.map((item) => this.parseSetting(item)) : []
        return { page: { value, continuationToken }, continuationToken }
      }, settings.continuationToken),
    )
  }
 
  private settingUrl(key: string, label: string | null | undefined): URL {
    const path = encodeResourceSegment(this.resolveKey(key), 'Configuration setting key')
    const url = new URL(`kv/${path}`, `${this.url}/`)
    const resolvedLabel = label === undefined ? this.defaultLabel : label
    if (typeof resolvedLabel === 'string') {
      url.searchParams.set('label', resolvedLabel)
    }
 
    return url
  }
 
  private resolveKey(key: string): string {
    Iif (key.trim().length === 0) {
      throw new TypeError('Configuration setting key must be a non-empty string')
    }
 
    return this.prefix === undefined ? key : `${this.prefix}:${key}`
  }
 
  /** `\0` selects settings without a label; generated filters escape reserved characters. */
  private resolveLabelFilter(labelFilter: string | null | undefined): string | undefined {
    Iif (labelFilter !== undefined) {
      return labelFilter ?? '\0'
    }
 
    if (this.defaultLabel === null) {
      return '\0'
    }
 
    return this.defaultLabel === undefined ? undefined : escapeFilter(this.defaultLabel)
  }
 
  private parseSetting(item: unknown): ConfigurationSetting {
    const key = readString(item, 'key')
    Iif (key === undefined) {
      throw new TypeError('App Configuration response did not include a key')
    }
 
    const lastModified = readString(item, 'last_modified')
    const prefix = this.prefix === undefined ? undefined : `${this.prefix}:`
    return {
      key: prefix !== undefined && key.startsWith(prefix) ? key.slice(prefix.length) : key,
      label: readString(item, 'label'),
      contentType: readString(item, 'content_type'),
      value: readString(item, 'value'),
      lastModified: lastModified === undefined ? undefined : new Date(lastModified),
      tags: readStringRecord(item, 'tags'),
      isReadOnly: readBoolean(item, 'locked') ?? false,
      etag: readString(item, 'etag'),
    }
  }
 
  private async send(
    method: string,
    url: URL,
    options: AppConfigurationRequestOptions,
    accept: string,
    body?: string,
  ): Promise<Response> {
    url.searchParams.set('api-version', this.apiVersion)
    // Sorted query parameters keep request URLs cache friendly, as the official SDK does.
    url.searchParams.sort()
    const headers = new Headers(options.headers)
    headers.set('Accept', accept)
    if (body !== undefined) {
      headers.set('Content-Type', settingContentType)
    }
 
    const syncToken = Array.from(this.syncTokens.values(), ({ token }) => token).join(',')
    if (syncToken !== '' && !headers.has('Sync-Token')) {
      headers.set('Sync-Token', syncToken)
    }
 
    const response = await this.client.fetch(url, {
      ...options,
      redirect: options.redirect ?? 'manual',
      method,
      headers,
      body,
    })
    this.updateSyncToken(response.headers.get('sync-token') ?? '')
    if (!response.ok) {
      throw await jsonRequestError(`${method} ${url.toString()}`, response, (problem) => ({
        code: jsonProperty(problem, 'name'),
        message: jsonProperty(problem, 'detail') ?? jsonProperty(problem, 'title'),
      }))
    }
 
    return response
  }
}
 
function escapeFilter(value: string): string {
  return value.replaceAll(reservedFilterCharacter, String.raw`\$1`)
}
 
function appConfigurationScope(endpoint: string): string {
  const { host } = new URL(endpoint)
  for (const cloud of ['azure.us', 'azure.cn']) {
    if (host.endsWith(`azconfig.${cloud}`) || host.endsWith(`appconfig.${cloud}`)) {
      return `https://appconfig.${cloud}/.default`
    }
  }
 
  return appConfigurationOAuthScope
}