async function validateOpenApiSpecFileUsingSpectral()

in packages/azure-openapi-validator/autorest/src/spectral-plugin-func.ts [109:148]


async function validateOpenApiSpecFileUsingSpectral(
  initiator: IAutoRestPluginInitiator,
  rulesetPayload: SpectralRulesetPayload,
  rulesetForManualSpecs: Ruleset,
  rulesetForTypeSpecGeneratedSpecs: Ruleset,
  openApiSpecFile: string,
) {
  if (openApiSpecFile.includes("common-types/resource-management")) {
    initiator.Message({
      Channel: "information",
      Text: `spectralPluginFunc: Ignoring file matching to 'common-types/resource-management': '${openApiSpecFile}'`,
    })
    return
  }

  try {
    const openApiSpecFilePath = openApiSpecFile.startsWith("file:///") ? fileURLToPath(openApiSpecFile) : openApiSpecFile
    const openApiSpecContent: string = await readFileUsingCache(initiator, openApiSpecFile)
    // load() documented at: https://github.com/nodeca/js-yaml/tree/4.1.0?tab=readme-ov-file#load-string---options-
    // Empirically confirmed the returned value type is object, not string.
    const openApiSpecYml: any = load(openApiSpecContent)
    // "x-typespec-generated" is expected to be found at JSONPath of $.info.x-typespec-generated.
    // Example: https://github.com/Azure/azure-rest-api-specs/blob/fca48bec19cc5aab0a45c0769bfca0f667164dbf/specification/edgemarketplace/resource-manager/Microsoft.EdgeMarketplace/stable/2023-08-01/operations.json#L7
    const specIsGeneratedFromTypeSpec = Boolean(openApiSpecYml.info["x-typespec-generated"]) // JSON.stringify(openApiSpecYml).includes("x-typespec-generated")

    initiator.Message({
      Channel: "information",
      Text: `spectralPluginFunc: Validating OpenAPI spec. TypeSpec-generated: ${specIsGeneratedFromTypeSpec}. Path: '${openApiSpecFile}'`,
    })

    const spectral = newSpectral(initiator, openApiSpecFile)
    spectral.setRuleset(specIsGeneratedFromTypeSpec ? rulesetForTypeSpecGeneratedSpecs : rulesetForManualSpecs)

    const sendMessage = initiator.Message.bind(initiator)

    await runSpectral(sendMessage, spectral, rulesetPayload, openApiSpecFilePath, openApiSpecYml)
  } catch (error: unknown) {
    catchSpectralRunErrors(openApiSpecFile, error, initiator)
  }
}