Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid client constructor generated. #1724

Closed
mvrius opened this issue Jan 16, 2023 · 8 comments · Fixed by #1956
Closed

Invalid client constructor generated. #1724

mvrius opened this issue Jan 16, 2023 · 8 comments · Fixed by #1956
Assignees
Labels
customer-reported Issues that are reported by GitHub users external to the Azure organization. Mgmt This issue is related to a management-plane library. question The issue doesn't require a change to the product in order to be resolved. Most issues start as that

Comments

@mvrius
Copy link

mvrius commented Jan 16, 2023

Hi,

I used the sample YAML from here: https://github.com/Azure/autorest/tree/main/Samples/openapi-v3/1a-code-generation-minimal but tried to generate the Typescript version.

input-file: pets.yaml

typescript:
  namespace: Petstore
  output-folder: Client

This generates the following code for constructor:

  constructor(options?: SwaggerPetstoreOptionalParams) {
    // Initializing default values for options
    if (!options) {
      options = {};
    }
    const defaults: SwaggerPetstoreOptionalParams = {
      requestContentType: "application/json; charset=utf-8"
    };

    const packageDetails = `azsdk-js-swaggerPetstore/1.0.0-beta.1`;
    const userAgentPrefix =
      options.userAgentOptions && options.userAgentOptions.userAgentPrefix
        ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
        : `${packageDetails}`;

    const optionsWithDefaults = {
      ...defaults,
      ...options,
      userAgentOptions: {
        userAgentPrefix
      },
      endpoint:
        options.endpoint ?? options.baseUri ?? "http://petstore.swagger.io/v1"
    };
    super(optionsWithDefaults);

    let bearerTokenAuthenticationPolicyFound: boolean = false;
    if (options?.pipeline && options.pipeline.getOrderedPolicies().length > 0) {
      const pipelinePolicies: coreRestPipeline.PipelinePolicy[] = options.pipeline.getOrderedPolicies();
      bearerTokenAuthenticationPolicyFound = pipelinePolicies.some(
        (pipelinePolicy) =>
          pipelinePolicy.name ===
          coreRestPipeline.bearerTokenAuthenticationPolicyName
      );
    }
    if (
      !options ||
      !options.pipeline ||
      options.pipeline.getOrderedPolicies().length == 0 ||
      !bearerTokenAuthenticationPolicyFound
    ) {
      this.pipeline.removePolicy({
        name: coreRestPipeline.bearerTokenAuthenticationPolicyName
      });
      this.pipeline.addPolicy(
        coreRestPipeline.bearerTokenAuthenticationPolicy({
          credential: credentials,
          scopes:
            optionsWithDefaults.credentialScopes ??
            `${optionsWithDefaults.endpoint}/.default`,
          challengeCallbacks: {
            authorizeRequestOnChallenge:
              coreClient.authorizeRequestOnClaimChallenge
          }
        })
      );
    }

    // Assigning values to Constant parameters
    this.$host = options.$host || "http://petstore.swagger.io/v1";
  }

Error is that the credentials variable is not defined. Build error:

pm run build

> swaggerPetstore@1.0.0-beta.1 build
> npm run clean && tsc && rollup -c 2>&1 && npm run minify && mkdirp ./review && npm run extract-api


> swaggerPetstore@1.0.0-beta.1 clean
> rimraf dist dist-browser dist-esm test-dist temp types *.tgz *.log

src/swaggerPetstore.ts:67:23 - error TS2552: Cannot find name 'credentials'. Did you mean 'Credential'?

67           credential: credentials,
                         ~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:3714:13
    3714 declare var Credential: {
                     ~~~~~~~~~~
    'Credential' is declared here.


Found 1 error in src/swaggerPetstore.ts:67

Here's the autorest command output which has versions listed:

autorest input-pets.yaml
AutoRest code generation utility [cli version: 3.6.3; node: v16.13.2]
(C) 2018 Microsoft Corporation.
https://aka.ms/autorest
info    |    Loading AutoRest core      'C:\Users\Storm\.autorest\@autorestcore@3.9.4\nodemodules\@autorest\core\dist' (3.9.4)
info    |    Loading AutoRest extension '@autorest/typescript' (latest->6.0.0-rc.7)
info    |    Loading AutoRest extension '@autorest/modelerfour' (4.25.0->4.25.0)
warning | PreCheck/SchemaMissingType | The schema 'Pet' with an undefined type and declared properties is a bit ambiguous. This has been auto-corrected to 'type:object'
    - file:///C:/dev/repos/photoprism-clients-rest/pets.yaml:84:5
warning | PreCheck/SchemaMissingType | The schema 'Error' with an undefined type and declared properties is a bit ambiguous. This has been auto-corrected to 'type:object'
    - file:///C:/dev/repos/photoprism-clients-rest/pets.yaml:84:5
warning | PreCheck/SchemaMissingType | The schema 'Error' with an undefined type and declared properties is a bit ambiguous. This has been auto-corrected to 'type:object'
    - file:///C:/dev/repos/photoprism-clients-rest/pets.yaml:100:5
warning | PreCheck/CheckDuplicateSchemas | Checking for duplicate schemas, this could take a (long) while.  Run with --verbose for more detail.
info    | Autorest.Typescript took 708ms
info    | Autorest completed in 2.66s. 10 files generated.

Is this expected? Are other flags needed for Typescript client generation?

Thanks,
Marius

@ghost ghost added customer-reported Issues that are reported by GitHub users external to the Azure organization. question The issue doesn't require a change to the product in order to be resolved. Most issues start as that labels Jan 16, 2023
@MaryGao MaryGao self-assigned this Jan 16, 2023
@MaryGao
Copy link
Contributor

MaryGao commented Jan 16, 2023

@mvrius Thanks for the reporting! I think this is a bug for autorest.typescript and I will fix it in future.

To non-block your testing you could disable authentication explicitly with below configs:

typescript:
  namespace: Petstore
  output-folder: Client
  add-credentials: false

@MaryGao
Copy link
Contributor

MaryGao commented Feb 13, 2023

@mvrius This issue won't happen in my side when I use the latest autorest.typescript. Could you have a try?

I will close this issue considering it's resolved. Feel free to reopen it if still existing.

@MaryGao MaryGao closed this as completed Feb 13, 2023
@raphael-verdier
Copy link

raphael-verdier commented May 31, 2023

Hello @MaryGao , while using the latet autorest typescript version I had the same issue.

Here are the logs from my generation:

$ autorest --typescript --input-file=api-v1.json --output-folder=./clients/ts4 --package-name=IndexerApi --
AutoRest code generation utility [cli version: 3.6.3; node: v18.12.1]
(C) 2018 Microsoft Corporation.
https://aka.ms/autorest
info    | AutoRest core version selected from configuration: ^3.7.0.
installing core... [========================================] 100% | 2/2
info    |    Loading AutoRest core      '/home/raphael/.autorest/@autorestcore@3.9.6/nodemodules/@autorest/core/dist' (3.9.6)
info    |    Installing AutoRest extension '@autorest/typescript' (latest -> 6.0.2)
installing... [========================================] 100% | 213/213
info    |    Installed AutoRest extension '@autorest/typescript' (latest->6.0.2)
info    |    Installing AutoRest extension '@autorest/modelerfour' (4.25.0 -> 4.25.0)

info    |    Installed AutoRest extension '@autorest/modelerfour' (4.25.0->4.25.0)
warning | PreCheck/SchemaMissingType | The schema 'SourceContract-topicsItem' with an undefined type and 'allOf'/'anyOf'/'oneOf' is a bit ambiguous. This has been auto-corrected to 'type:object'
    - file:///home/raphael/CODE/engine/battle-blockchain-indexer/api-v1.json:85:13
warning | PreCheck/CheckDuplicateSchemas | Checking for duplicate schemas, this could take a (long) while.  Run with --verbose for more detail.
warning | Deprecated | seal-single-value-enum-by-default is a temporary flag that WILL be removed in the future. Please change the spec to add x-ms-enum.modelAsString=false for enums with this issue.
info    | Autorest.Typescript took 619ms
info    | Autorest completed in 15.35s. 10 files generated.
Done in 19.92s.

The credentials variable is wrongly used in the following generated statement:

        coreRestPipeline.bearerTokenAuthenticationPolicy({
          credential: credentials,
          scopes:
            optionsWithDefaults.credentialScopes ??
            `${optionsWithDefaults.endpoint}/.default`,
          challengeCallbacks: {
            authorizeRequestOnChallenge:
              coreClient.authorizeRequestOnClaimChallenge
          }
        })
    

@aklt
Copy link

aklt commented Aug 3, 2023

We are also running into this issue using the latest autorest which installs the latest autorest.typescript that you mention @MaryGao

Should I be looking for a different tool for generation of a TS client?

@MaryGao MaryGao reopened this Aug 4, 2023
@MaryGao
Copy link
Contributor

MaryGao commented Aug 4, 2023

@aklt @raphael-verdier Sorry for the late reply I re-opened this issue and let me take a look again.

@aklt
Copy link

aklt commented Aug 4, 2023

Great! Please let me know if further info can be helpful

@MaryGao
Copy link
Contributor

MaryGao commented Aug 4, 2023

@aklt I am working on the fix, as a workaround you could directly add --add-credentials=false to escape the issue.

$ autorest --typescript --input-file=api-v1.json --output-folder=./clients/ts4 --package-name=IndexerApi --add-credentials=false

@aklt
Copy link

aklt commented Aug 4, 2023

@MaryGao Thank you for the suggestion, this gets me further and I can start using the TS client it seems.

Before adding to this issue I tried adding:

add-credentials: true

To the readme.md config file, but this client exhibited
the error in this issue. I will try again soon, maybe I missed something.

@lirenhe lirenhe added the Mgmt This issue is related to a management-plane library. label Aug 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
customer-reported Issues that are reported by GitHub users external to the Azure organization. Mgmt This issue is related to a management-plane library. question The issue doesn't require a change to the product in order to be resolved. Most issues start as that
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants