@typespec/http-client-js 0.4.0-dev.0 → 0.4.0-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/src/components/client-context/client-context-factory.d.ts.map +1 -1
  2. package/dist/src/components/client-context/client-context-factory.js +104 -37
  3. package/dist/src/components/client-context/client-context-factory.js.map +1 -1
  4. package/dist/src/components/client-operation.js +5 -7
  5. package/dist/src/components/client-operation.js.map +1 -1
  6. package/dist/src/components/client.d.ts.map +1 -1
  7. package/dist/src/components/client.js +5 -3
  8. package/dist/src/components/client.js.map +1 -1
  9. package/dist/src/components/external-packages/ts-http-runtime.d.ts +8 -3
  10. package/dist/src/components/external-packages/ts-http-runtime.d.ts.map +1 -1
  11. package/dist/src/components/external-packages/ts-http-runtime.js +2 -2
  12. package/dist/src/components/external-packages/ts-http-runtime.js.map +1 -1
  13. package/dist/src/components/http-request-options.d.ts +1 -1
  14. package/dist/src/components/http-request-options.d.ts.map +1 -1
  15. package/dist/src/components/http-request-options.js +2 -1
  16. package/dist/src/components/http-request-options.js.map +1 -1
  17. package/dist/src/components/http-request-parameters-expression.d.ts +2 -1
  18. package/dist/src/components/http-request-parameters-expression.d.ts.map +1 -1
  19. package/dist/src/components/http-request-parameters-expression.js +125 -18
  20. package/dist/src/components/http-request-parameters-expression.js.map +1 -1
  21. package/dist/src/components/http-request.js +1 -0
  22. package/dist/src/components/http-request.js.map +1 -1
  23. package/dist/src/components/operation-parameters.d.ts +1 -1
  24. package/dist/src/components/operation-parameters.d.ts.map +1 -1
  25. package/dist/src/components/operation-parameters.js +7 -5
  26. package/dist/src/components/operation-parameters.js.map +1 -1
  27. package/dist/src/components/static-helpers/bytes-encoding.js +14 -16
  28. package/dist/src/components/static-helpers/bytes-encoding.js.map +1 -1
  29. package/dist/src/components/static-helpers/multipart-helpers.js +12 -10
  30. package/dist/src/components/static-helpers/multipart-helpers.js.map +1 -1
  31. package/dist/src/components/static-helpers/rest-error.d.ts.map +1 -1
  32. package/dist/src/components/static-helpers/rest-error.js +15 -10
  33. package/dist/src/components/static-helpers/rest-error.js.map +1 -1
  34. package/dist/src/components/testing/client-options.d.ts +1 -1
  35. package/dist/src/components/testing/client-options.d.ts.map +1 -1
  36. package/dist/src/components/transforms/json/json-array-transform.d.ts +1 -1
  37. package/dist/src/components/transforms/json/json-array-transform.d.ts.map +1 -1
  38. package/dist/src/components/transforms/json/json-array-transform.js +6 -7
  39. package/dist/src/components/transforms/json/json-array-transform.js.map +1 -1
  40. package/dist/src/components/transforms/json/json-model-property-transform.d.ts.map +1 -1
  41. package/dist/src/components/transforms/json/json-model-property-transform.js +15 -2
  42. package/dist/src/components/transforms/json/json-model-property-transform.js.map +1 -1
  43. package/dist/src/components/transforms/json/json-model-transform.js +8 -8
  44. package/dist/src/components/transforms/json/json-model-transform.js.map +1 -1
  45. package/dist/src/components/transforms/json/json-record-transform.d.ts +1 -1
  46. package/dist/src/components/transforms/json/json-record-transform.d.ts.map +1 -1
  47. package/dist/src/components/transforms/json/json-record-transform.js +6 -7
  48. package/dist/src/components/transforms/json/json-record-transform.js.map +1 -1
  49. package/dist/src/components/transforms/json/json-transform-discriminator.js +6 -7
  50. package/dist/src/components/transforms/json/json-transform-discriminator.js.map +1 -1
  51. package/dist/src/components/transforms/json/union-transform.js +6 -7
  52. package/dist/src/components/transforms/json/union-transform.js.map +1 -1
  53. package/dist/src/components/transforms/operation-transform-declaration.d.ts.map +1 -1
  54. package/dist/src/components/transforms/operation-transform-declaration.js +2 -3
  55. package/dist/src/components/transforms/operation-transform-declaration.js.map +1 -1
  56. package/dist/src/utils/parameters.d.ts +1 -1
  57. package/dist/src/utils/parameters.d.ts.map +1 -1
  58. package/dist/src/utils/parameters.js +29 -14
  59. package/dist/src/utils/parameters.js.map +1 -1
  60. package/dist/tsconfig.tsbuildinfo +1 -1
  61. package/package.json +5 -5
  62. package/src/components/client-context/client-context-factory.tsx +86 -37
  63. package/src/components/client-operation.tsx +3 -3
  64. package/src/components/client.tsx +6 -9
  65. package/src/components/external-packages/ts-http-runtime.ts +9 -4
  66. package/src/components/http-request-options.tsx +6 -1
  67. package/src/components/http-request-parameters-expression.tsx +142 -18
  68. package/src/components/http-request.tsx +1 -0
  69. package/src/components/operation-parameters.tsx +9 -8
  70. package/src/components/static-helpers/bytes-encoding.tsx +5 -5
  71. package/src/components/static-helpers/multipart-helpers.tsx +7 -7
  72. package/src/components/static-helpers/rest-error.tsx +6 -3
  73. package/src/components/transforms/json/json-array-transform.tsx +3 -3
  74. package/src/components/transforms/json/json-model-property-transform.tsx +13 -1
  75. package/src/components/transforms/json/json-model-transform.tsx +3 -3
  76. package/src/components/transforms/json/json-record-transform.tsx +3 -3
  77. package/src/components/transforms/json/json-transform-discriminator.tsx +3 -3
  78. package/src/components/transforms/json/union-transform.tsx +3 -3
  79. package/src/components/transforms/operation-transform-declaration.tsx +2 -1
  80. package/src/utils/parameters.tsx +43 -28
  81. package/test/e2e/http/authentication/oauth2/main.test.ts +6 -16
  82. package/test/e2e/http/authentication/union/main.test.ts +2 -5
  83. package/test/scenarios/auth/basic_auth.md +11 -7
  84. package/test/scenarios/auth/bearer.md +11 -7
  85. package/test/scenarios/auth/client_parameters.md +19 -6
  86. package/test/scenarios/auth/client_structure.md +1 -1
  87. package/test/scenarios/auth/key_credential.md +11 -6
  88. package/test/scenarios/auth/oauth2.md +91 -0
  89. package/test/scenarios/auth/sub_client_override.md +11 -7
  90. package/test/scenarios/encoding/header_bytes.md +1 -1
  91. package/test/scenarios/encoding/header_date.md +1 -1
  92. package/test/scenarios/encoding/query_date.md +1 -1
  93. package/test/scenarios/http-operations/query-parameter.md +1 -1
  94. package/test/scenarios/operation-parameters/body_root_anonymous.md +1 -1
  95. package/test/scenarios/operation-parameters/with_body_property.md +1 -1
  96. package/test/scenarios/operation-parameters/with_body_root.md +1 -1
@@ -78,9 +78,9 @@ export function JsonTransformDiscriminatorDeclaration(
78
78
  const inputType = props.target === "transport" ? typeRef : "any";
79
79
  const inputRef = ay.refkey();
80
80
 
81
- const parameters: Record<string, ts.ParameterDescriptor> = {
82
- input_: { type: inputType, refkey: inputRef, optional: true },
83
- };
81
+ const parameters: ts.ParameterDescriptor[] = [
82
+ { name: "input_", type: inputType, refkey: inputRef, optional: true },
83
+ ];
84
84
 
85
85
  return (
86
86
  <ts.FunctionDeclaration
@@ -58,9 +58,9 @@ export function JsonUnionTransformDeclaration(props: JsonUnionTransformDeclarati
58
58
  const inputType = props.target === "transport" ? <>{typeRef} | null</> : "any";
59
59
  const inputRef = ay.refkey();
60
60
 
61
- const parameters: Record<string, ts.ParameterDescriptor> = {
62
- input_: { type: inputType, refkey: inputRef, optional: true },
63
- };
61
+ const parameters: ts.ParameterDescriptor[] = [
62
+ { name: "input_", type: inputType, refkey: inputRef, optional: true },
63
+ ];
64
64
 
65
65
  const declarationRefkey = getJsonUnionTransformRefkey(props.type, props.target);
66
66
  return (
@@ -35,6 +35,7 @@ export interface SingleBodyTransformDeclarationProps {
35
35
  export function SingleBodyTransformDeclaration(props: SingleBodyTransformDeclarationProps) {
36
36
  const inputRef = ay.refkey(props.payload, "property");
37
37
  const payloadParameter: ts.ParameterDescriptor = {
38
+ name: "payload",
38
39
  type: <ef.TypeExpression type={props.payload.type} />,
39
40
  refkey: inputRef,
40
41
  };
@@ -43,7 +44,7 @@ export function SingleBodyTransformDeclaration(props: SingleBodyTransformDeclara
43
44
  <ts.FunctionDeclaration
44
45
  export
45
46
  name={props.name}
46
- parameters={{ payload: payloadParameter }}
47
+ parameters={[payloadParameter]}
47
48
  refkey={props.refkey}
48
49
  >
49
50
  return <JsonTransform itemRef={inputRef} target="transport" type={props.payload.type} />
@@ -3,37 +3,37 @@ import * as ts from "@alloy-js/typescript";
3
3
  import { ModelProperty, Value } from "@typespec/compiler";
4
4
  import { $ } from "@typespec/compiler/experimental/typekit";
5
5
  import { buildParameterDescriptor } from "@typespec/emitter-framework/typescript";
6
- import { HttpAuth, HttpProperty } from "@typespec/http";
6
+ import { HttpAuth, HttpProperty, OAuth2FlowType } from "@typespec/http";
7
7
  import * as cl from "@typespec/http-client";
8
8
  import { getClientContextOptionsRef } from "../components/client-context/client-context-options.jsx";
9
9
  import { httpRuntimeTemplateLib } from "../components/external-packages/ts-http-runtime.js";
10
10
 
11
- export function buildClientParameters(client: cl.Client): Record<string, ts.ParameterDescriptor> {
11
+ export function buildClientParameters(client: cl.Client): ts.ParameterDescriptor[] {
12
12
  const clientConstructor = $.client.getConstructor(client);
13
13
  const parameters = $.operation.getClientSignature(client, clientConstructor);
14
- const params = parameters.reduce(
15
- (acc, param) => {
16
- const paramsDescriptor = buildClientParameterDescriptor(param);
17
- if (!paramsDescriptor) {
18
- return acc;
14
+ const params = parameters.flatMap(
15
+ (param) => {
16
+ const descriptor = buildClientParameterDescriptor(param);
17
+ if (!descriptor) {
18
+ return [];
19
19
  }
20
- const [name, descriptor] = paramsDescriptor;
21
20
 
22
21
  if (!descriptor.optional) {
23
- acc[name] = descriptor;
22
+ return [descriptor];
24
23
  }
25
24
 
26
- return acc;
25
+ return [];
27
26
  },
28
27
  {} as Record<string, ts.ParameterDescriptor>,
29
28
  );
30
29
 
31
- if (!params["options"]) {
32
- params["options"] = {
30
+ if (!params.some((p) => p.name === "options")) {
31
+ params.push({
32
+ name: "options",
33
33
  refkey: ay.refkey(),
34
34
  optional: true,
35
35
  type: getClientContextOptionsRef(client),
36
- };
36
+ });
37
37
  }
38
38
 
39
39
  return params;
@@ -41,7 +41,7 @@ export function buildClientParameters(client: cl.Client): Record<string, ts.Para
41
41
 
42
42
  function buildClientParameterDescriptor(
43
43
  modelProperty: ModelProperty,
44
- ): [string, ts.ParameterDescriptor] | undefined {
44
+ ): ts.ParameterDescriptor | undefined {
45
45
  const authSchemes = $.modelProperty.getCredentialAuth(modelProperty);
46
46
 
47
47
  if (authSchemes) {
@@ -52,30 +52,45 @@ function buildClientParameterDescriptor(
52
52
  const credentialType = Array.from(
53
53
  new Set(authSchemes.filter((s) => s.type !== "noAuth").map((s) => getCredentialType(s))),
54
54
  );
55
- return [
56
- "credential",
57
- {
58
- refkey: ay.refkey(modelProperty),
59
- optional: modelProperty.optional,
60
- type: ay.mapJoin(
61
- () => credentialType,
62
- (t) => t,
63
- { joiner: " | " },
64
- ),
65
- },
66
- ];
55
+ return {
56
+ name: "credential",
57
+ refkey: ay.refkey(modelProperty),
58
+ optional: modelProperty.optional,
59
+ type: ay.mapJoin(
60
+ () => credentialType,
61
+ (t) => t,
62
+ { joiner: " | " },
63
+ ),
64
+ };
67
65
  }
68
66
 
69
67
  return buildParameterDescriptor(modelProperty);
70
68
  }
71
69
 
70
+ const oauth2FlowRefs: Record<OAuth2FlowType, ay.Refkey> = {
71
+ authorizationCode: httpRuntimeTemplateLib.AuthorizationCodeFlow,
72
+ clientCredentials: httpRuntimeTemplateLib.ClientCredentialsFlow,
73
+ password: httpRuntimeTemplateLib.PasswordFlow,
74
+ implicit: httpRuntimeTemplateLib.ImplicitFlow,
75
+ };
76
+
72
77
  function getCredentialType(scheme: HttpAuth) {
73
78
  switch (scheme.type) {
74
79
  case "apiKey":
80
+ return httpRuntimeTemplateLib.ApiKeyCredential;
75
81
  case "http":
76
- return httpRuntimeTemplateLib.KeyCredential;
82
+ if (scheme.scheme === "Basic") {
83
+ return httpRuntimeTemplateLib.BasicCredential;
84
+ } else {
85
+ return httpRuntimeTemplateLib.BearerTokenCredential;
86
+ }
77
87
  case "oauth2":
78
- return httpRuntimeTemplateLib.TokenCredential;
88
+ const flowType = ay.mapJoin(
89
+ () => scheme.flows,
90
+ (x) => oauth2FlowRefs[x.type],
91
+ { joiner: " | " },
92
+ );
93
+ return ay.code`${httpRuntimeTemplateLib.OAuth2TokenCredential}<${flowType}>`;
79
94
  default:
80
95
  return null;
81
96
  }
@@ -4,38 +4,28 @@ import { OAuth2Client } from "../../../generated/authentication/oauth2/src/index
4
4
  describe("Authentication.OAuth2", () => {
5
5
  const client = new OAuth2Client(
6
6
  {
7
- getToken: async () => ({
8
- token: "Bearer https://security.microsoft.com/.default",
9
- expiresOnTimestamp: Date.now() + 3600 * 1000,
10
- }),
7
+ getOAuth2Token: async () => "https://security.microsoft.com/.default",
11
8
  },
12
9
  { allowInsecureConnection: true },
13
10
  );
14
11
 
15
- it.skip("should validate the client is authenticated", async () => {
12
+ it("should validate the client is authenticated", async () => {
16
13
  const response = await client.valid();
17
14
  expect(response).toBe(undefined); // No content response
18
15
  });
19
16
 
20
- it.skip("should handle invalid authentication and return error", async () => {
17
+ it("should handle invalid authentication and return error", async () => {
21
18
  try {
22
19
  const client = new OAuth2Client(
23
20
  {
24
- getToken: async () => ({
25
- token: "invalid",
26
- expiresOnTimestamp: Date.now() + 3600 * 1000,
27
- }),
21
+ getOAuth2Token: async () => "invalid",
28
22
  },
29
23
  { allowInsecureConnection: true },
30
24
  );
31
25
  await client.invalid();
32
26
  } catch (error: any) {
33
- expect(error.statusCode).toBe(403);
34
- expect(error.error).toMatchObject({
35
- message: "Expected Bearer x but got Bearer y",
36
- expected: "Bearer x",
37
- actual: "Bearer y",
38
- });
27
+ expect(error.status).toBe("403");
28
+ expect(error.body.error).toBe("invalid-grant");
39
29
  }
40
30
  });
41
31
  });
@@ -13,13 +13,10 @@ describe("Authentication.Union", () => {
13
13
  // Assert successful request
14
14
  });
15
15
 
16
- it.skip("should authenticate using the valid OAuth token", async () => {
16
+ it("should authenticate using the valid OAuth token", async () => {
17
17
  const client = new UnionClient(
18
18
  {
19
- getToken: async () => ({
20
- token: "Bearer https://security.microsoft.com/.default",
21
- expiresOnTimestamp: Date.now() + 3600 * 1000,
22
- }),
19
+ getOAuth2Token: async () => "https://security.microsoft.com/.default",
23
20
  },
24
21
  { allowInsecureConnection: true },
25
22
  );
@@ -20,13 +20,13 @@ op valid(): NoContentResponse;
20
20
 
21
21
  ### Client
22
22
 
23
- The client signature should include a positional parameter for credential of type KeyCredential. A basic auth token is a key credential that gets put into the Authorization header
23
+ The client signature should include a positional parameter for credential of type BasicCredential. A basic auth token consists of a username and password which are concatenated with a colon and base64 encoded. The resulting string is then put into the Authorization header.
24
24
 
25
25
  ```ts src/testClient.ts class TestClient
26
26
  export class TestClient {
27
27
  #context: TestClientContext;
28
28
 
29
- constructor(endpoint: string, credential: KeyCredential, options?: TestClientOptions) {
29
+ constructor(endpoint: string, credential: BasicCredential, options?: TestClientOptions) {
30
30
  this.#context = createTestClientContext(endpoint, credential, options);
31
31
  }
32
32
  async valid(options?: ValidOptions) {
@@ -42,7 +42,7 @@ The client context should setup the pipeline to use the credential in the Author
42
42
  ```ts src/api/testClientContext.ts function createTestClientContext
43
43
  export function createTestClientContext(
44
44
  endpoint: string,
45
- credential: KeyCredential,
45
+ credential: BasicCredential,
46
46
  options?: TestClientOptions,
47
47
  ): TestClientContext {
48
48
  const params: Record<string, any> = {
@@ -55,11 +55,15 @@ export function createTestClientContext(
55
55
  throw new Error(`Missing parameter: ${key}`);
56
56
  })(),
57
57
  );
58
- return getClient(resolvedEndpoint, credential, {
58
+ return getClient(resolvedEndpoint, {
59
59
  ...options,
60
- credentials: {
61
- apiKeyHeaderName: "Authorization",
62
- },
60
+ credential,
61
+ authSchemes: [
62
+ {
63
+ kind: "http",
64
+ scheme: "basic",
65
+ },
66
+ ],
63
67
  });
64
68
  }
65
69
  ```
@@ -20,13 +20,13 @@ op valid(): NoContentResponse;
20
20
 
21
21
  ### Client
22
22
 
23
- The client signature should include a positional parameter for credential of type KeyCredential. A Bearer token is a key credential that gets put into the Authorization header
23
+ The client signature should include a positional parameter for credential of type BearerTokenCredential. A Bearer token is a token credential that gets put into the Authorization header
24
24
 
25
25
  ```ts src/testClient.ts class TestClient
26
26
  export class TestClient {
27
27
  #context: TestClientContext;
28
28
 
29
- constructor(endpoint: string, credential: KeyCredential, options?: TestClientOptions) {
29
+ constructor(endpoint: string, credential: BasicCredential, options?: TestClientOptions) {
30
30
  this.#context = createTestClientContext(endpoint, credential, options);
31
31
  }
32
32
  async valid(options?: ValidOptions) {
@@ -42,7 +42,7 @@ The client context should setup the pipeline to use the credential in the Author
42
42
  ```ts src/api/testClientContext.ts function createTestClientContext
43
43
  export function createTestClientContext(
44
44
  endpoint: string,
45
- credential: KeyCredential,
45
+ credential: BasicCredential,
46
46
  options?: TestClientOptions,
47
47
  ): TestClientContext {
48
48
  const params: Record<string, any> = {
@@ -55,11 +55,15 @@ export function createTestClientContext(
55
55
  throw new Error(`Missing parameter: ${key}`);
56
56
  })(),
57
57
  );
58
- return getClient(resolvedEndpoint, credential, {
58
+ return getClient(resolvedEndpoint, {
59
59
  ...options,
60
- credentials: {
61
- apiKeyHeaderName: "Authorization",
62
- },
60
+ credential,
61
+ authSchemes: [
62
+ {
63
+ kind: "http",
64
+ scheme: "bearer",
65
+ },
66
+ ],
63
67
  });
64
68
  }
65
69
  ```
@@ -27,7 +27,11 @@ TODO: Revisit if we need additional types since it will be difficult at runtime
27
27
  export class TestClient {
28
28
  #context: TestClientContext;
29
29
 
30
- constructor(endpoint: string, credential: KeyCredential, options?: TestClientOptions) {
30
+ constructor(
31
+ endpoint: string,
32
+ credential: BearerTokenCredential | ApiKeyCredential,
33
+ options?: TestClientOptions,
34
+ ) {
31
35
  this.#context = createTestClientContext(endpoint, credential, options);
32
36
  }
33
37
  async valid(options?: ValidOptions) {
@@ -43,7 +47,7 @@ The client context should setup the pipeline to use the credential in the Author
43
47
  ```ts src/api/testClientContext.ts function createTestClientContext
44
48
  export function createTestClientContext(
45
49
  endpoint: string,
46
- credential: KeyCredential,
50
+ credential: BearerTokenCredential | ApiKeyCredential,
47
51
  options?: TestClientOptions,
48
52
  ): TestClientContext {
49
53
  const params: Record<string, any> = {
@@ -56,11 +60,20 @@ export function createTestClientContext(
56
60
  throw new Error(`Missing parameter: ${key}`);
57
61
  })(),
58
62
  );
59
- return getClient(resolvedEndpoint, credential, {
63
+ return getClient(resolvedEndpoint, {
60
64
  ...options,
61
- credentials: {
62
- apiKeyHeaderName: "Authorization",
63
- },
65
+ credential,
66
+ authSchemes: [
67
+ {
68
+ kind: "http",
69
+ scheme: "bearer",
70
+ },
71
+ {
72
+ kind: "apiKey",
73
+ apiKeyLocation: "header",
74
+ name: "X-API-KEY",
75
+ },
76
+ ],
64
77
  });
65
78
  }
66
79
  ```
@@ -27,7 +27,7 @@ export class MyApiClient {
27
27
  #context: MyApiClientContext;
28
28
  fooClient: FooClient;
29
29
  barClient: BarClient;
30
- constructor(endpoint: string, credential: KeyCredential, options?: MyApiClientOptions) {
30
+ constructor(endpoint: string, credential: BasicCredential, options?: MyApiClientOptions) {
31
31
  this.#context = createMyApiClientContext(endpoint, credential, options);
32
32
  this.fooClient = new FooClient(endpoint, credential, options);
33
33
  this.barClient = new BarClient(endpoint, credential, options);
@@ -26,7 +26,7 @@ The client signature should include a positional parameter for credential of typ
26
26
  export class TestClient {
27
27
  #context: TestClientContext;
28
28
 
29
- constructor(endpoint: string, credential: KeyCredential, options?: TestClientOptions) {
29
+ constructor(endpoint: string, credential: ApiKeyCredential, options?: TestClientOptions) {
30
30
  this.#context = createTestClientContext(endpoint, credential, options);
31
31
  }
32
32
  async valid(options?: ValidOptions) {
@@ -42,7 +42,7 @@ The client context should setup the pipeline to use the credential in the header
42
42
  ```ts src/api/testClientContext.ts function createTestClientContext
43
43
  export function createTestClientContext(
44
44
  endpoint: string,
45
- credential: KeyCredential,
45
+ credential: ApiKeyCredential,
46
46
  options?: TestClientOptions,
47
47
  ): TestClientContext {
48
48
  const params: Record<string, any> = {
@@ -55,11 +55,16 @@ export function createTestClientContext(
55
55
  throw new Error(`Missing parameter: ${key}`);
56
56
  })(),
57
57
  );
58
- return getClient(resolvedEndpoint, credential, {
58
+ return getClient(resolvedEndpoint, {
59
59
  ...options,
60
- credentials: {
61
- apiKeyHeaderName: "X-API-KEY",
62
- },
60
+ credential,
61
+ authSchemes: [
62
+ {
63
+ kind: "apiKey",
64
+ apiKeyLocation: "header",
65
+ name: "X-API-KEY",
66
+ },
67
+ ],
63
68
  });
64
69
  }
65
70
  ```
@@ -0,0 +1,91 @@
1
+ # Handles oauth2 authentication scheme
2
+
3
+ This test validates that the emitter can handle a basic authentication scheme correctly, including the client signature and its initialization
4
+
5
+ ## Typespec
6
+
7
+ The spec contains a simple service with a Bearer authentication scheme
8
+
9
+ ```tsp
10
+ @service(#{ title: "Test Service" })
11
+ @useAuth(
12
+ OAuth2Auth<
13
+ [
14
+ {
15
+ type: OAuth2FlowType.clientCredentials,
16
+ tokenUrl: "https://api.example.com/oauth2/authorize",
17
+ refreshUrl: "https://api.example.com/oauth2/refresh",
18
+ }
19
+ ],
20
+ ["read"]
21
+ >
22
+ )
23
+ namespace Test;
24
+
25
+ @route("/valid")
26
+ @get
27
+ op valid(): NoContentResponse;
28
+ ```
29
+
30
+ ## TypeScript
31
+
32
+ ### Client
33
+
34
+ The client signature should include a positional parameter for credential of type KeyCredential. A basic auth token is a key credential that gets put into the Authorization header
35
+
36
+ ```ts src/testClient.ts class TestClient
37
+ export class TestClient {
38
+ #context: TestClientContext;
39
+
40
+ constructor(
41
+ endpoint: string,
42
+ credential: OAuth2TokenCredential<ClientCredentialsFlow>,
43
+ options?: TestClientOptions,
44
+ ) {
45
+ this.#context = createTestClientContext(endpoint, credential, options);
46
+ }
47
+ async valid(options?: ValidOptions) {
48
+ return valid(this.#context, options);
49
+ }
50
+ }
51
+ ```
52
+
53
+ ### ClientContext
54
+
55
+ The client context should setup the pipeline to use the credential in the Authorization header.
56
+
57
+ ```ts src/api/testClientContext.ts function createTestClientContext
58
+ export function createTestClientContext(
59
+ endpoint: string,
60
+ credential: OAuth2TokenCredential<ClientCredentialsFlow>,
61
+ options?: TestClientOptions,
62
+ ): TestClientContext {
63
+ const params: Record<string, any> = {
64
+ endpoint: endpoint,
65
+ };
66
+ const resolvedEndpoint = "{endpoint}".replace(/{([^}]+)}/g, (_, key) =>
67
+ key in params
68
+ ? String(params[key])
69
+ : (() => {
70
+ throw new Error(`Missing parameter: ${key}`);
71
+ })(),
72
+ );
73
+ return getClient(resolvedEndpoint, {
74
+ ...options,
75
+ credential,
76
+ authSchemes: [
77
+ {
78
+ kind: "oauth2",
79
+ flows: [
80
+ {
81
+ kind: "clientCredentials",
82
+ tokenUrl: "https://api.example.com/oauth2/authorize",
83
+ refreshUrl: "https://api.example.com/oauth2/refresh",
84
+ scopes: ["read"],
85
+ },
86
+ ],
87
+ },
88
+ ],
89
+ });
90
+ }
91
+ ```
@@ -35,7 +35,7 @@ The subclient is not a child of the TestClient because they have different param
35
35
  export class TestClient {
36
36
  #context: TestClientContext;
37
37
 
38
- constructor(endpoint: string, credential: KeyCredential, options?: TestClientOptions) {
38
+ constructor(endpoint: string, credential: BasicCredential, options?: TestClientOptions) {
39
39
  this.#context = createTestClientContext(endpoint, credential, options);
40
40
  }
41
41
  async valid(options?: ValidOptions) {
@@ -66,7 +66,7 @@ The client context should setup the pipeline to use the credential in the Author
66
66
  ```ts src/api/testClientContext.ts function createTestClientContext
67
67
  export function createTestClientContext(
68
68
  endpoint: string,
69
- credential: KeyCredential,
69
+ credential: BasicCredential,
70
70
  options?: TestClientOptions,
71
71
  ): TestClientContext {
72
72
  const params: Record<string, any> = {
@@ -79,11 +79,15 @@ export function createTestClientContext(
79
79
  throw new Error(`Missing parameter: ${key}`);
80
80
  })(),
81
81
  );
82
- return getClient(resolvedEndpoint, credential, {
82
+ return getClient(resolvedEndpoint, {
83
83
  ...options,
84
- credentials: {
85
- apiKeyHeaderName: "Authorization",
86
- },
84
+ credential,
85
+ authSchemes: [
86
+ {
87
+ kind: "http",
88
+ scheme: "basic",
89
+ },
90
+ ],
87
91
  });
88
92
  }
89
93
  ```
@@ -105,7 +109,7 @@ export function createSubClientContext(
105
109
  throw new Error(`Missing parameter: ${key}`);
106
110
  })(),
107
111
  );
108
- return getClient(resolvedEndpoint, credential, {
112
+ return getClient(resolvedEndpoint, {
109
113
  ...options,
110
114
  });
111
115
  }
@@ -69,7 +69,7 @@ export async function defaultEncoding(
69
69
  const httpRequestOptions = {
70
70
  headers: {
71
71
  ...(options?.value && {
72
- value: encodeUint8Array(options?.value, "base64")!,
72
+ value: encodeUint8Array(options.value, "base64")!,
73
73
  }),
74
74
  },
75
75
  };
@@ -68,7 +68,7 @@ export async function defaultEncoding(
68
68
  const path = parse("/default").expand({});
69
69
  const httpRequestOptions = {
70
70
  headers: {
71
- ...(options?.value && { value: dateRfc7231Serializer(options?.value) }),
71
+ ...(options?.value && { value: dateRfc7231Serializer(options.value) }),
72
72
  },
73
73
  };
74
74
  const response = await client.pathUnchecked(path).get(httpRequestOptions);
@@ -66,7 +66,7 @@ export async function defaultEncoding(
66
66
  options?: DefaultEncodingOptions,
67
67
  ): Promise<void> {
68
68
  const path = parse("/default{?value}").expand({
69
- ...(options?.value && { value: dateRfc3339Serializer(options?.value) }),
69
+ ...(options?.value && { value: dateRfc3339Serializer(options.value) }),
70
70
  });
71
71
  const httpRequestOptions = {
72
72
  headers: {},
@@ -24,7 +24,7 @@ export async function headModel(
24
24
  const path = parse("/").expand({});
25
25
  const httpRequestOptions = {
26
26
  headers: {
27
- ...(options?.foo && { foo: options?.foo }),
27
+ ...(input.foo && { foo: input.foo }),
28
28
  },
29
29
  body: jsonVisibilityModelToTransportTransform(input),
30
30
  };
@@ -27,7 +27,7 @@ export async function create(
27
27
  const path = parse("/").expand({});
28
28
  const httpRequestOptions = {
29
29
  headers: {
30
- ...(options?.foo && { foo: options?.foo }),
30
+ ...(widget.foo && { foo: widget.foo }),
31
31
  },
32
32
  body: {
33
33
  id: widget.id,
@@ -26,7 +26,7 @@ export async function create(
26
26
  const path = parse("/").expand({});
27
27
  const httpRequestOptions = {
28
28
  headers: {
29
- ...(options?.foo && { foo: options?.foo }),
29
+ ...(options?.foo && { foo: options.foo }),
30
30
  },
31
31
  body: jsonWidgetToTransportTransform(widget),
32
32
  };
@@ -27,7 +27,7 @@ export async function create(
27
27
  const path = parse("/").expand({});
28
28
  const httpRequestOptions = {
29
29
  headers: {
30
- ...(options?.foo && { foo: options?.foo }),
30
+ ...(widget.foo && { foo: widget.foo }),
31
31
  },
32
32
  body: jsonWidgetToTransportTransform(widget),
33
33
  };