@azure/core-client 1.9.2-alpha.20240322.2 → 1.9.2-alpha.20240329.3

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 (73) hide show
  1. package/dist/browser/authorizeRequestOnClaimChallenge.js +1 -1
  2. package/dist/browser/authorizeRequestOnClaimChallenge.js.map +1 -1
  3. package/dist/browser/authorizeRequestOnTenantChallenge.js +2 -5
  4. package/dist/browser/authorizeRequestOnTenantChallenge.js.map +1 -1
  5. package/dist/browser/deserializationPolicy.js +16 -13
  6. package/dist/browser/deserializationPolicy.js.map +1 -1
  7. package/dist/browser/pipeline.js +1 -1
  8. package/dist/browser/pipeline.js.map +1 -1
  9. package/dist/browser/serializationPolicy.js +10 -8
  10. package/dist/browser/serializationPolicy.js.map +1 -1
  11. package/dist/browser/serializer.js +23 -22
  12. package/dist/browser/serializer.js.map +1 -1
  13. package/dist/browser/serviceClient.js +7 -31
  14. package/dist/browser/serviceClient.js.map +1 -1
  15. package/dist/browser/urlHelpers.js +4 -2
  16. package/dist/browser/urlHelpers.js.map +1 -1
  17. package/dist/browser/utils.js +10 -23
  18. package/dist/browser/utils.js.map +1 -1
  19. package/dist/commonjs/authorizeRequestOnClaimChallenge.js +1 -1
  20. package/dist/commonjs/authorizeRequestOnClaimChallenge.js.map +1 -1
  21. package/dist/commonjs/authorizeRequestOnTenantChallenge.js +2 -5
  22. package/dist/commonjs/authorizeRequestOnTenantChallenge.js.map +1 -1
  23. package/dist/commonjs/deserializationPolicy.js +16 -13
  24. package/dist/commonjs/deserializationPolicy.js.map +1 -1
  25. package/dist/commonjs/pipeline.js +1 -1
  26. package/dist/commonjs/pipeline.js.map +1 -1
  27. package/dist/commonjs/serializationPolicy.js +10 -8
  28. package/dist/commonjs/serializationPolicy.js.map +1 -1
  29. package/dist/commonjs/serializer.js +23 -22
  30. package/dist/commonjs/serializer.js.map +1 -1
  31. package/dist/commonjs/serviceClient.js +7 -31
  32. package/dist/commonjs/serviceClient.js.map +1 -1
  33. package/dist/commonjs/urlHelpers.js +4 -2
  34. package/dist/commonjs/urlHelpers.js.map +1 -1
  35. package/dist/commonjs/utils.js +10 -23
  36. package/dist/commonjs/utils.js.map +1 -1
  37. package/dist/esm/authorizeRequestOnClaimChallenge.js +1 -1
  38. package/dist/esm/authorizeRequestOnClaimChallenge.js.map +1 -1
  39. package/dist/esm/authorizeRequestOnTenantChallenge.js +2 -5
  40. package/dist/esm/authorizeRequestOnTenantChallenge.js.map +1 -1
  41. package/dist/esm/deserializationPolicy.js +16 -13
  42. package/dist/esm/deserializationPolicy.js.map +1 -1
  43. package/dist/esm/pipeline.js +1 -1
  44. package/dist/esm/pipeline.js.map +1 -1
  45. package/dist/esm/serializationPolicy.js +10 -8
  46. package/dist/esm/serializationPolicy.js.map +1 -1
  47. package/dist/esm/serializer.js +23 -22
  48. package/dist/esm/serializer.js.map +1 -1
  49. package/dist/esm/serviceClient.js +7 -31
  50. package/dist/esm/serviceClient.js.map +1 -1
  51. package/dist/esm/urlHelpers.js +4 -2
  52. package/dist/esm/urlHelpers.js.map +1 -1
  53. package/dist/esm/utils.js +10 -23
  54. package/dist/esm/utils.js.map +1 -1
  55. package/dist/react-native/authorizeRequestOnClaimChallenge.js +1 -1
  56. package/dist/react-native/authorizeRequestOnClaimChallenge.js.map +1 -1
  57. package/dist/react-native/authorizeRequestOnTenantChallenge.js +2 -5
  58. package/dist/react-native/authorizeRequestOnTenantChallenge.js.map +1 -1
  59. package/dist/react-native/deserializationPolicy.js +16 -13
  60. package/dist/react-native/deserializationPolicy.js.map +1 -1
  61. package/dist/react-native/pipeline.js +1 -1
  62. package/dist/react-native/pipeline.js.map +1 -1
  63. package/dist/react-native/serializationPolicy.js +10 -8
  64. package/dist/react-native/serializationPolicy.js.map +1 -1
  65. package/dist/react-native/serializer.js +23 -22
  66. package/dist/react-native/serializer.js.map +1 -1
  67. package/dist/react-native/serviceClient.js +7 -31
  68. package/dist/react-native/serviceClient.js.map +1 -1
  69. package/dist/react-native/urlHelpers.js +4 -2
  70. package/dist/react-native/urlHelpers.js.map +1 -1
  71. package/dist/react-native/utils.js +10 -23
  72. package/dist/react-native/utils.js.map +1 -1
  73. package/package.json +2 -2
@@ -15,43 +15,22 @@ const log_js_1 = require("./log.js");
15
15
  * Initializes a new instance of the ServiceClient.
16
16
  */
17
17
  class ServiceClient {
18
- /**
19
- * If specified, this is the base URI that requests will be made against for this ServiceClient.
20
- * If it is not specified, then all OperationSpecs must contain a baseUrl property.
21
- */
22
- _endpoint;
23
- /**
24
- * The default request content type for the service.
25
- * Used if no requestContentType is present on an OperationSpec.
26
- */
27
- _requestContentType;
28
- /**
29
- * Set to true if the request is sent over HTTP instead of HTTPS
30
- */
31
- _allowInsecureConnection;
32
- /**
33
- * The HTTP client that will be used to send requests.
34
- */
35
- _httpClient;
36
- /**
37
- * The pipeline used by this client to make requests
38
- */
39
- pipeline;
40
18
  /**
41
19
  * The ServiceClient constructor
42
20
  * @param credential - The credentials used for authentication with the service.
43
21
  * @param options - The service client options that govern the behavior of the client.
44
22
  */
45
23
  constructor(options = {}) {
24
+ var _a, _b;
46
25
  this._requestContentType = options.requestContentType;
47
- this._endpoint = options.endpoint ?? options.baseUri;
26
+ this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
48
27
  if (options.baseUri) {
49
28
  log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
50
29
  }
51
30
  this._allowInsecureConnection = options.allowInsecureConnection;
52
31
  this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)();
53
32
  this.pipeline = options.pipeline || createDefaultPipeline(options);
54
- if (options.additionalPolicies?.length) {
33
+ if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
55
34
  for (const { policy, position } of options.additionalPolicies) {
56
35
  // Sign happens after Retry and is commonly needed to occur
57
36
  // before policies that intercept post-retry.
@@ -130,17 +109,17 @@ class ServiceClient {
130
109
  try {
131
110
  const rawResponse = await this.sendRequest(request);
132
111
  const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]);
133
- if (options?.onResponse) {
112
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
134
113
  options.onResponse(rawResponse, flatResponse);
135
114
  }
136
115
  return flatResponse;
137
116
  }
138
117
  catch (error) {
139
- if (typeof error === "object" && error?.response) {
118
+ if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
140
119
  const rawResponse = error.response;
141
120
  const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
142
121
  error.details = flatResponse;
143
- if (options?.onResponse) {
122
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
144
123
  options.onResponse(rawResponse, flatResponse, error);
145
124
  }
146
125
  }
@@ -154,10 +133,7 @@ function createDefaultPipeline(options) {
154
133
  const credentialOptions = options.credential && credentialScopes
155
134
  ? { credentialScopes, credential: options.credential }
156
135
  : undefined;
157
- return (0, pipeline_js_1.createClientPipeline)({
158
- ...options,
159
- credentialOptions,
160
- });
136
+ return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions }));
161
137
  }
162
138
  function getCredentialScopes(options) {
163
139
  if (options.credentialScopes) {
@@ -1 +1 @@
1
- {"version":3,"file":"serviceClient.js","sourceRoot":"","sources":["../../src/serviceClient.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAQlC,kEAMmC;AAEnC,+CAAqD;AACrD,yCAA6C;AAC7C,6DAAkE;AAClE,+DAAgE;AAChE,mDAAgD;AAChD,+DAAwE;AACxE,qCAAkC;AAqClC;;GAEG;AACH,MAAa,aAAa;IACxB;;;OAGG;IACc,SAAS,CAAU;IAEpC;;;OAGG;IACc,mBAAmB,CAAU;IAE9C;;OAEG;IACc,wBAAwB,CAAW;IAEpD;;OAEG;IACc,WAAW,CAAa;IAEzC;;OAE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AAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CommonClientOptions,\n OperationArguments,\n OperationRequest,\n OperationSpec,\n} from \"./interfaces.js\";\nimport {\n HttpClient,\n Pipeline,\n PipelineRequest,\n PipelineResponse,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { createClientPipeline } from \"./pipeline.js\";\nimport { flattenResponse } from \"./utils.js\";\nimport { getCachedDefaultHttpClient } from \"./httpClientCache.js\";\nimport { getOperationRequestInfo } from \"./operationHelpers.js\";\nimport { getRequestUrl } from \"./urlHelpers.js\";\nimport { getStreamingResponseStatusCodes } from \"./interfaceHelpers.js\";\nimport { logger } from \"./log.js\";\n\n/**\n * Options to be provided while creating the client.\n */\nexport interface ServiceClientOptions extends CommonClientOptions {\n /**\n * If specified, this is the base URI that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n * @deprecated This property is deprecated and will be removed soon, please use endpoint instead\n */\n baseUri?: string;\n /**\n * If specified, this is the endpoint that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n * to encourage customer to use endpoint, we mark the baseUri as deprecated.\n */\n endpoint?: string;\n /**\n * If specified, will be used to build the BearerTokenAuthenticationPolicy.\n */\n credentialScopes?: string | string[];\n /**\n * The default request content type for the service.\n * Used if no requestContentType is present on an OperationSpec.\n */\n requestContentType?: string;\n /**\n * Credential used to authenticate the request.\n */\n credential?: TokenCredential;\n /**\n * A customized pipeline to use, otherwise a default one will be created.\n */\n pipeline?: Pipeline;\n}\n\n/**\n * Initializes a new instance of the ServiceClient.\n */\nexport class ServiceClient {\n /**\n * If specified, this is the base URI that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n */\n private readonly _endpoint?: string;\n\n /**\n * The default request content type for the service.\n * Used if no requestContentType is present on an OperationSpec.\n */\n private readonly _requestContentType?: string;\n\n /**\n * Set to true if the request is sent over HTTP instead of HTTPS\n */\n private readonly _allowInsecureConnection?: boolean;\n\n /**\n * The HTTP client that will be used to send requests.\n */\n private readonly _httpClient: HttpClient;\n\n /**\n * The pipeline used by this client to make requests\n */\n public readonly pipeline: Pipeline;\n\n /**\n * The ServiceClient constructor\n * @param credential - The credentials used for authentication with the service.\n * @param options - The service client options that govern the behavior of the client.\n */\n constructor(options: ServiceClientOptions = {}) {\n this._requestContentType = options.requestContentType;\n this._endpoint = options.endpoint ?? options.baseUri;\n if (options.baseUri) {\n logger.warning(\n \"The baseUri option for SDK Clients has been deprecated, please use endpoint instead.\",\n );\n }\n this._allowInsecureConnection = options.allowInsecureConnection;\n this._httpClient = options.httpClient || getCachedDefaultHttpClient();\n\n this.pipeline = options.pipeline || createDefaultPipeline(options);\n if (options.additionalPolicies?.length) {\n for (const { policy, position } of options.additionalPolicies) {\n // Sign happens after Retry and is commonly needed to occur\n // before policies that intercept post-retry.\n const afterPhase = position === \"perRetry\" ? \"Sign\" : undefined;\n this.pipeline.addPolicy(policy, {\n afterPhase,\n });\n }\n }\n }\n\n /**\n * Send the provided httpRequest.\n */\n async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n return this.pipeline.sendRequest(this._httpClient, request);\n }\n\n /**\n * Send an HTTP request that is populated using the provided OperationSpec.\n * @typeParam T - The typed result of the request, based on the OperationSpec.\n * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.\n * @param operationSpec - The OperationSpec to use to populate the httpRequest.\n */\n async sendOperationRequest<T>(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<T> {\n const endpoint: string | undefined = operationSpec.baseUrl || this._endpoint;\n if (!endpoint) {\n throw new Error(\n \"If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.\",\n );\n }\n\n // Templatized URLs sometimes reference properties on the ServiceClient child class,\n // so we have to pass `this` below in order to search these properties if they're\n // not part of OperationArguments\n const url = getRequestUrl(endpoint, operationSpec, operationArguments, this);\n\n const request: OperationRequest = createPipelineRequest({\n url,\n });\n request.method = operationSpec.httpMethod;\n const operationInfo = getOperationRequestInfo(request);\n operationInfo.operationSpec = operationSpec;\n operationInfo.operationArguments = operationArguments;\n\n const contentType = operationSpec.contentType || this._requestContentType;\n if (contentType && operationSpec.requestBody) {\n request.headers.set(\"Content-Type\", contentType);\n }\n\n const options = operationArguments.options;\n if (options) {\n const requestOptions = options.requestOptions;\n\n if (requestOptions) {\n if (requestOptions.timeout) {\n request.timeout = requestOptions.timeout;\n }\n\n if (requestOptions.onUploadProgress) {\n request.onUploadProgress = requestOptions.onUploadProgress;\n }\n\n if (requestOptions.onDownloadProgress) {\n request.onDownloadProgress = requestOptions.onDownloadProgress;\n }\n\n if (requestOptions.shouldDeserialize !== undefined) {\n operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;\n }\n\n if (requestOptions.allowInsecureConnection) {\n request.allowInsecureConnection = true;\n }\n }\n\n if (options.abortSignal) {\n request.abortSignal = options.abortSignal;\n }\n\n if (options.tracingOptions) {\n request.tracingOptions = options.tracingOptions;\n }\n }\n\n if (this._allowInsecureConnection) {\n request.allowInsecureConnection = true;\n }\n\n if (request.streamResponseStatusCodes === undefined) {\n request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec);\n }\n\n try {\n const rawResponse = await this.sendRequest(request);\n const flatResponse = flattenResponse(\n rawResponse,\n operationSpec.responses[rawResponse.status],\n ) as T;\n if (options?.onResponse) {\n options.onResponse(rawResponse, flatResponse);\n }\n return flatResponse;\n } catch (error: any) {\n if (typeof error === \"object\" && error?.response) {\n const rawResponse = error.response;\n const flatResponse = flattenResponse(\n rawResponse,\n operationSpec.responses[error.statusCode] || operationSpec.responses[\"default\"],\n );\n error.details = flatResponse;\n if (options?.onResponse) {\n options.onResponse(rawResponse, flatResponse, error);\n }\n }\n throw error;\n }\n }\n}\n\nfunction createDefaultPipeline(options: ServiceClientOptions): Pipeline {\n const credentialScopes = getCredentialScopes(options);\n const credentialOptions =\n options.credential && credentialScopes\n ? { credentialScopes, credential: options.credential }\n : undefined;\n\n return createClientPipeline({\n ...options,\n credentialOptions,\n });\n}\n\nfunction getCredentialScopes(options: ServiceClientOptions): string | string[] | undefined {\n if (options.credentialScopes) {\n return options.credentialScopes;\n }\n\n if (options.endpoint) {\n return `${options.endpoint}/.default`;\n }\n\n if (options.baseUri) {\n return `${options.baseUri}/.default`;\n }\n\n if (options.credential && !options.credentialScopes) {\n throw new Error(\n `When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`,\n );\n }\n\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"serviceClient.js","sourceRoot":"","sources":["../../src/serviceClient.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAQlC,kEAMmC;AAEnC,+CAAqD;AACrD,yCAA6C;AAC7C,6DAAkE;AAClE,+DAAgE;AAChE,mDAAgD;AAChD,+DAAwE;AACxE,qCAAkC;AAqClC;;GAEG;AACH,MAAa,aAAa;IA4BxB;;;;OAIG;IACH,YAAY,UAAgC,EAAE;;QAC5C,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACtD,IAAI,CAAC,SAAS,GAAG,MAAA,OAAO,CAAC,QAAQ,mCAAI,OAAO,CAAC,OAAO,CAAC;QACrD,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,eAAM,CAAC,OAAO,CACZ,sFAAsF,CACvF,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,wBAAwB,GAAG,OAAO,CAAC,uBAAuB,CAAC;QAChE,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,IAAI,IAAA,+CAA0B,GAAE,CAAC;QAEtE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,qBAAqB,CAAC,OAAO,CAAC,CAAC;QACnE,I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1D,MAAM,gBAAgB,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,iBAAiB,GACrB,OAAO,CAAC,UAAU,IAAI,gBAAgB;QACpC,CAAC,CAAC,EAAE,gBAAgB,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE;QACtD,CAAC,CAAC,SAAS,CAAC;IAEhB,OAAO,IAAA,kCAAoB,kCACtB,OAAO,KACV,iBAAiB,IACjB,CAAC;AACL,CAAC;AAED,SAAS,mBAAmB,CAAC,OAA6B;IACxD,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;QAC7B,OAAO,OAAO,CAAC,gBAAgB,CAAC;IAClC,CAAC;IAED,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;QACrB,OAAO,GAAG,OAAO,CAAC,QAAQ,WAAW,CAAC;IACxC,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO,GAAG,OAAO,CAAC,OAAO,WAAW,CAAC;IACvC,CAAC;IAED,IAAI,OAAO,CAAC,UAAU,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC;QACpD,MAAM,IAAI,KAAK,CACb,2JAA2J,CAC5J,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CommonClientOptions,\n OperationArguments,\n OperationRequest,\n OperationSpec,\n} from \"./interfaces.js\";\nimport {\n HttpClient,\n Pipeline,\n PipelineRequest,\n PipelineResponse,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { createClientPipeline } from \"./pipeline.js\";\nimport { flattenResponse } from \"./utils.js\";\nimport { getCachedDefaultHttpClient } from \"./httpClientCache.js\";\nimport { getOperationRequestInfo } from \"./operationHelpers.js\";\nimport { getRequestUrl } from \"./urlHelpers.js\";\nimport { getStreamingResponseStatusCodes } from \"./interfaceHelpers.js\";\nimport { logger } from \"./log.js\";\n\n/**\n * Options to be provided while creating the client.\n */\nexport interface ServiceClientOptions extends CommonClientOptions {\n /**\n * If specified, this is the base URI that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n * @deprecated This property is deprecated and will be removed soon, please use endpoint instead\n */\n baseUri?: string;\n /**\n * If specified, this is the endpoint that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n * to encourage customer to use endpoint, we mark the baseUri as deprecated.\n */\n endpoint?: string;\n /**\n * If specified, will be used to build the BearerTokenAuthenticationPolicy.\n */\n credentialScopes?: string | string[];\n /**\n * The default request content type for the service.\n * Used if no requestContentType is present on an OperationSpec.\n */\n requestContentType?: string;\n /**\n * Credential used to authenticate the request.\n */\n credential?: TokenCredential;\n /**\n * A customized pipeline to use, otherwise a default one will be created.\n */\n pipeline?: Pipeline;\n}\n\n/**\n * Initializes a new instance of the ServiceClient.\n */\nexport class ServiceClient {\n /**\n * If specified, this is the base URI that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n */\n private readonly _endpoint?: string;\n\n /**\n * The default request content type for the service.\n * Used if no requestContentType is present on an OperationSpec.\n */\n private readonly _requestContentType?: string;\n\n /**\n * Set to true if the request is sent over HTTP instead of HTTPS\n */\n private readonly _allowInsecureConnection?: boolean;\n\n /**\n * The HTTP client that will be used to send requests.\n */\n private readonly _httpClient: HttpClient;\n\n /**\n * The pipeline used by this client to make requests\n */\n public readonly pipeline: Pipeline;\n\n /**\n * The ServiceClient constructor\n * @param credential - The credentials used for authentication with the service.\n * @param options - The service client options that govern the behavior of the client.\n */\n constructor(options: ServiceClientOptions = {}) {\n this._requestContentType = options.requestContentType;\n this._endpoint = options.endpoint ?? options.baseUri;\n if (options.baseUri) {\n logger.warning(\n \"The baseUri option for SDK Clients has been deprecated, please use endpoint instead.\",\n );\n }\n this._allowInsecureConnection = options.allowInsecureConnection;\n this._httpClient = options.httpClient || getCachedDefaultHttpClient();\n\n this.pipeline = options.pipeline || createDefaultPipeline(options);\n if (options.additionalPolicies?.length) {\n for (const { policy, position } of options.additionalPolicies) {\n // Sign happens after Retry and is commonly needed to occur\n // before policies that intercept post-retry.\n const afterPhase = position === \"perRetry\" ? \"Sign\" : undefined;\n this.pipeline.addPolicy(policy, {\n afterPhase,\n });\n }\n }\n }\n\n /**\n * Send the provided httpRequest.\n */\n async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n return this.pipeline.sendRequest(this._httpClient, request);\n }\n\n /**\n * Send an HTTP request that is populated using the provided OperationSpec.\n * @typeParam T - The typed result of the request, based on the OperationSpec.\n * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.\n * @param operationSpec - The OperationSpec to use to populate the httpRequest.\n */\n async sendOperationRequest<T>(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<T> {\n const endpoint: string | undefined = operationSpec.baseUrl || this._endpoint;\n if (!endpoint) {\n throw new Error(\n \"If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.\",\n );\n }\n\n // Templatized URLs sometimes reference properties on the ServiceClient child class,\n // so we have to pass `this` below in order to search these properties if they're\n // not part of OperationArguments\n const url = getRequestUrl(endpoint, operationSpec, operationArguments, this);\n\n const request: OperationRequest = createPipelineRequest({\n url,\n });\n request.method = operationSpec.httpMethod;\n const operationInfo = getOperationRequestInfo(request);\n operationInfo.operationSpec = operationSpec;\n operationInfo.operationArguments = operationArguments;\n\n const contentType = operationSpec.contentType || this._requestContentType;\n if (contentType && operationSpec.requestBody) {\n request.headers.set(\"Content-Type\", contentType);\n }\n\n const options = operationArguments.options;\n if (options) {\n const requestOptions = options.requestOptions;\n\n if (requestOptions) {\n if (requestOptions.timeout) {\n request.timeout = requestOptions.timeout;\n }\n\n if (requestOptions.onUploadProgress) {\n request.onUploadProgress = requestOptions.onUploadProgress;\n }\n\n if (requestOptions.onDownloadProgress) {\n request.onDownloadProgress = requestOptions.onDownloadProgress;\n }\n\n if (requestOptions.shouldDeserialize !== undefined) {\n operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;\n }\n\n if (requestOptions.allowInsecureConnection) {\n request.allowInsecureConnection = true;\n }\n }\n\n if (options.abortSignal) {\n request.abortSignal = options.abortSignal;\n }\n\n if (options.tracingOptions) {\n request.tracingOptions = options.tracingOptions;\n }\n }\n\n if (this._allowInsecureConnection) {\n request.allowInsecureConnection = true;\n }\n\n if (request.streamResponseStatusCodes === undefined) {\n request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec);\n }\n\n try {\n const rawResponse = await this.sendRequest(request);\n const flatResponse = flattenResponse(\n rawResponse,\n operationSpec.responses[rawResponse.status],\n ) as T;\n if (options?.onResponse) {\n options.onResponse(rawResponse, flatResponse);\n }\n return flatResponse;\n } catch (error: any) {\n if (typeof error === \"object\" && error?.response) {\n const rawResponse = error.response;\n const flatResponse = flattenResponse(\n rawResponse,\n operationSpec.responses[error.statusCode] || operationSpec.responses[\"default\"],\n );\n error.details = flatResponse;\n if (options?.onResponse) {\n options.onResponse(rawResponse, flatResponse, error);\n }\n }\n throw error;\n }\n }\n}\n\nfunction createDefaultPipeline(options: ServiceClientOptions): Pipeline {\n const credentialScopes = getCredentialScopes(options);\n const credentialOptions =\n options.credential && credentialScopes\n ? { credentialScopes, credential: options.credential }\n : undefined;\n\n return createClientPipeline({\n ...options,\n credentialOptions,\n });\n}\n\nfunction getCredentialScopes(options: ServiceClientOptions): string | string[] | undefined {\n if (options.credentialScopes) {\n return options.credentialScopes;\n }\n\n if (options.endpoint) {\n return `${options.endpoint}/.default`;\n }\n\n if (options.baseUri) {\n return `${options.baseUri}/.default`;\n }\n\n if (options.credential && !options.credentialScopes) {\n throw new Error(\n `When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`,\n );\n }\n\n return undefined;\n}\n"]}
@@ -54,8 +54,9 @@ function replaceAll(input, replacements) {
54
54
  return result;
55
55
  }
56
56
  function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
57
+ var _a;
57
58
  const result = new Map();
58
- if (operationSpec.urlParameters?.length) {
59
+ if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
59
60
  for (const urlParameter of operationSpec.urlParameters) {
60
61
  let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject);
61
62
  const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter);
@@ -99,9 +100,10 @@ function appendPath(url, pathToAppend) {
99
100
  return parsedUrl.toString();
100
101
  }
101
102
  function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
103
+ var _a;
102
104
  const result = new Map();
103
105
  const sequenceParams = new Set();
104
- if (operationSpec.queryParameters?.length) {
106
+ if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
105
107
  for (const queryParameter of operationSpec.queryParameters) {
106
108
  if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
107
109
  sequenceParams.add(queryParameter.mapper.serializedName);
@@ -1 +1 @@
1
- {"version":3,"file":"urlHelpers.js","sourceRoot":"","sources":["../../src/urlHelpers.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,+DAA+E;AAC/E,+DAAmE;AAEnE,MAAM,8BAA8B,GAA+C;IACjF,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,KAAK,EAAE,OAAO;IACd,GAAG,EAAE,IAAI;IACT,KAAK,EAAE,GAAG;CACX,CAAC;AAEF,SAAgB,aAAa,CAC3B,OAAe,EACf,aAA4B,EAC5B,kBAAsC,EACtC,cAAgD;IAEhD,MAAM,eAAe,GAAG,wBAAwB,CAC9C,aAAa,EACb,kBAAkB,EAClB,cAAc,CACf,CAAC;IAEF,IAAI,cAAc,GAAG,KAAK,CAAC;IAE3B,IA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,GAAG,IAAI,IAAI,KAAK,EAAE,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;IAED,6FAA6F;IAC7F,SAAS,CAAC,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3E,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;AAC9B,CAAC;AA1DD,8CA0DC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { OperationArguments, OperationSpec, QueryCollectionFormat } from \"./interfaces.js\";\nimport { getOperationArgumentValueFromParameter } from \"./operationHelpers.js\";\nimport { getPathStringFromParameter } from \"./interfaceHelpers.js\";\n\nconst CollectionFormatToDelimiterMap: { [key in QueryCollectionFormat]: string } = {\n CSV: \",\",\n SSV: \" \",\n Multi: \"Multi\",\n TSV: \"\\t\",\n Pipes: \"|\",\n};\n\nexport function getRequestUrl(\n baseUri: string,\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any },\n): string {\n const urlReplacements = calculateUrlReplacements(\n operationSpec,\n operationArguments,\n fallbackObject,\n );\n\n let isAbsolutePath = false;\n\n let requestUrl = replaceAll(baseUri, urlReplacements);\n if (operationSpec.path) {\n let path = replaceAll(operationSpec.path, urlReplacements);\n // QUIRK: sometimes we get a path component like /{nextLink}\n // which may be a fully formed URL with a leading /. In that case, we should\n // remove the leading /\n if (operationSpec.path === \"/{nextLink}\" && path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n // QUIRK: sometimes we get a path component like {nextLink}\n // which may be a fully formed URL. In that case, we should\n // ignore the baseUri.\n if (isAbsoluteUrl(path)) {\n requestUrl = path;\n isAbsolutePath = true;\n } else {\n requestUrl = appendPath(requestUrl, path);\n }\n }\n\n const { queryParams, sequenceParams } = calculateQueryParameters(\n operationSpec,\n operationArguments,\n fallbackObject,\n );\n /**\n * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`\n * is an absolute path. This ensures that existing query parameter values in `requestUrl`\n * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it\n * is still being built so there is nothing to overwrite.\n */\n requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);\n\n return requestUrl;\n}\n\nfunction replaceAll(input: string, replacements: Map<string, string>): string {\n let result = input;\n for (const [searchValue, replaceValue] of replacements) {\n result = result.split(searchValue).join(replaceValue);\n }\n return result;\n}\n\nfunction calculateUrlReplacements(\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any },\n): Map<string, string> {\n const result = new Map<string, string>();\n if (operationSpec.urlParameters?.length) {\n for (const urlParameter of operationSpec.urlParameters) {\n let urlParameterValue: string = getOperationArgumentValueFromParameter(\n operationArguments,\n urlParameter,\n fallbackObject,\n );\n const parameterPathString = getPathStringFromParameter(urlParameter);\n urlParameterValue = operationSpec.serializer.serialize(\n urlParameter.mapper,\n urlParameterValue,\n parameterPathString,\n );\n if (!urlParameter.skipEncoding) {\n urlParameterValue = encodeURIComponent(urlParameterValue);\n }\n result.set(\n `{${urlParameter.mapper.serializedName || parameterPathString}}`,\n urlParameterValue,\n );\n }\n }\n return result;\n}\n\nfunction isAbsoluteUrl(url: string): boolean {\n return url.includes(\"://\");\n}\n\nfunction appendPath(url: string, pathToAppend?: string): string {\n if (!pathToAppend) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n let newPath = parsedUrl.pathname;\n\n if (!newPath.endsWith(\"/\")) {\n newPath = `${newPath}/`;\n }\n\n if (pathToAppend.startsWith(\"/\")) {\n pathToAppend = pathToAppend.substring(1);\n }\n\n const searchStart = pathToAppend.indexOf(\"?\");\n if (searchStart !== -1) {\n const path = pathToAppend.substring(0, searchStart);\n const search = pathToAppend.substring(searchStart + 1);\n newPath = newPath + path;\n if (search) {\n parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;\n }\n } else {\n newPath = newPath + pathToAppend;\n }\n\n parsedUrl.pathname = newPath;\n\n return parsedUrl.toString();\n}\n\nfunction calculateQueryParameters(\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any },\n): {\n queryParams: Map<string, string | string[]>;\n sequenceParams: Set<string>;\n} {\n const result = new Map<string, string | string[]>();\n const sequenceParams: Set<string> = new Set<string>();\n\n if (operationSpec.queryParameters?.length) {\n for (const queryParameter of operationSpec.queryParameters) {\n if (queryParameter.mapper.type.name === \"Sequence\" && queryParameter.mapper.serializedName) {\n sequenceParams.add(queryParameter.mapper.serializedName);\n }\n let queryParameterValue: string | string[] = getOperationArgumentValueFromParameter(\n operationArguments,\n queryParameter,\n fallbackObject,\n );\n if (\n (queryParameterValue !== undefined && queryParameterValue !== null) ||\n queryParameter.mapper.required\n ) {\n queryParameterValue = operationSpec.serializer.serialize(\n queryParameter.mapper,\n queryParameterValue,\n getPathStringFromParameter(queryParameter),\n );\n\n const delimiter = queryParameter.collectionFormat\n ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]\n : \"\";\n if (Array.isArray(queryParameterValue)) {\n // replace null and undefined\n queryParameterValue = queryParameterValue.map((item) => {\n if (item === null || item === undefined) {\n return \"\";\n }\n\n return item;\n });\n }\n if (queryParameter.collectionFormat === \"Multi\" && queryParameterValue.length === 0) {\n continue;\n } else if (\n Array.isArray(queryParameterValue) &&\n (queryParameter.collectionFormat === \"SSV\" || queryParameter.collectionFormat === \"TSV\")\n ) {\n queryParameterValue = queryParameterValue.join(delimiter);\n }\n if (!queryParameter.skipEncoding) {\n if (Array.isArray(queryParameterValue)) {\n queryParameterValue = queryParameterValue.map((item: string) => {\n return encodeURIComponent(item);\n });\n } else {\n queryParameterValue = encodeURIComponent(queryParameterValue);\n }\n }\n\n // Join pipes and CSV *after* encoding, or the server will be upset.\n if (\n Array.isArray(queryParameterValue) &&\n (queryParameter.collectionFormat === \"CSV\" || queryParameter.collectionFormat === \"Pipes\")\n ) {\n queryParameterValue = queryParameterValue.join(delimiter);\n }\n\n result.set(\n queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter),\n queryParameterValue,\n );\n }\n }\n }\n return {\n queryParams: result,\n sequenceParams,\n };\n}\n\nfunction simpleParseQueryParams(queryString: string): Map<string, string | string[] | undefined> {\n const result: Map<string, string | string[] | undefined> = new Map<\n string,\n string | string[] | undefined\n >();\n if (!queryString || queryString[0] !== \"?\") {\n return result;\n }\n\n // remove the leading ?\n queryString = queryString.slice(1);\n const pairs = queryString.split(\"&\");\n\n for (const pair of pairs) {\n const [name, value] = pair.split(\"=\", 2);\n const existingValue = result.get(name);\n if (existingValue) {\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n } else {\n result.set(name, [existingValue, value]);\n }\n } else {\n result.set(name, value);\n }\n }\n\n return result;\n}\n\n/** @internal */\nexport function appendQueryParams(\n url: string,\n queryParams: Map<string, string | string[]>,\n sequenceParams: Set<string>,\n noOverwrite: boolean = false,\n): string {\n if (queryParams.size === 0) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n\n // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which\n // can change their meaning to the server, such as in the case of a SAS signature.\n // To avoid accidentally un-encoding a query param, we parse the key/values ourselves\n const combinedParams = simpleParseQueryParams(parsedUrl.search);\n\n for (const [name, value] of queryParams) {\n const existingValue = combinedParams.get(name);\n if (Array.isArray(existingValue)) {\n if (Array.isArray(value)) {\n existingValue.push(...value);\n const valueSet = new Set(existingValue);\n combinedParams.set(name, Array.from(valueSet));\n } else {\n existingValue.push(value);\n }\n } else if (existingValue) {\n if (Array.isArray(value)) {\n value.unshift(existingValue);\n } else if (sequenceParams.has(name)) {\n combinedParams.set(name, [existingValue, value]);\n }\n if (!noOverwrite) {\n combinedParams.set(name, value);\n }\n } else {\n combinedParams.set(name, value);\n }\n }\n\n const searchPieces: string[] = [];\n for (const [name, value] of combinedParams) {\n if (typeof value === \"string\") {\n searchPieces.push(`${name}=${value}`);\n } else if (Array.isArray(value)) {\n // QUIRK: If we get an array of values, include multiple key/value pairs\n for (const subValue of value) {\n searchPieces.push(`${name}=${subValue}`);\n }\n } else {\n searchPieces.push(`${name}=${value}`);\n }\n }\n\n // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.\n parsedUrl.search = searchPieces.length ? `?${searchPieces.join(\"&\")}` : \"\";\n return parsedUrl.toString();\n}\n"]}
1
+ {"version":3,"file":"urlHelpers.js","sourceRoot":"","sources":["../../src/urlHelpers.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,+DAA+E;AAC/E,+DAAmE;AAEnE,MAAM,8BAA8B,GAA+C;IACjF,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,KAAK,EAAE,OAAO;IACd,GAAG,EAAE,IAAI;IACT,KAAK,EAAE,GAAG;CACX,CAAC;AAEF,SAAgB,aAAa,CAC3B,OAAe,EACf,aAA4B,EAC5B,kBAAsC,EACtC,cAAgD;IAEhD,MAAM,eAAe,GAAG,wBAAwB,CAC9C,aAAa,EACb,kBAAkB,EAClB,cAAc,CACf,CAAC;IAEF,IAAI,cAAc,GAAG,KAAK,CAAC;IAE3B,IAAI,UAAU,GAAG,UAAU,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;IACtD,IAAI,aAAa,CAAC,IAAI,EAAE,CAAC;QACvB,IAAI,IAAI,GAAG,UAAU,CAAC,aAAa,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QAC3D,4DAA4D;QAC5D,4EAA4E;QAC5E,uBAAuB;QACvB,IAAI,aAAa,CAAC,IAAI,KAAK,aAAa,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACjE,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAC3B,CAAC;QACD,2DAA2D;QAC3D,2DAA2D;QAC3D,sBAAsB;QACtB,IAAI,aAAa,CAAC,IAAI,CAAC,EA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AC,aAAa,EAAE,KAAK,CAAC,CAAC,CAAC;YACnD,CAAC;YACD,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,cAAc,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAClC,CAAC;QACH,CAAC;aAAM,CAAC;YACN,cAAc,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;IAED,MAAM,YAAY,GAAa,EAAE,CAAC;IAClC,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,cAAc,EAAE,CAAC;QAC3C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,YAAY,CAAC,IAAI,CAAC,GAAG,IAAI,IAAI,KAAK,EAAE,CAAC,CAAC;QACxC,CAAC;aAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YAChC,wEAAwE;YACxE,KAAK,MAAM,QAAQ,IAAI,KAAK,EAAE,CAAC;gBAC7B,YAAY,CAAC,IAAI,CAAC,GAAG,IAAI,IAAI,QAAQ,EAAE,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;aAAM,CAAC;YACN,YAAY,CAAC,IAAI,CAAC,GAAG,IAAI,IAAI,KAAK,EAAE,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;IAED,6FAA6F;IAC7F,SAAS,CAAC,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3E,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;AAC9B,CAAC;AA1DD,8CA0DC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { OperationArguments, OperationSpec, QueryCollectionFormat } from \"./interfaces.js\";\nimport { getOperationArgumentValueFromParameter } from \"./operationHelpers.js\";\nimport { getPathStringFromParameter } from \"./interfaceHelpers.js\";\n\nconst CollectionFormatToDelimiterMap: { [key in QueryCollectionFormat]: string } = {\n CSV: \",\",\n SSV: \" \",\n Multi: \"Multi\",\n TSV: \"\\t\",\n Pipes: \"|\",\n};\n\nexport function getRequestUrl(\n baseUri: string,\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any },\n): string {\n const urlReplacements = calculateUrlReplacements(\n operationSpec,\n operationArguments,\n fallbackObject,\n );\n\n let isAbsolutePath = false;\n\n let requestUrl = replaceAll(baseUri, urlReplacements);\n if (operationSpec.path) {\n let path = replaceAll(operationSpec.path, urlReplacements);\n // QUIRK: sometimes we get a path component like /{nextLink}\n // which may be a fully formed URL with a leading /. In that case, we should\n // remove the leading /\n if (operationSpec.path === \"/{nextLink}\" && path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n // QUIRK: sometimes we get a path component like {nextLink}\n // which may be a fully formed URL. In that case, we should\n // ignore the baseUri.\n if (isAbsoluteUrl(path)) {\n requestUrl = path;\n isAbsolutePath = true;\n } else {\n requestUrl = appendPath(requestUrl, path);\n }\n }\n\n const { queryParams, sequenceParams } = calculateQueryParameters(\n operationSpec,\n operationArguments,\n fallbackObject,\n );\n /**\n * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`\n * is an absolute path. This ensures that existing query parameter values in `requestUrl`\n * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it\n * is still being built so there is nothing to overwrite.\n */\n requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);\n\n return requestUrl;\n}\n\nfunction replaceAll(input: string, replacements: Map<string, string>): string {\n let result = input;\n for (const [searchValue, replaceValue] of replacements) {\n result = result.split(searchValue).join(replaceValue);\n }\n return result;\n}\n\nfunction calculateUrlReplacements(\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any },\n): Map<string, string> {\n const result = new Map<string, string>();\n if (operationSpec.urlParameters?.length) {\n for (const urlParameter of operationSpec.urlParameters) {\n let urlParameterValue: string = getOperationArgumentValueFromParameter(\n operationArguments,\n urlParameter,\n fallbackObject,\n );\n const parameterPathString = getPathStringFromParameter(urlParameter);\n urlParameterValue = operationSpec.serializer.serialize(\n urlParameter.mapper,\n urlParameterValue,\n parameterPathString,\n );\n if (!urlParameter.skipEncoding) {\n urlParameterValue = encodeURIComponent(urlParameterValue);\n }\n result.set(\n `{${urlParameter.mapper.serializedName || parameterPathString}}`,\n urlParameterValue,\n );\n }\n }\n return result;\n}\n\nfunction isAbsoluteUrl(url: string): boolean {\n return url.includes(\"://\");\n}\n\nfunction appendPath(url: string, pathToAppend?: string): string {\n if (!pathToAppend) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n let newPath = parsedUrl.pathname;\n\n if (!newPath.endsWith(\"/\")) {\n newPath = `${newPath}/`;\n }\n\n if (pathToAppend.startsWith(\"/\")) {\n pathToAppend = pathToAppend.substring(1);\n }\n\n const searchStart = pathToAppend.indexOf(\"?\");\n if (searchStart !== -1) {\n const path = pathToAppend.substring(0, searchStart);\n const search = pathToAppend.substring(searchStart + 1);\n newPath = newPath + path;\n if (search) {\n parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;\n }\n } else {\n newPath = newPath + pathToAppend;\n }\n\n parsedUrl.pathname = newPath;\n\n return parsedUrl.toString();\n}\n\nfunction calculateQueryParameters(\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any },\n): {\n queryParams: Map<string, string | string[]>;\n sequenceParams: Set<string>;\n} {\n const result = new Map<string, string | string[]>();\n const sequenceParams: Set<string> = new Set<string>();\n\n if (operationSpec.queryParameters?.length) {\n for (const queryParameter of operationSpec.queryParameters) {\n if (queryParameter.mapper.type.name === \"Sequence\" && queryParameter.mapper.serializedName) {\n sequenceParams.add(queryParameter.mapper.serializedName);\n }\n let queryParameterValue: string | string[] = getOperationArgumentValueFromParameter(\n operationArguments,\n queryParameter,\n fallbackObject,\n );\n if (\n (queryParameterValue !== undefined && queryParameterValue !== null) ||\n queryParameter.mapper.required\n ) {\n queryParameterValue = operationSpec.serializer.serialize(\n queryParameter.mapper,\n queryParameterValue,\n getPathStringFromParameter(queryParameter),\n );\n\n const delimiter = queryParameter.collectionFormat\n ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]\n : \"\";\n if (Array.isArray(queryParameterValue)) {\n // replace null and undefined\n queryParameterValue = queryParameterValue.map((item) => {\n if (item === null || item === undefined) {\n return \"\";\n }\n\n return item;\n });\n }\n if (queryParameter.collectionFormat === \"Multi\" && queryParameterValue.length === 0) {\n continue;\n } else if (\n Array.isArray(queryParameterValue) &&\n (queryParameter.collectionFormat === \"SSV\" || queryParameter.collectionFormat === \"TSV\")\n ) {\n queryParameterValue = queryParameterValue.join(delimiter);\n }\n if (!queryParameter.skipEncoding) {\n if (Array.isArray(queryParameterValue)) {\n queryParameterValue = queryParameterValue.map((item: string) => {\n return encodeURIComponent(item);\n });\n } else {\n queryParameterValue = encodeURIComponent(queryParameterValue);\n }\n }\n\n // Join pipes and CSV *after* encoding, or the server will be upset.\n if (\n Array.isArray(queryParameterValue) &&\n (queryParameter.collectionFormat === \"CSV\" || queryParameter.collectionFormat === \"Pipes\")\n ) {\n queryParameterValue = queryParameterValue.join(delimiter);\n }\n\n result.set(\n queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter),\n queryParameterValue,\n );\n }\n }\n }\n return {\n queryParams: result,\n sequenceParams,\n };\n}\n\nfunction simpleParseQueryParams(queryString: string): Map<string, string | string[] | undefined> {\n const result: Map<string, string | string[] | undefined> = new Map<\n string,\n string | string[] | undefined\n >();\n if (!queryString || queryString[0] !== \"?\") {\n return result;\n }\n\n // remove the leading ?\n queryString = queryString.slice(1);\n const pairs = queryString.split(\"&\");\n\n for (const pair of pairs) {\n const [name, value] = pair.split(\"=\", 2);\n const existingValue = result.get(name);\n if (existingValue) {\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n } else {\n result.set(name, [existingValue, value]);\n }\n } else {\n result.set(name, value);\n }\n }\n\n return result;\n}\n\n/** @internal */\nexport function appendQueryParams(\n url: string,\n queryParams: Map<string, string | string[]>,\n sequenceParams: Set<string>,\n noOverwrite: boolean = false,\n): string {\n if (queryParams.size === 0) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n\n // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which\n // can change their meaning to the server, such as in the case of a SAS signature.\n // To avoid accidentally un-encoding a query param, we parse the key/values ourselves\n const combinedParams = simpleParseQueryParams(parsedUrl.search);\n\n for (const [name, value] of queryParams) {\n const existingValue = combinedParams.get(name);\n if (Array.isArray(existingValue)) {\n if (Array.isArray(value)) {\n existingValue.push(...value);\n const valueSet = new Set(existingValue);\n combinedParams.set(name, Array.from(valueSet));\n } else {\n existingValue.push(value);\n }\n } else if (existingValue) {\n if (Array.isArray(value)) {\n value.unshift(existingValue);\n } else if (sequenceParams.has(name)) {\n combinedParams.set(name, [existingValue, value]);\n }\n if (!noOverwrite) {\n combinedParams.set(name, value);\n }\n } else {\n combinedParams.set(name, value);\n }\n }\n\n const searchPieces: string[] = [];\n for (const [name, value] of combinedParams) {\n if (typeof value === \"string\") {\n searchPieces.push(`${name}=${value}`);\n } else if (Array.isArray(value)) {\n // QUIRK: If we get an array of values, include multiple key/value pairs\n for (const subValue of value) {\n searchPieces.push(`${name}=${subValue}`);\n }\n } else {\n searchPieces.push(`${name}=${value}`);\n }\n }\n\n // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.\n parsedUrl.search = searchPieces.length ? `?${searchPieces.join(\"&\")}` : \"\";\n return parsedUrl.toString();\n}\n"]}
@@ -15,7 +15,7 @@ function isPrimitiveBody(value, mapperTypeName) {
15
15
  (typeof value === "string" ||
16
16
  typeof value === "number" ||
17
17
  typeof value === "boolean" ||
18
- mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !==
18
+ (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
19
19
  null ||
20
20
  value === undefined ||
21
21
  value === null));
@@ -55,21 +55,14 @@ exports.isValidUuid = isValidUuid;
55
55
  * @internal
56
56
  */
57
57
  function handleNullableResponseAndWrappableBody(responseObject) {
58
- const combinedHeadersAndBody = {
59
- ...responseObject.headers,
60
- ...responseObject.body,
61
- };
58
+ const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
62
59
  if (responseObject.hasNullableType &&
63
60
  Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
64
61
  return responseObject.shouldWrapBody ? { body: null } : null;
65
62
  }
66
63
  else {
67
64
  return responseObject.shouldWrapBody
68
- ? {
69
- ...responseObject.headers,
70
- body: responseObject.body,
71
- }
72
- : combinedHeadersAndBody;
65
+ ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
73
66
  }
74
67
  }
75
68
  /**
@@ -81,35 +74,29 @@ function handleNullableResponseAndWrappableBody(responseObject) {
81
74
  * @internal
82
75
  */
83
76
  function flattenResponse(fullResponse, responseSpec) {
77
+ var _a, _b;
84
78
  const parsedHeaders = fullResponse.parsedHeaders;
85
79
  // head methods never have a body, but we return a boolean set to body property
86
80
  // to indicate presence/absence of the resource
87
81
  if (fullResponse.request.method === "HEAD") {
88
- return {
89
- ...parsedHeaders,
90
- body: fullResponse.parsedBody,
91
- };
82
+ return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
92
83
  }
93
84
  const bodyMapper = responseSpec && responseSpec.bodyMapper;
94
- const isNullable = Boolean(bodyMapper?.nullable);
95
- const expectedBodyTypeName = bodyMapper?.type.name;
85
+ const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
86
+ const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
96
87
  /** If the body is asked for, we look at the expected body type to handle it */
97
88
  if (expectedBodyTypeName === "Stream") {
98
- return {
99
- ...parsedHeaders,
100
- blobBody: fullResponse.blobBody,
101
- readableStreamBody: fullResponse.readableStreamBody,
102
- };
89
+ return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
103
90
  }
104
91
  const modelProperties = (expectedBodyTypeName === "Composite" &&
105
92
  bodyMapper.type.modelProperties) ||
106
93
  {};
107
94
  const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
108
95
  if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
109
- const arrayResponse = fullResponse.parsedBody ?? [];
96
+ const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
110
97
  for (const key of Object.keys(modelProperties)) {
111
98
  if (modelProperties[key].serializedName) {
112
- arrayResponse[key] = fullResponse.parsedBody?.[key];
99
+ arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
113
100
  }
114
101
  }
115
102
  if (parsedHeaders) {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAUlC;;;;;GAKG;AACH,SAAgB,eAAe,CAAC,KAAc,EAAE,cAAuB;IACrE,OAAO,CACL,cAAc,KAAK,WAAW;QAC9B,cAAc,KAAK,YAAY;QAC/B,CAAC,OAAO,KAAK,KAAK,QAAQ;YACxB,OAAO,KAAK,KAAK,QAAQ;YACzB,OAAO,KAAK,KAAK,SAAS;YAC1B,cAAc,EAAE,KAAK,CAAC,iEAAiE,CAAC;gBACtF,IAAI;YACN,KAAK,KAAK,SAAS;YACnB,KAAK,KAAK,IAAI,CAAC,CAClB,CAAC;AACJ,CAAC;AAZD,0CAYC;AAED,MAAM,mBAAmB,GACvB,qKAAqK,CAAC;AAExK;;;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aAAa;YACd,MAAM,CAAC,mBAAmB,CAAC,eAAe,CAAC,CAAC,MAAM,KAAK,CAAC;YACxD,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,aAAa,CAAC;IACpB,CAAC;IAED,OAAO,sCAAsC,CAAC;QAC5C,IAAI,EAAE,YAAY,CAAC,UAAU;QAC7B,OAAO,EAAE,aAAa;QACtB,eAAe,EAAE,UAAU;QAC3B,cAAc,EAAE,eAAe,CAAC,YAAY,CAAC,UAAU,EAAE,oBAAoB,CAAC;KAC/E,CAAC,CAAC;AACL,CAAC;AA/DD,0CA+DC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CompositeMapper, FullOperationResponse, OperationResponseMap } from \"./interfaces.js\";\n\n/**\n * The union of all possible types for a primitive response body.\n * @internal\n */\nexport type BodyPrimitive = number | string | boolean | Date | Uint8Array | undefined | null;\n\n/**\n * A type guard for a primitive response body.\n * @param value - Value to test\n *\n * @internal\n */\nexport function isPrimitiveBody(value: unknown, mapperTypeName?: string): value is BodyPrimitive {\n return (\n mapperTypeName !== \"Composite\" &&\n mapperTypeName !== \"Dictionary\" &&\n (typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !==\n null ||\n value === undefined ||\n value === null)\n );\n}\n\nconst validateISODuration =\n /^(-|\\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;\n\n/**\n * Returns true if the given string is in ISO 8601 format.\n * @param value - The value to be validated for ISO 8601 duration format.\n * @internal\n */\nexport function isDuration(value: string): boolean {\n return validateISODuration.test(value);\n}\n\nconst validUuidRegex =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;\n\n/**\n * Returns true if the provided uuid is valid.\n *\n * @param uuid - The uuid that needs to be validated.\n *\n * @internal\n */\nexport function isValidUuid(uuid: string): boolean {\n return validUuidRegex.test(uuid);\n}\n\n/**\n * Representation of parsed response headers and body coupled with information\n * about how to map them:\n * - whether the response body should be wrapped (typically if its type is primitive).\n * - whether the response is nullable so it can be null if the combination of\n * the headers and the body is empty.\n */\ninterface ResponseObjectWithMetadata {\n /** whether the mapper allows nullable body */\n hasNullableType: boolean;\n /** whether the response's body should be wrapped */\n shouldWrapBody: boolean;\n /** parsed headers of the response */\n headers:\n | {\n [key: string]: unknown;\n }\n | undefined;\n /** parsed body of the response */\n body: any;\n}\n\n/**\n * Maps the response as follows:\n * - wraps the response body if needed (typically if its type is primitive).\n * - returns null if the combination of the headers and the body is empty.\n * - otherwise, returns the combination of the headers and the body.\n *\n * @param responseObject - a representation of the parsed response\n * @returns the response that will be returned to the user which can be null and/or wrapped\n *\n * @internal\n */\nfunction handleNullableResponseAndWrappableBody(\n responseObject: ResponseObjectWithMetadata,\n): unknown | null {\n const combinedHeadersAndBody = {\n ...responseObject.headers,\n ...responseObject.body,\n };\n if (\n responseObject.hasNullableType &&\n Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0\n ) {\n return responseObject.shouldWrapBody ? { body: null } : null;\n } else {\n return responseObject.shouldWrapBody\n ? {\n ...responseObject.headers,\n body: responseObject.body,\n }\n : combinedHeadersAndBody;\n }\n}\n\n/**\n * Take a `FullOperationResponse` and turn it into a flat\n * response object to hand back to the consumer.\n * @param fullResponse - The processed response from the operation request\n * @param responseSpec - The response map from the OperationSpec\n *\n * @internal\n */\nexport function flattenResponse(\n fullResponse: FullOperationResponse,\n responseSpec: OperationResponseMap | undefined,\n): unknown {\n const parsedHeaders = fullResponse.parsedHeaders;\n\n // head methods never have a body, but we return a boolean set to body property\n // to indicate presence/absence of the resource\n if (fullResponse.request.method === \"HEAD\") {\n return {\n ...parsedHeaders,\n body: fullResponse.parsedBody,\n };\n }\n const bodyMapper = responseSpec && responseSpec.bodyMapper;\n const isNullable = Boolean(bodyMapper?.nullable);\n const expectedBodyTypeName = bodyMapper?.type.name;\n\n /** If the body is asked for, we look at the expected body type to handle it */\n if (expectedBodyTypeName === \"Stream\") {\n return {\n ...parsedHeaders,\n blobBody: fullResponse.blobBody,\n readableStreamBody: fullResponse.readableStreamBody,\n };\n }\n\n const modelProperties =\n (expectedBodyTypeName === \"Composite\" &&\n (bodyMapper as CompositeMapper).type.modelProperties) ||\n {};\n const isPageableResponse = Object.keys(modelProperties).some(\n (k) => modelProperties[k].serializedName === \"\",\n );\n if (expectedBodyTypeName === \"Sequence\" || isPageableResponse) {\n const arrayResponse: { [key: string]: unknown } =\n fullResponse.parsedBody ?? ([] as unknown as { [key: string]: unknown });\n\n for (const key of Object.keys(modelProperties)) {\n if (modelProperties[key].serializedName) {\n arrayResponse[key] = fullResponse.parsedBody?.[key];\n }\n }\n\n if (parsedHeaders) {\n for (const key of Object.keys(parsedHeaders)) {\n arrayResponse[key] = parsedHeaders[key];\n }\n }\n return isNullable &&\n !fullResponse.parsedBody &&\n !parsedHeaders &&\n Object.getOwnPropertyNames(modelProperties).length === 0\n ? null\n : arrayResponse;\n }\n\n return handleNullableResponseAndWrappableBody({\n body: fullResponse.parsedBody,\n headers: parsedHeaders,\n hasNullableType: isNullable,\n shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),\n });\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAUlC;;;;;GAKG;AACH,SAAgB,eAAe,CAAC,KAAc,EAAE,cAAuB;IACrE,OAAO,CACL,cAAc,KAAK,WAAW;QAC9B,cAAc,KAAK,YAAY;QAC/B,CAAC,OAAO,KAAK,KAAK,QAAQ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C;YACtD,CAAC;QACH,CAAC;QAED,IAAI,aAAa,EAAE,CAAC;YAClB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;gBAC7C,aAAa,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;YAC1C,CAAC;QACH,CAAC;QACD,OAAO,UAAU;YACf,CAAC,YAAY,CAAC,UAAU;YACxB,CAAC,aAAa;YACd,MAAM,CAAC,mBAAmB,CAAC,eAAe,CAAC,CAAC,MAAM,KAAK,CAAC;YACxD,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,aAAa,CAAC;IACpB,CAAC;IAED,OAAO,sCAAsC,CAAC;QAC5C,IAAI,EAAE,YAAY,CAAC,UAAU;QAC7B,OAAO,EAAE,aAAa;QACtB,eAAe,EAAE,UAAU;QAC3B,cAAc,EAAE,eAAe,CAAC,YAAY,CAAC,UAAU,EAAE,oBAAoB,CAAC;KAC/E,CAAC,CAAC;AACL,CAAC;AA/DD,0CA+DC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CompositeMapper, FullOperationResponse, OperationResponseMap } from \"./interfaces.js\";\n\n/**\n * The union of all possible types for a primitive response body.\n * @internal\n */\nexport type BodyPrimitive = number | string | boolean | Date | Uint8Array | undefined | null;\n\n/**\n * A type guard for a primitive response body.\n * @param value - Value to test\n *\n * @internal\n */\nexport function isPrimitiveBody(value: unknown, mapperTypeName?: string): value is BodyPrimitive {\n return (\n mapperTypeName !== \"Composite\" &&\n mapperTypeName !== \"Dictionary\" &&\n (typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !==\n null ||\n value === undefined ||\n value === null)\n );\n}\n\nconst validateISODuration =\n /^(-|\\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;\n\n/**\n * Returns true if the given string is in ISO 8601 format.\n * @param value - The value to be validated for ISO 8601 duration format.\n * @internal\n */\nexport function isDuration(value: string): boolean {\n return validateISODuration.test(value);\n}\n\nconst validUuidRegex =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;\n\n/**\n * Returns true if the provided uuid is valid.\n *\n * @param uuid - The uuid that needs to be validated.\n *\n * @internal\n */\nexport function isValidUuid(uuid: string): boolean {\n return validUuidRegex.test(uuid);\n}\n\n/**\n * Representation of parsed response headers and body coupled with information\n * about how to map them:\n * - whether the response body should be wrapped (typically if its type is primitive).\n * - whether the response is nullable so it can be null if the combination of\n * the headers and the body is empty.\n */\ninterface ResponseObjectWithMetadata {\n /** whether the mapper allows nullable body */\n hasNullableType: boolean;\n /** whether the response's body should be wrapped */\n shouldWrapBody: boolean;\n /** parsed headers of the response */\n headers:\n | {\n [key: string]: unknown;\n }\n | undefined;\n /** parsed body of the response */\n body: any;\n}\n\n/**\n * Maps the response as follows:\n * - wraps the response body if needed (typically if its type is primitive).\n * - returns null if the combination of the headers and the body is empty.\n * - otherwise, returns the combination of the headers and the body.\n *\n * @param responseObject - a representation of the parsed response\n * @returns the response that will be returned to the user which can be null and/or wrapped\n *\n * @internal\n */\nfunction handleNullableResponseAndWrappableBody(\n responseObject: ResponseObjectWithMetadata,\n): unknown | null {\n const combinedHeadersAndBody = {\n ...responseObject.headers,\n ...responseObject.body,\n };\n if (\n responseObject.hasNullableType &&\n Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0\n ) {\n return responseObject.shouldWrapBody ? { body: null } : null;\n } else {\n return responseObject.shouldWrapBody\n ? {\n ...responseObject.headers,\n body: responseObject.body,\n }\n : combinedHeadersAndBody;\n }\n}\n\n/**\n * Take a `FullOperationResponse` and turn it into a flat\n * response object to hand back to the consumer.\n * @param fullResponse - The processed response from the operation request\n * @param responseSpec - The response map from the OperationSpec\n *\n * @internal\n */\nexport function flattenResponse(\n fullResponse: FullOperationResponse,\n responseSpec: OperationResponseMap | undefined,\n): unknown {\n const parsedHeaders = fullResponse.parsedHeaders;\n\n // head methods never have a body, but we return a boolean set to body property\n // to indicate presence/absence of the resource\n if (fullResponse.request.method === \"HEAD\") {\n return {\n ...parsedHeaders,\n body: fullResponse.parsedBody,\n };\n }\n const bodyMapper = responseSpec && responseSpec.bodyMapper;\n const isNullable = Boolean(bodyMapper?.nullable);\n const expectedBodyTypeName = bodyMapper?.type.name;\n\n /** If the body is asked for, we look at the expected body type to handle it */\n if (expectedBodyTypeName === \"Stream\") {\n return {\n ...parsedHeaders,\n blobBody: fullResponse.blobBody,\n readableStreamBody: fullResponse.readableStreamBody,\n };\n }\n\n const modelProperties =\n (expectedBodyTypeName === \"Composite\" &&\n (bodyMapper as CompositeMapper).type.modelProperties) ||\n {};\n const isPageableResponse = Object.keys(modelProperties).some(\n (k) => modelProperties[k].serializedName === \"\",\n );\n if (expectedBodyTypeName === \"Sequence\" || isPageableResponse) {\n const arrayResponse: { [key: string]: unknown } =\n fullResponse.parsedBody ?? ([] as unknown as { [key: string]: unknown });\n\n for (const key of Object.keys(modelProperties)) {\n if (modelProperties[key].serializedName) {\n arrayResponse[key] = fullResponse.parsedBody?.[key];\n }\n }\n\n if (parsedHeaders) {\n for (const key of Object.keys(parsedHeaders)) {\n arrayResponse[key] = parsedHeaders[key];\n }\n }\n return isNullable &&\n !fullResponse.parsedBody &&\n !parsedHeaders &&\n Object.getOwnPropertyNames(modelProperties).length === 0\n ? null\n : arrayResponse;\n }\n\n return handleNullableResponseAndWrappableBody({\n body: fullResponse.parsedBody,\n headers: parsedHeaders,\n hasNullableType: isNullable,\n shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),\n });\n}\n"]}
@@ -14,7 +14,7 @@ export function parseCAEChallenge(challenges) {
14
14
  const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
15
15
  const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
16
16
  // Key-value pairs to plain object:
17
- return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});
17
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
18
18
  });
19
19
  }
20
20
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"authorizeRequestOnClaimChallenge.js","sourceRoot":"","sources":["../../src/authorizeRequestOnClaimChallenge.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,MAAM,IAAI,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAkB;IAClD,MAAM,gBAAgB,GAAG,KAAK,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IACtF,OAAO,gBAAgB,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE;QACxC,MAAM,cAAc,GAAG,GAAG,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;QAC7E,MAAM,aAAa,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CACpD,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC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,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,kBAAkB,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;IACvF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AuthorizeRequestOnChallengeOptions } from \"@azure/core-rest-pipeline\";\nimport { logger as coreClientLogger } from \"./log.js\";\nimport { decodeStringToString } from \"./base64.js\";\n\n/**\n * Converts: `Bearer a=\"b\", c=\"d\", Bearer d=\"e\", f=\"g\"`.\n * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.\n *\n * @internal\n */\nexport function parseCAEChallenge(challenges: string): any[] {\n const bearerChallenges = `, ${challenges.trim()}`.split(\", Bearer \").filter((x) => x);\n return bearerChallenges.map((challenge) => {\n const challengeParts = `${challenge.trim()}, `.split('\", ').filter((x) => x);\n const keyValuePairs = challengeParts.map((keyValue) =>\n (([key, value]) => ({ [key]: value }))(keyValue.trim().split('=\"')),\n );\n // Key-value pairs to plain object:\n return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});\n });\n}\n\n/**\n * CAE Challenge structure\n */\nexport interface CAEChallenge {\n scope: string;\n claims: string;\n}\n\n/**\n * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:\n * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).\n *\n * Call the `bearerTokenAuthenticationPolicy` with the following options:\n *\n * ```ts\n * import { bearerTokenAuthenticationPolicy } from \"@azure/core-rest-pipeline\";\n * import { authorizeRequestOnClaimChallenge } from \"@azure/core-client\";\n *\n * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({\n * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge\n * });\n * ```\n *\n * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.\n * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.\n *\n * Example challenge with claims:\n *\n * ```\n * Bearer authorization_uri=\"https://login.windows-ppe.net/\", error=\"invalid_token\",\n * error_description=\"User session has been revoked\",\n * claims=\"eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0=\"\n * ```\n */\nexport async function authorizeRequestOnClaimChallenge(\n onChallengeOptions: AuthorizeRequestOnChallengeOptions,\n): Promise<boolean> {\n const { scopes, response } = onChallengeOptions;\n const logger = onChallengeOptions.logger || coreClientLogger;\n\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (!challenge) {\n logger.info(\n `The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`,\n );\n return false;\n }\n const challenges: CAEChallenge[] = parseCAEChallenge(challenge) || [];\n\n const parsedChallenge = challenges.find((x) => x.claims);\n if (!parsedChallenge) {\n logger.info(\n `The WWW-Authenticate header was missing the necessary \"claims\" to perform the Continuous Access Evaluation authentication flow.`,\n );\n return false;\n }\n\n const accessToken = await onChallengeOptions.getAccessToken(\n parsedChallenge.scope ? [parsedChallenge.scope] : scopes,\n {\n claims: decodeStringToString(parsedChallenge.claims),\n },\n );\n\n if (!accessToken) {\n return false;\n }\n\n onChallengeOptions.request.headers.set(\"Authorization\", `Bearer ${accessToken.token}`);\n return true;\n}\n"]}
1
+ {"version":3,"file":"authorizeRequestOnClaimChallenge.js","sourceRoot":"","sources":["../../src/authorizeRequestOnClaimChallenge.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,MAAM,IAAI,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD;;;;;GAKG;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M,CAAC,IAAI,CACT,kHAAkH,CACnH,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,UAAU,GAAmB,iBAAiB,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;IAEtE,MAAM,eAAe,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IACzD,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,CAAC,IAAI,CACT,iIAAiI,CAClI,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,kBAAkB,CAAC,cAAc,CACzD,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EACxD;QACE,MAAM,EAAE,oBAAoB,CAAC,eAAe,CAAC,MAAM,CAAC;KACrD,CACF,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,kBAAkB,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;IACvF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AuthorizeRequestOnChallengeOptions } from \"@azure/core-rest-pipeline\";\nimport { logger as coreClientLogger } from \"./log.js\";\nimport { decodeStringToString } from \"./base64.js\";\n\n/**\n * Converts: `Bearer a=\"b\", c=\"d\", Bearer d=\"e\", f=\"g\"`.\n * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.\n *\n * @internal\n */\nexport function parseCAEChallenge(challenges: string): any[] {\n const bearerChallenges = `, ${challenges.trim()}`.split(\", Bearer \").filter((x) => x);\n return bearerChallenges.map((challenge) => {\n const challengeParts = `${challenge.trim()}, `.split('\", ').filter((x) => x);\n const keyValuePairs = challengeParts.map((keyValue) =>\n (([key, value]) => ({ [key]: value }))(keyValue.trim().split('=\"')),\n );\n // Key-value pairs to plain object:\n return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});\n });\n}\n\n/**\n * CAE Challenge structure\n */\nexport interface CAEChallenge {\n scope: string;\n claims: string;\n}\n\n/**\n * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:\n * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).\n *\n * Call the `bearerTokenAuthenticationPolicy` with the following options:\n *\n * ```ts\n * import { bearerTokenAuthenticationPolicy } from \"@azure/core-rest-pipeline\";\n * import { authorizeRequestOnClaimChallenge } from \"@azure/core-client\";\n *\n * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({\n * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge\n * });\n * ```\n *\n * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.\n * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.\n *\n * Example challenge with claims:\n *\n * ```\n * Bearer authorization_uri=\"https://login.windows-ppe.net/\", error=\"invalid_token\",\n * error_description=\"User session has been revoked\",\n * claims=\"eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0=\"\n * ```\n */\nexport async function authorizeRequestOnClaimChallenge(\n onChallengeOptions: AuthorizeRequestOnChallengeOptions,\n): Promise<boolean> {\n const { scopes, response } = onChallengeOptions;\n const logger = onChallengeOptions.logger || coreClientLogger;\n\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (!challenge) {\n logger.info(\n `The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`,\n );\n return false;\n }\n const challenges: CAEChallenge[] = parseCAEChallenge(challenge) || [];\n\n const parsedChallenge = challenges.find((x) => x.claims);\n if (!parsedChallenge) {\n logger.info(\n `The WWW-Authenticate header was missing the necessary \"claims\" to perform the Continuous Access Evaluation authentication flow.`,\n );\n return false;\n }\n\n const accessToken = await onChallengeOptions.getAccessToken(\n parsedChallenge.scope ? [parsedChallenge.scope] : scopes,\n {\n claims: decodeStringToString(parsedChallenge.claims),\n },\n );\n\n if (!accessToken) {\n return false;\n }\n\n onChallengeOptions.request.headers.set(\"Authorization\", `Bearer ${accessToken.token}`);\n return true;\n}\n"]}
@@ -27,10 +27,7 @@ export const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
27
27
  const challengeInfo = parseChallenge(challenge);
28
28
  const challengeScopes = buildScopes(challengeOptions, challengeInfo);
29
29
  const tenantId = extractTenantId(challengeInfo);
30
- const accessToken = await challengeOptions.getAccessToken(challengeScopes, {
31
- ...requestOptions,
32
- tenantId,
33
- });
30
+ const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
34
31
  if (!accessToken) {
35
32
  return false;
36
33
  }
@@ -85,7 +82,7 @@ function parseChallenge(challenge) {
85
82
  const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
86
83
  const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
87
84
  // Key-value pairs to plain object:
88
- return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});
85
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
89
86
  }
90
87
  /**
91
88
  * Extracts the options form a Pipeline Request for later re-use
@@ -1 +1 @@
1
- {"version":3,"file":"authorizeRequestOnTenantChallenge.js","sourceRoot":"","sources":["../../src/authorizeRequestOnTenantChallenge.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAUlC;;GAEG;AACH,MAAM,SAAS,GAAG;IAChB,YAAY,EAAE,WAAW;IACzB;;OAEG;IACH,eA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AAG,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,EAAE,EAAe,CAAC,CAAC;AAC3E,CAAC;AAED;;GAEG;AACH,SAAS,gBAAgB,CAAC,OAAwB;IAChD,OAAO;QACL,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,cAAc,EAAE;YACd,OAAO,EAAE,OAAO,CAAC,OAAO;SACzB;QACD,cAAc,EAAE,OAAO,CAAC,cAAc;KACvC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AuthorizeRequestOnChallengeOptions,\n PipelineRequest,\n PipelineResponse,\n} from \"@azure/core-rest-pipeline\";\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * A set of constants used internally when processing requests.\n */\nconst Constants = {\n DefaultScope: \"/.default\",\n /**\n * Defines constants for use with HTTP headers.\n */\n HeaderConstants: {\n /**\n * The Authorization header.\n */\n AUTHORIZATION: \"authorization\",\n },\n};\n\n/**\n * Defines a callback to handle auth challenge for Storage APIs.\n * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge\n * Handling has specific features for storage that departs to the general AAD challenge docs.\n **/\nexport const authorizeRequestOnTenantChallenge: (\n challengeOptions: AuthorizeRequestOnChallengeOptions,\n) => Promise<boolean> = async (challengeOptions) => {\n const requestOptions = requestToOptions(challengeOptions.request);\n const challenge = getChallenge(challengeOptions.response);\n if (challenge) {\n const challengeInfo: Challenge = parseChallenge(challenge);\n const challengeScopes = buildScopes(challengeOptions, challengeInfo);\n const tenantId = extractTenantId(challengeInfo);\n const accessToken = await challengeOptions.getAccessToken(challengeScopes, {\n ...requestOptions,\n tenantId,\n });\n\n if (!accessToken) {\n return false;\n }\n\n challengeOptions.request.headers.set(\n Constants.HeaderConstants.AUTHORIZATION,\n `Bearer ${accessToken.token}`,\n );\n return true;\n }\n return false;\n};\n\n/**\n * Extracts the tenant id from the challenge information\n * The tenant id is contained in the authorization_uri as the first\n * path part.\n */\nfunction extractTenantId(challengeInfo: Challenge): string {\n const parsedAuthUri = new URL(challengeInfo.authorization_uri);\n const pathSegments = parsedAuthUri.pathname.split(\"/\");\n const tenantId = pathSegments[1];\n\n return tenantId;\n}\n\n/**\n * Builds the authentication scopes based on the information that comes in the\n * challenge information. Scopes url is present in the resource_id, if it is empty\n * we keep using the original scopes.\n */\nfunction buildScopes(\n challengeOptions: AuthorizeRequestOnChallengeOptions,\n challengeInfo: Challenge,\n): string[] {\n if (!challengeInfo.resource_id) {\n return challengeOptions.scopes;\n }\n\n const challengeScopes = new URL(challengeInfo.resource_id);\n challengeScopes.pathname = Constants.DefaultScope;\n return [challengeScopes.toString()];\n}\n\n/**\n * We will retrieve the challenge only if the response status code was 401,\n * and if the response contained the header \"WWW-Authenticate\" with a non-empty value.\n */\nfunction getChallenge(response: PipelineResponse): string | undefined {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}\n\n/**\n * Challenge structure\n */\ninterface Challenge {\n authorization_uri: string;\n resource_id?: string;\n}\n\n/**\n * Converts: `Bearer a=\"b\" c=\"d\"`.\n * Into: `[ { a: 'b', c: 'd' }]`.\n *\n * @internal\n */\nfunction parseChallenge(challenge: string): Challenge {\n const bearerChallenge = challenge.slice(\"Bearer \".length);\n const challengeParts = `${bearerChallenge.trim()} `.split(\" \").filter((x) => x);\n const keyValuePairs = challengeParts.map((keyValue) =>\n (([key, value]) => ({ [key]: value }))(keyValue.trim().split(\"=\")),\n );\n // Key-value pairs to plain object:\n return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {} as Challenge);\n}\n\n/**\n * Extracts the options form a Pipeline Request for later re-use\n */\nfunction requestToOptions(request: PipelineRequest): GetTokenOptions {\n return {\n abortSignal: request.abortSignal,\n requestOptions: {\n timeout: request.timeout,\n },\n tracingOptions: request.tracingOptions,\n };\n}\n"]}
1
+ {"version":3,"file":"authorizeRequestOnTenantCh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,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CACnE,CAAC;IACF,mCAAmC;IACnC,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,iCAAM,CAAC,GAAK,CAAC,EAAG,EAAE,EAAe,CAAC,CAAC;AAC3E,CAAC;AAED;;GAEG;AACH,SAAS,gBAAgB,CAAC,OAAwB;IAChD,OAAO;QACL,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,cAAc,EAAE;YACd,OAAO,EAAE,OAAO,CAAC,OAAO;SACzB;QACD,cAAc,EAAE,OAAO,CAAC,cAAc;KACvC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AuthorizeRequestOnChallengeOptions,\n PipelineRequest,\n PipelineResponse,\n} from \"@azure/core-rest-pipeline\";\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * A set of constants used internally when processing requests.\n */\nconst Constants = {\n DefaultScope: \"/.default\",\n /**\n * Defines constants for use with HTTP headers.\n */\n HeaderConstants: {\n /**\n * The Authorization header.\n */\n AUTHORIZATION: \"authorization\",\n },\n};\n\n/**\n * Defines a callback to handle auth challenge for Storage APIs.\n * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge\n * Handling has specific features for storage that departs to the general AAD challenge docs.\n **/\nexport const authorizeRequestOnTenantChallenge: (\n challengeOptions: AuthorizeRequestOnChallengeOptions,\n) => Promise<boolean> = async (challengeOptions) => {\n const requestOptions = requestToOptions(challengeOptions.request);\n const challenge = getChallenge(challengeOptions.response);\n if (challenge) {\n const challengeInfo: Challenge = parseChallenge(challenge);\n const challengeScopes = buildScopes(challengeOptions, challengeInfo);\n const tenantId = extractTenantId(challengeInfo);\n const accessToken = await challengeOptions.getAccessToken(challengeScopes, {\n ...requestOptions,\n tenantId,\n });\n\n if (!accessToken) {\n return false;\n }\n\n challengeOptions.request.headers.set(\n Constants.HeaderConstants.AUTHORIZATION,\n `Bearer ${accessToken.token}`,\n );\n return true;\n }\n return false;\n};\n\n/**\n * Extracts the tenant id from the challenge information\n * The tenant id is contained in the authorization_uri as the first\n * path part.\n */\nfunction extractTenantId(challengeInfo: Challenge): string {\n const parsedAuthUri = new URL(challengeInfo.authorization_uri);\n const pathSegments = parsedAuthUri.pathname.split(\"/\");\n const tenantId = pathSegments[1];\n\n return tenantId;\n}\n\n/**\n * Builds the authentication scopes based on the information that comes in the\n * challenge information. Scopes url is present in the resource_id, if it is empty\n * we keep using the original scopes.\n */\nfunction buildScopes(\n challengeOptions: AuthorizeRequestOnChallengeOptions,\n challengeInfo: Challenge,\n): string[] {\n if (!challengeInfo.resource_id) {\n return challengeOptions.scopes;\n }\n\n const challengeScopes = new URL(challengeInfo.resource_id);\n challengeScopes.pathname = Constants.DefaultScope;\n return [challengeScopes.toString()];\n}\n\n/**\n * We will retrieve the challenge only if the response status code was 401,\n * and if the response contained the header \"WWW-Authenticate\" with a non-empty value.\n */\nfunction getChallenge(response: PipelineResponse): string | undefined {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}\n\n/**\n * Challenge structure\n */\ninterface Challenge {\n authorization_uri: string;\n resource_id?: string;\n}\n\n/**\n * Converts: `Bearer a=\"b\" c=\"d\"`.\n * Into: `[ { a: 'b', c: 'd' }]`.\n *\n * @internal\n */\nfunction parseChallenge(challenge: string): Challenge {\n const bearerChallenge = challenge.slice(\"Bearer \".length);\n const challengeParts = `${bearerChallenge.trim()} `.split(\" \").filter((x) => x);\n const keyValuePairs = challengeParts.map((keyValue) =>\n (([key, value]) => ({ [key]: value }))(keyValue.trim().split(\"=\")),\n );\n // Key-value pairs to plain object:\n return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {} as Challenge);\n}\n\n/**\n * Extracts the options form a Pipeline Request for later re-use\n */\nfunction requestToOptions(request: PipelineRequest): GetTokenOptions {\n return {\n abortSignal: request.abortSignal,\n requestOptions: {\n timeout: request.timeout,\n },\n tracingOptions: request.tracingOptions,\n };\n}\n"]}
@@ -14,15 +14,16 @@ export const deserializationPolicyName = "deserializationPolicy";
14
14
  * This policy handles parsing out responses according to OperationSpecs on the request.
15
15
  */
16
16
  export function deserializationPolicy(options = {}) {
17
- const jsonContentTypes = options.expectedContentTypes?.json ?? defaultJsonContentTypes;
18
- const xmlContentTypes = options.expectedContentTypes?.xml ?? defaultXmlContentTypes;
17
+ var _a, _b, _c, _d, _e, _f, _g;
18
+ const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
19
+ const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
19
20
  const parseXML = options.parseXML;
20
21
  const serializerOptions = options.serializerOptions;
21
22
  const updatedOptions = {
22
23
  xml: {
23
- rootName: serializerOptions?.xml.rootName ?? "",
24
- includeRoot: serializerOptions?.xml.includeRoot ?? false,
25
- xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY,
24
+ rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
25
+ includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
26
+ xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : XML_CHARKEY,
26
27
  },
27
28
  };
28
29
  return {
@@ -37,13 +38,13 @@ function getOperationResponseMap(parsedResponse) {
37
38
  let result;
38
39
  const request = parsedResponse.request;
39
40
  const operationInfo = getOperationRequestInfo(request);
40
- const operationSpec = operationInfo?.operationSpec;
41
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
41
42
  if (operationSpec) {
42
- if (!operationInfo?.operationResponseGetter) {
43
+ if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
43
44
  result = operationSpec.responses[parsedResponse.status];
44
45
  }
45
46
  else {
46
- result = operationInfo?.operationResponseGetter(operationSpec, parsedResponse);
47
+ result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
47
48
  }
48
49
  }
49
50
  return result;
@@ -51,7 +52,7 @@ function getOperationResponseMap(parsedResponse) {
51
52
  function shouldDeserializeResponse(parsedResponse) {
52
53
  const request = parsedResponse.request;
53
54
  const operationInfo = getOperationRequestInfo(request);
54
- const shouldDeserialize = operationInfo?.shouldDeserialize;
55
+ const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
55
56
  let result;
56
57
  if (shouldDeserialize === undefined) {
57
58
  result = true;
@@ -70,7 +71,7 @@ async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, respon
70
71
  return parsedResponse;
71
72
  }
72
73
  const operationInfo = getOperationRequestInfo(parsedResponse.request);
73
- const operationSpec = operationInfo?.operationSpec;
74
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
74
75
  if (!operationSpec || !operationSpec.responses) {
75
76
  return parsedResponse;
76
77
  }
@@ -121,6 +122,7 @@ function isOperationSpecEmpty(operationSpec) {
121
122
  (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
122
123
  }
123
124
  function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
125
+ var _a;
124
126
  const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
125
127
  const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
126
128
  ? isSuccessByStatus
@@ -135,8 +137,8 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec, option
135
137
  return { error: null, shouldReturnResponse: false };
136
138
  }
137
139
  }
138
- const errorResponseSpec = responseSpec ?? operationSpec.responses.default;
139
- const initialErrorMessage = parsedResponse.request.streamResponseStatusCodes?.has(parsedResponse.status)
140
+ const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
141
+ const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
140
142
  ? `Unexpected status code: ${parsedResponse.status}`
141
143
  : parsedResponse.bodyAsText;
142
144
  const error = new RestError(initialErrorMessage, {
@@ -189,7 +191,8 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec, option
189
191
  return { error, shouldReturnResponse: false };
190
192
  }
191
193
  async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
192
- if (!operationResponse.request.streamResponseStatusCodes?.has(operationResponse.status) &&
194
+ var _a;
195
+ if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
193
196
  operationResponse.bodyAsText) {
194
197
  const text = operationResponse.bodyAsText;
195
198
  const contentType = operationResponse.headers.get("Content-Type") || "";