@typespec/ts-http-runtime 1.0.0-alpha.20231110.2 → 1.0.0-alpha.20231120.4
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.
- package/dist/index.js +500 -250
- package/dist/index.js.map +1 -1
- package/dist-esm/src/client/sendRequest.js +1 -1
- package/dist-esm/src/client/sendRequest.js.map +1 -1
- package/dist-esm/src/createPipelineFromOptions.js +5 -0
- package/dist-esm/src/createPipelineFromOptions.js.map +1 -1
- package/dist-esm/src/fetchHttpClient.js +1 -14
- package/dist-esm/src/fetchHttpClient.js.map +1 -1
- package/dist-esm/src/index.js +2 -0
- package/dist-esm/src/index.js.map +1 -1
- package/dist-esm/src/interfaces.js.map +1 -1
- package/dist-esm/src/pipelineRequest.js +1 -0
- package/dist-esm/src/pipelineRequest.js.map +1 -1
- package/dist-esm/src/policies/formDataPolicy.js +34 -32
- package/dist-esm/src/policies/formDataPolicy.js.map +1 -1
- package/dist-esm/src/policies/multipartPolicy.js +112 -0
- package/dist-esm/src/policies/multipartPolicy.js.map +1 -0
- package/dist-esm/src/util/file.js +51 -0
- package/dist-esm/src/util/file.js.map +1 -0
- package/dist-esm/src/util/stream.browser.js +64 -0
- package/dist-esm/src/util/stream.browser.js.map +1 -0
- package/dist-esm/src/util/stream.js +81 -0
- package/dist-esm/src/util/stream.js.map +1 -0
- package/dist-esm/src/util/typeGuards.js +14 -0
- package/dist-esm/src/util/typeGuards.js.map +1 -1
- package/dist-esm/src/xhrHttpClient.js +2 -12
- package/dist-esm/src/xhrHttpClient.js.map +1 -1
- package/package.json +3 -4
- package/types/ts-http-runtime.d.ts +116 -2
- package/dist-esm/src/client/helpers/isReadableStream.browser.js +0 -12
- package/dist-esm/src/client/helpers/isReadableStream.browser.js.map +0 -1
- package/dist-esm/src/client/helpers/isReadableStream.js +0 -10
- package/dist-esm/src/client/helpers/isReadableStream.js.map +0 -1
- package/dist-esm/src/policies/formDataPolicy.browser.js +0 -43
- package/dist-esm/src/policies/formDataPolicy.browser.js.map +0 -1
|
@@ -4,7 +4,7 @@ import { RestError } from "../restError";
|
|
|
4
4
|
import { createHttpHeaders } from "../httpHeaders";
|
|
5
5
|
import { createPipelineRequest } from "../pipelineRequest";
|
|
6
6
|
import { getCachedDefaultHttpsClient } from "./clientHelpers";
|
|
7
|
-
import { isReadableStream } from "
|
|
7
|
+
import { isReadableStream } from "../util/typeGuards";
|
|
8
8
|
import { binaryArrayToString } from "./helpers/getBinaryBody";
|
|
9
9
|
/**
|
|
10
10
|
* Helper function to send request used by the client
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sendRequest.js","sourceRoot":"","sources":["../../../src/client/sendRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAWlC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,MAAmB,EACnB,GAAW,EACX,QAAkB,EAClB,UAA6B,EAAE,EAC/B,gBAA6B;IAE7B,MAAM,UAAU,GAAG,gBAAgB,aAAhB,gBAAgB,cAAhB,gBAAgB,GAAI,2BAA2B,EAAE,CAAC;IACrE,MAAM,OAAO,GAAG,oBAAoB,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAE3D,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAEjE,MAAM,UAAU,GAAmB,QAAQ,CAAC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AAkB,EAAE;YACpC,MAAM,gBAAgB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;SACzC;QAED,gEAAgE;QAChE,cAAc;QACd,OAAO,MAAM,CAAC,WAAW,CAAC,CAAC;KAC5B;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,QAA0B,EAAE,GAAQ;;IAC5D,MAAM,GAAG,GAAG,UAAU,GAAG,gDAAgD,QAAQ,CAAC,UAAU,GAAG,CAAC;IAChG,MAAM,OAAO,GAAG,MAAA,GAAG,CAAC,IAAI,mCAAI,SAAS,CAAC,WAAW,CAAC;IAClD,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE;QACxB,IAAI,EAAE,OAAO;QACb,UAAU,EAAE,QAAQ,CAAC,MAAM;QAC3B,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n FormDataMap,\n HttpClient,\n HttpMethods,\n PipelineRequest,\n PipelineResponse,\n RawHttpHeaders,\n RequestBodyType,\n} from \"../interfaces\";\nimport { RestError } from \"../restError\";\nimport { Pipeline } from \"../pipeline\";\nimport { createHttpHeaders } from \"../httpHeaders\";\nimport { createPipelineRequest } from \"../pipelineRequest\";\nimport { getCachedDefaultHttpsClient } from \"./clientHelpers\";\nimport { isReadableStream } from \"./helpers/isReadableStream\";\nimport { HttpResponse, RequestParameters } from \"./common\";\nimport { binaryArrayToString } from \"./helpers/getBinaryBody\";\n\n/**\n * Helper function to send request used by the client\n * @param method - method to use to send the request\n * @param url - url to send the request to\n * @param pipeline - pipeline with the policies to run when sending the request\n * @param options - request options\n * @param customHttpClient - a custom HttpClient to use when making the request\n * @returns returns and HttpResponse\n */\nexport async function sendRequest(\n method: HttpMethods,\n url: string,\n pipeline: Pipeline,\n options: RequestParameters = {},\n customHttpClient?: HttpClient\n): Promise<HttpResponse> {\n const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();\n const request = buildPipelineRequest(method, url, options);\n\n const response = await pipeline.sendRequest(httpClient, request);\n\n const rawHeaders: RawHttpHeaders = response.headers.toJSON();\n\n const parsedBody: RequestBodyType | undefined = getResponseBody(response);\n\n if (options?.onResponse) {\n options.onResponse({ ...response, request, rawHeaders, parsedBody });\n }\n\n return {\n request,\n headers: rawHeaders,\n status: `${response.status}`,\n body: parsedBody,\n };\n}\n\n/**\n * Helper function to send request used by the client\n * @param method - method to use to send the request\n * @param url - url to send the request to\n * @param pipeline - pipeline with the policies to run when sending the request\n * @param options - request options\n * @param customHttpClient - a custom HttpClient to use when making the request\n * @returns returns and HttpResponse\n */\nexport async function sendRequestAsStream<\n TResponse extends HttpResponse & {\n body: NodeJS.ReadableStream | ReadableStream<Uint8Array> | undefined;\n }\n>(\n method: HttpMethods,\n url: string,\n pipeline: Pipeline,\n options: RequestParameters = {},\n customHttpClient?: HttpClient\n): Promise<TResponse> {\n const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();\n const request = buildPipelineRequest(method, url, { ...options, responseAsStream: true });\n const response = await pipeline.sendRequest(httpClient, request);\n const rawHeaders: RawHttpHeaders = response.headers.toJSON();\n\n const parsedBody = response.browserStreamBody ?? response.readableStreamBody;\n\n return {\n request,\n headers: rawHeaders,\n status: `${response.status}`,\n body: parsedBody,\n } as TResponse;\n}\n\n/**\n * Function to determine the content-type of a body\n * this is used if an explicit content-type is not provided\n * @param body - body in the request\n * @returns returns the content-type\n */\nfunction getContentType(body: any): string {\n if (ArrayBuffer.isView(body)) {\n return \"application/octet-stream\";\n }\n\n // By default return json\n return \"application/json; charset=UTF-8\";\n}\n\nexport interface InternalRequestParameters extends RequestParameters {\n responseAsStream?: boolean;\n}\n\nfunction buildPipelineRequest(\n method: HttpMethods,\n url: string,\n options: InternalRequestParameters = {}\n): PipelineRequest {\n const { body, formData } = getRequestBody(options.body, options.contentType);\n const hasContent = body !== undefined || formData !== undefined;\n\n const headers = createHttpHeaders({\n ...(options.headers ? options.headers : {}),\n accept: options.accept ?? \"application/json\",\n ...(hasContent && {\n \"content-type\": options.contentType ?? getContentType(options.body),\n }),\n });\n\n return createPipelineRequest({\n url,\n method,\n body,\n formData,\n headers,\n allowInsecureConnection: options.allowInsecureConnection,\n tracingOptions: options.tracingOptions,\n abortSignal: options.abortSignal,\n onUploadProgress: options.onUploadProgress,\n onDownloadProgress: options.onDownloadProgress,\n timeout: options.timeout,\n enableBrowserStreams: true,\n streamResponseStatusCodes: options.responseAsStream\n ? new Set([Number.POSITIVE_INFINITY])\n : undefined,\n });\n}\n\ninterface RequestBody {\n body?: RequestBodyType;\n formData?: FormDataMap;\n}\n\n/**\n * Prepares the body before sending the request\n */\nfunction getRequestBody(body?: unknown, contentType: string = \"\"): RequestBody {\n if (body === undefined) {\n return { body: undefined };\n }\n\n if (isReadableStream(body)) {\n return { body };\n }\n\n if (!contentType && typeof body === \"string\") {\n return { body };\n }\n\n const firstType = contentType.split(\";\")[0];\n\n if (firstType === \"application/json\") {\n return { body: JSON.stringify(body) };\n }\n\n if (ArrayBuffer.isView(body)) {\n if (body instanceof Uint8Array) {\n return { body: binaryArrayToString(body) };\n } else {\n return { body: JSON.stringify(body) };\n }\n }\n\n switch (firstType) {\n case \"multipart/form-data\":\n return isFormData(body)\n ? { formData: processFormData(body) }\n : { body: JSON.stringify(body) };\n case \"text/plain\":\n return { body: String(body) };\n default:\n if (typeof body === \"string\") {\n return { body };\n }\n return { body: JSON.stringify(body) };\n }\n}\n\nfunction isFormData(body: unknown): body is FormDataMap {\n return body instanceof Object && Object.keys(body).length > 0;\n}\n\n/**\n * Checks if binary data is in Uint8Array format, if so decode it to a binary string\n * to send over the wire\n */\nfunction processFormData(formData?: FormDataMap) {\n if (!formData) {\n return formData;\n }\n\n const processedFormData: FormDataMap = {};\n\n for (const element in formData) {\n const item = formData[element];\n if (item instanceof Uint8Array) {\n processedFormData[element] = binaryArrayToString(item);\n } else {\n processedFormData[element] = item;\n }\n }\n\n return processedFormData;\n}\n\n/**\n * Prepares the response body\n */\nfunction getResponseBody(response: PipelineResponse): RequestBodyType | undefined {\n // Set the default response type\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const firstType = contentType.split(\";\")[0];\n const bodyToParse: string = response.bodyAsText ?? \"\";\n\n if (firstType === \"text/plain\") {\n return String(bodyToParse);\n }\n // Default to \"application/json\" and fallback to string;\n try {\n return bodyToParse ? JSON.parse(bodyToParse) : undefined;\n } catch (error: any) {\n // If we were supposed to get a JSON object and failed to\n // parse, throw a parse error\n if (firstType === \"application/json\") {\n throw createParseError(response, error);\n }\n\n // We are not sure how to handle the response so we return it as\n // plain text.\n return String(bodyToParse);\n }\n}\n\nfunction createParseError(response: PipelineResponse, err: any): RestError {\n const msg = `Error \"${err}\" occurred while parsing the response body - ${response.bodyAsText}.`;\n const errCode = err.code ?? RestError.PARSE_ERROR;\n return new RestError(msg, {\n code: errCode,\n statusCode: response.status,\n request: response.request,\n response: response,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sendRequest.js","sourceRoot":"","sources":["../../../src/client/sendRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAWlC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,MAAmB,EACnB,GAAW,EACX,QAAkB,EAClB,UAA6B,EAAE,EAC/B,gBAA6B;IAE7B,MAAM,UAAU,GAAG,gBAAgB,aAAhB,gBAAgB,cAAh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AAC,WAAW,CAAC,CAAC;KAC5B;IACD,wDAAwD;IACxD,IAAI;QACF,OAAO,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;KAC1D;IAAC,OAAO,KAAU,EAAE;QACnB,yDAAyD;QACzD,6BAA6B;QAC7B,IAAI,SAAS,KAAK,kBAAkB,EAAE;YACpC,MAAM,gBAAgB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;SACzC;QAED,gEAAgE;QAChE,cAAc;QACd,OAAO,MAAM,CAAC,WAAW,CAAC,CAAC;KAC5B;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,QAA0B,EAAE,GAAQ;;IAC5D,MAAM,GAAG,GAAG,UAAU,GAAG,gDAAgD,QAAQ,CAAC,UAAU,GAAG,CAAC;IAChG,MAAM,OAAO,GAAG,MAAA,GAAG,CAAC,IAAI,mCAAI,SAAS,CAAC,WAAW,CAAC;IAClD,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE;QACxB,IAAI,EAAE,OAAO;QACb,UAAU,EAAE,QAAQ,CAAC,MAAM;QAC3B,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n FormDataMap,\n HttpClient,\n HttpMethods,\n PipelineRequest,\n PipelineResponse,\n RawHttpHeaders,\n RequestBodyType,\n} from \"../interfaces\";\nimport { RestError } from \"../restError\";\nimport { Pipeline } from \"../pipeline\";\nimport { createHttpHeaders } from \"../httpHeaders\";\nimport { createPipelineRequest } from \"../pipelineRequest\";\nimport { getCachedDefaultHttpsClient } from \"./clientHelpers\";\nimport { isReadableStream } from \"../util/typeGuards\";\nimport { HttpResponse, RequestParameters } from \"./common\";\nimport { binaryArrayToString } from \"./helpers/getBinaryBody\";\n\n/**\n * Helper function to send request used by the client\n * @param method - method to use to send the request\n * @param url - url to send the request to\n * @param pipeline - pipeline with the policies to run when sending the request\n * @param options - request options\n * @param customHttpClient - a custom HttpClient to use when making the request\n * @returns returns and HttpResponse\n */\nexport async function sendRequest(\n method: HttpMethods,\n url: string,\n pipeline: Pipeline,\n options: RequestParameters = {},\n customHttpClient?: HttpClient\n): Promise<HttpResponse> {\n const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();\n const request = buildPipelineRequest(method, url, options);\n\n const response = await pipeline.sendRequest(httpClient, request);\n\n const rawHeaders: RawHttpHeaders = response.headers.toJSON();\n\n const parsedBody: RequestBodyType | undefined = getResponseBody(response);\n\n if (options?.onResponse) {\n options.onResponse({ ...response, request, rawHeaders, parsedBody });\n }\n\n return {\n request,\n headers: rawHeaders,\n status: `${response.status}`,\n body: parsedBody,\n };\n}\n\n/**\n * Helper function to send request used by the client\n * @param method - method to use to send the request\n * @param url - url to send the request to\n * @param pipeline - pipeline with the policies to run when sending the request\n * @param options - request options\n * @param customHttpClient - a custom HttpClient to use when making the request\n * @returns returns and HttpResponse\n */\nexport async function sendRequestAsStream<\n TResponse extends HttpResponse & {\n body: NodeJS.ReadableStream | ReadableStream<Uint8Array> | undefined;\n }\n>(\n method: HttpMethods,\n url: string,\n pipeline: Pipeline,\n options: RequestParameters = {},\n customHttpClient?: HttpClient\n): Promise<TResponse> {\n const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();\n const request = buildPipelineRequest(method, url, { ...options, responseAsStream: true });\n const response = await pipeline.sendRequest(httpClient, request);\n const rawHeaders: RawHttpHeaders = response.headers.toJSON();\n\n const parsedBody = response.browserStreamBody ?? response.readableStreamBody;\n\n return {\n request,\n headers: rawHeaders,\n status: `${response.status}`,\n body: parsedBody,\n } as TResponse;\n}\n\n/**\n * Function to determine the content-type of a body\n * this is used if an explicit content-type is not provided\n * @param body - body in the request\n * @returns returns the content-type\n */\nfunction getContentType(body: any): string {\n if (ArrayBuffer.isView(body)) {\n return \"application/octet-stream\";\n }\n\n // By default return json\n return \"application/json; charset=UTF-8\";\n}\n\nexport interface InternalRequestParameters extends RequestParameters {\n responseAsStream?: boolean;\n}\n\nfunction buildPipelineRequest(\n method: HttpMethods,\n url: string,\n options: InternalRequestParameters = {}\n): PipelineRequest {\n const { body, formData } = getRequestBody(options.body, options.contentType);\n const hasContent = body !== undefined || formData !== undefined;\n\n const headers = createHttpHeaders({\n ...(options.headers ? options.headers : {}),\n accept: options.accept ?? \"application/json\",\n ...(hasContent && {\n \"content-type\": options.contentType ?? getContentType(options.body),\n }),\n });\n\n return createPipelineRequest({\n url,\n method,\n body,\n formData,\n headers,\n allowInsecureConnection: options.allowInsecureConnection,\n tracingOptions: options.tracingOptions,\n abortSignal: options.abortSignal,\n onUploadProgress: options.onUploadProgress,\n onDownloadProgress: options.onDownloadProgress,\n timeout: options.timeout,\n enableBrowserStreams: true,\n streamResponseStatusCodes: options.responseAsStream\n ? new Set([Number.POSITIVE_INFINITY])\n : undefined,\n });\n}\n\ninterface RequestBody {\n body?: RequestBodyType;\n formData?: FormDataMap;\n}\n\n/**\n * Prepares the body before sending the request\n */\nfunction getRequestBody(body?: unknown, contentType: string = \"\"): RequestBody {\n if (body === undefined) {\n return { body: undefined };\n }\n\n if (isReadableStream(body)) {\n return { body };\n }\n\n if (!contentType && typeof body === \"string\") {\n return { body };\n }\n\n const firstType = contentType.split(\";\")[0];\n\n if (firstType === \"application/json\") {\n return { body: JSON.stringify(body) };\n }\n\n if (ArrayBuffer.isView(body)) {\n if (body instanceof Uint8Array) {\n return { body: binaryArrayToString(body) };\n } else {\n return { body: JSON.stringify(body) };\n }\n }\n\n switch (firstType) {\n case \"multipart/form-data\":\n return isFormData(body)\n ? { formData: processFormData(body) }\n : { body: JSON.stringify(body) };\n case \"text/plain\":\n return { body: String(body) };\n default:\n if (typeof body === \"string\") {\n return { body };\n }\n return { body: JSON.stringify(body) };\n }\n}\n\nfunction isFormData(body: unknown): body is FormDataMap {\n return body instanceof Object && Object.keys(body).length > 0;\n}\n\n/**\n * Checks if binary data is in Uint8Array format, if so decode it to a binary string\n * to send over the wire\n */\nfunction processFormData(formData?: FormDataMap) {\n if (!formData) {\n return formData;\n }\n\n const processedFormData: FormDataMap = {};\n\n for (const element in formData) {\n const item = formData[element];\n if (item instanceof Uint8Array) {\n processedFormData[element] = binaryArrayToString(item);\n } else {\n processedFormData[element] = item;\n }\n }\n\n return processedFormData;\n}\n\n/**\n * Prepares the response body\n */\nfunction getResponseBody(response: PipelineResponse): RequestBodyType | undefined {\n // Set the default response type\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const firstType = contentType.split(\";\")[0];\n const bodyToParse: string = response.bodyAsText ?? \"\";\n\n if (firstType === \"text/plain\") {\n return String(bodyToParse);\n }\n // Default to \"application/json\" and fallback to string;\n try {\n return bodyToParse ? JSON.parse(bodyToParse) : undefined;\n } catch (error: any) {\n // If we were supposed to get a JSON object and failed to\n // parse, throw a parse error\n if (firstType === \"application/json\") {\n throw createParseError(response, error);\n }\n\n // We are not sure how to handle the response so we return it as\n // plain text.\n return String(bodyToParse);\n }\n}\n\nfunction createParseError(response: PipelineResponse, err: any): RestError {\n const msg = `Error \"${err}\" occurred while parsing the response body - ${response.bodyAsText}.`;\n const errCode = err.code ?? RestError.PARSE_ERROR;\n return new RestError(msg, {\n code: errCode,\n statusCode: response.status,\n request: response.request,\n response: response,\n });\n}\n"]}
|
|
@@ -11,6 +11,7 @@ import { isNode } from "./util/checkEnvironment";
|
|
|
11
11
|
import { proxyPolicy } from "./policies/proxyPolicy";
|
|
12
12
|
import { tlsPolicy } from "./policies/tlsPolicy";
|
|
13
13
|
import { tracingPolicy } from "./policies/tracingPolicy";
|
|
14
|
+
import { multipartPolicy } from "./policies/multipartPolicy";
|
|
14
15
|
/**
|
|
15
16
|
* Create a new pipeline with a default set of customizable policies.
|
|
16
17
|
* @param options - Options to configure a custom pipeline.
|
|
@@ -26,6 +27,10 @@ export function createPipelineFromOptions(options) {
|
|
|
26
27
|
}
|
|
27
28
|
pipeline.addPolicy(formDataPolicy());
|
|
28
29
|
pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));
|
|
30
|
+
// The multipart policy is added after policies with no phase, so that
|
|
31
|
+
// policies can be added between it and formDataPolicy to modify
|
|
32
|
+
// properties (e.g., making the boundary constant in recorded tests).
|
|
33
|
+
pipeline.addPolicy(multipartPolicy(), { afterPhase: "Deserialize" });
|
|
29
34
|
pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
|
|
30
35
|
pipeline.addPolicy(tracingPolicy(options.userAgentOptions), { afterPhase: "Retry" });
|
|
31
36
|
if (isNode) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPipelineFromOptions.js","sourceRoot":"","sources":["../../src/createPipelineFromOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAoB,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAY,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAE3D,OAAO,EAAyB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAClF,OAAO,EAA0B,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAGrF,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"createPipelineFromOptions.js","sourceRoot":"","sources":["../../src/createPipelineFromOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,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EAAE,UAAU,EAAE,aAAa,EAAE,CAAC,CAAC;IACrE,QAAQ,CAAC,SAAS,CAAC,kBAAkB,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IACjF,QAAQ,CAAC,SAAS,CAAC,aAAa,CAAC,OAAO,CAAC,gBAAgB,CAAC,EAAE,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;IACrF,IAAI,MAAM,EAAE;QACV,+DAA+D;QAC/D,kDAAkD;QAClD,QAAQ,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;KACtF;IACD,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;IAE9E,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LogPolicyOptions, logPolicy } from \"./policies/logPolicy\";\nimport { Pipeline, createEmptyPipeline } from \"./pipeline\";\nimport { PipelineRetryOptions, TlsSettings } from \"./interfaces\";\nimport { RedirectPolicyOptions, redirectPolicy } from \"./policies/redirectPolicy\";\nimport { UserAgentPolicyOptions, userAgentPolicy } from \"./policies/userAgentPolicy\";\n\nimport { ProxySettings } from \".\";\nimport { decompressResponsePolicy } from \"./policies/decompressResponsePolicy\";\nimport { defaultRetryPolicy } from \"./policies/defaultRetryPolicy\";\nimport { formDataPolicy } from \"./policies/formDataPolicy\";\nimport { isNode } from \"./util/checkEnvironment\";\nimport { proxyPolicy } from \"./policies/proxyPolicy\";\nimport { tlsPolicy } from \"./policies/tlsPolicy\";\nimport { tracingPolicy } from \"./policies/tracingPolicy\";\nimport { multipartPolicy } from \"./policies/multipartPolicy\";\n\n/**\n * Defines options that are used to configure the HTTP pipeline for\n * an SDK client.\n */\nexport interface PipelineOptions {\n /**\n * Options that control how to retry failed requests.\n */\n retryOptions?: PipelineRetryOptions;\n\n /**\n * Options to configure a proxy for outgoing requests.\n */\n proxyOptions?: ProxySettings;\n\n /** Options for configuring TLS authentication */\n tlsOptions?: TlsSettings;\n\n /**\n * Options for how redirect responses are handled.\n */\n redirectOptions?: RedirectPolicyOptions;\n\n /**\n * Options for adding user agent details to outgoing requests.\n */\n userAgentOptions?: UserAgentPolicyOptions;\n\n /**\n * Options for setting common telemetry and tracing info to outgoing requests.\n */\n telemetryOptions?: TelemetryOptions;\n}\n\n/**\n * Defines options that are used to configure common telemetry and tracing info\n */\nexport interface TelemetryOptions {\n /**\n * The name of the header to pass the request ID to.\n */\n clientRequestIdHeaderName?: string;\n}\n\n/**\n * Defines options that are used to configure internal options of\n * the HTTP pipeline for an SDK client.\n */\nexport interface InternalPipelineOptions extends PipelineOptions {\n /**\n * Options to configure request/response logging.\n */\n loggingOptions?: LogPolicyOptions;\n}\n\n/**\n * Create a new pipeline with a default set of customizable policies.\n * @param options - Options to configure a custom pipeline.\n */\nexport function createPipelineFromOptions(options: InternalPipelineOptions): Pipeline {\n const pipeline = createEmptyPipeline();\n\n if (isNode) {\n if (options.tlsOptions) {\n pipeline.addPolicy(tlsPolicy(options.tlsOptions));\n }\n pipeline.addPolicy(proxyPolicy(options.proxyOptions));\n pipeline.addPolicy(decompressResponsePolicy());\n }\n\n pipeline.addPolicy(formDataPolicy());\n pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));\n // The multipart policy is added after policies with no phase, so that\n // policies can be added between it and formDataPolicy to modify\n // properties (e.g., making the boundary constant in recorded tests).\n pipeline.addPolicy(multipartPolicy(), { afterPhase: \"Deserialize\" });\n pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: \"Retry\" });\n pipeline.addPolicy(tracingPolicy(options.userAgentOptions), { afterPhase: \"Retry\" });\n if (isNode) {\n // Both XHR and Fetch expect to handle redirects automatically,\n // so only include this policy when we're in Node.\n pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: \"Retry\" });\n }\n pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: \"Sign\" });\n\n return pipeline;\n}\n"]}
|
|
@@ -3,20 +3,7 @@
|
|
|
3
3
|
import { AbortError } from "./abort-controller/AbortError";
|
|
4
4
|
import { RestError } from "./restError";
|
|
5
5
|
import { createHttpHeaders } from "./httpHeaders";
|
|
6
|
-
|
|
7
|
-
* Checks if the body is a NodeReadable stream which is not supported in Browsers
|
|
8
|
-
*/
|
|
9
|
-
function isNodeReadableStream(body) {
|
|
10
|
-
return body && typeof body.pipe === "function";
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Checks if the body is a ReadableStream supported by browsers
|
|
14
|
-
*/
|
|
15
|
-
function isReadableStream(body) {
|
|
16
|
-
return Boolean(body &&
|
|
17
|
-
typeof body.getReader === "function" &&
|
|
18
|
-
typeof body.tee === "function");
|
|
19
|
-
}
|
|
6
|
+
import { isNodeReadableStream, isReadableStream } from "./util/typeGuards";
|
|
20
7
|
/**
|
|
21
8
|
* Checks if the body is a Blob or Blob-like
|
|
22
9
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchHttpClient.js","sourceRoot":"","sources":["../../src/fetchHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAQ3D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD;;GAEG;AACH,SAAS,oBAAoB,CAAC,IAAS;IACrC,OAAO,IAAI,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,UAAU,CAAC;AACjD,CAAC;AAED;;GAEG;AACH,SAAS,gBAAgB,CAAC,IAAa;IACrC,OAAO,OAAO,CACZ,IAAI;QACF,OAAQ,IAAuB,CAAC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M,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;SACF,CAAC,CAAC;KACJ;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,IAAI,eAAe,EAAE,CAAC;AAC/B,CAAC;AAED,SAAS,0BAA0B,CAAC,cAA8B;IAChE,OAAO,cAAc,CAAC,WAAW,KAAK,SAAS,IAAI,IAAI,CAAC,eAAe,KAAK,SAAS,CAAC;AACxF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError } from \"./abort-controller/AbortError\";\nimport {\n HttpClient,\n HttpHeaders as PipelineHeaders,\n PipelineRequest,\n PipelineResponse,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { RestError } from \"./restError\";\nimport { createHttpHeaders } from \"./httpHeaders\";\n\n/**\n * Checks if the body is a NodeReadable stream which is not supported in Browsers\n */\nfunction isNodeReadableStream(body: any): body is NodeJS.ReadableStream {\n return body && typeof body.pipe === \"function\";\n}\n\n/**\n * Checks if the body is a ReadableStream supported by browsers\n */\nfunction isReadableStream(body: unknown): body is ReadableStream {\n return Boolean(\n body &&\n typeof (body as ReadableStream).getReader === \"function\" &&\n typeof (body as ReadableStream).tee === \"function\"\n );\n}\n\n/**\n * Checks if the body is a Blob or Blob-like\n */\nfunction isBlob(body: unknown): body is Blob {\n // File objects count as a type of Blob, so we want to use instanceof explicitly\n return (typeof Blob === \"function\" || typeof Blob === \"object\") && body instanceof Blob;\n}\n\n/**\n * A HttpClient implementation that uses window.fetch to send HTTP requests.\n * @internal\n */\nclass FetchHttpClient implements HttpClient {\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n const url = new URL(request.url);\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n if (request.proxySettings) {\n throw new Error(\"HTTP proxy is not supported in browser environment\");\n }\n\n try {\n return await makeRequest(request);\n } catch (e: any) {\n throw getError(e, request);\n }\n }\n}\n\n/**\n * Sends a request\n */\nasync function makeRequest(request: PipelineRequest): Promise<PipelineResponse> {\n const { abortController, abortControllerCleanup } = setupAbortSignal(request);\n try {\n const headers = buildFetchHeaders(request.headers);\n const { streaming, body: requestBody } = buildRequestBody(request);\n const requestInit: RequestInit = {\n body: requestBody,\n method: request.method,\n headers: headers,\n signal: abortController.signal,\n // Cloudflare doesn't implement the full Fetch API spec\n // because of some of it doesn't make sense in the edge.\n // See https://github.com/cloudflare/workerd/issues/902\n ...(\"credentials\" in Request.prototype\n ? { credentials: request.withCredentials ? \"include\" : \"same-origin\" }\n : {}),\n ...(\"cache\" in Request.prototype ? { cache: \"no-store\" } : {}),\n };\n\n // According to https://fetch.spec.whatwg.org/#fetch-method,\n // init.duplex must be set when body is a ReadableStream object.\n // currently \"half\" is the only valid value.\n if (streaming) {\n (requestInit as any).duplex = \"half\";\n }\n /**\n * Developers of the future:\n * Do not set redirect: \"manual\" as part\n * of request options.\n * It will not work as you expect.\n */\n const response = await fetch(request.url, requestInit);\n // If we're uploading a blob, we need to fire the progress event manually\n if (isBlob(request.body) && request.onUploadProgress) {\n request.onUploadProgress({ loadedBytes: request.body.size });\n }\n return buildPipelineResponse(response, request, abortControllerCleanup);\n } catch (e) {\n abortControllerCleanup?.();\n throw e;\n }\n}\n\n/**\n * Creates a pipeline response from a Fetch response;\n */\nasync function buildPipelineResponse(\n httpResponse: Response,\n request: PipelineRequest,\n abortControllerCleanup?: () => void\n) {\n const headers = buildPipelineHeaders(httpResponse);\n const response: PipelineResponse = {\n request,\n headers,\n status: httpResponse.status,\n };\n\n const bodyStream = isReadableStream(httpResponse.body)\n ? buildBodyStream(httpResponse.body, {\n onProgress: request.onDownloadProgress,\n onEnd: abortControllerCleanup,\n })\n : httpResponse.body;\n\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(response.status)\n ) {\n if (request.enableBrowserStreams) {\n response.browserStreamBody = bodyStream ?? undefined;\n } else {\n const responseStream = new Response(bodyStream);\n response.blobBody = responseStream.blob();\n abortControllerCleanup?.();\n }\n } else {\n const responseStream = new Response(bodyStream);\n\n response.bodyAsText = await responseStream.text();\n abortControllerCleanup?.();\n }\n\n return response;\n}\n\nfunction setupAbortSignal(request: PipelineRequest): {\n abortController: AbortController;\n abortControllerCleanup: (() => void) | undefined;\n} {\n const abortController = new AbortController();\n\n // Cleanup function\n let abortControllerCleanup: (() => void) | undefined;\n\n /**\n * Attach an abort listener to the request\n */\n let abortListener: ((event: any) => void) | undefined;\n if (request.abortSignal) {\n if (request.abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n abortListener = (event: Event) => {\n if (event.type === \"abort\") {\n abortController.abort();\n }\n };\n request.abortSignal.addEventListener(\"abort\", abortListener);\n abortControllerCleanup = () => {\n if (abortListener) {\n request.abortSignal?.removeEventListener(\"abort\", abortListener);\n }\n };\n }\n\n // If a timeout was passed, call the abort signal once the time elapses\n if (request.timeout > 0) {\n setTimeout(() => {\n abortController.abort();\n }, request.timeout);\n }\n\n return { abortController, abortControllerCleanup };\n}\n\n/**\n * Gets the specific error\n */\nfunction getError(e: RestError, request: PipelineRequest): RestError {\n if (e && e?.name === \"AbortError\") {\n return e;\n } else {\n return new RestError(`Error sending request: ${e.message}`, {\n code: e?.code ?? RestError.REQUEST_SEND_ERROR,\n request,\n });\n }\n}\n\n/**\n * Converts PipelineRequest headers to Fetch headers\n */\nfunction buildFetchHeaders(pipelineHeaders: PipelineHeaders) {\n const headers = new Headers();\n for (const [name, value] of pipelineHeaders) {\n headers.append(name, value);\n }\n\n return headers;\n}\n\nfunction buildPipelineHeaders(httpResponse: Response): PipelineHeaders {\n const responseHeaders = createHttpHeaders();\n for (const [name, value] of httpResponse.headers) {\n responseHeaders.set(name, value);\n }\n\n return responseHeaders;\n}\n\nfunction buildRequestBody(request: PipelineRequest) {\n const body = typeof request.body === \"function\" ? request.body() : request.body;\n if (isNodeReadableStream(body)) {\n throw new Error(\"Node streams are not supported in browser environment.\");\n }\n\n return isReadableStream(body)\n ? { streaming: true, body: buildBodyStream(body, { onProgress: request.onUploadProgress }) }\n : { streaming: false, body };\n}\n\n/**\n * Reads the request/response original stream and stream it through a new\n * ReadableStream, this is done to be able to report progress in a way that\n * all modern browsers support. TransformStreams would be an alternative,\n * however they are not yet supported by all browsers i.e Firefox\n */\nfunction buildBodyStream(\n readableStream: ReadableStream<Uint8Array>,\n options: { onProgress?: (progress: TransferProgressEvent) => void; onEnd?: () => void } = {}\n): ReadableStream<Uint8Array> {\n let loadedBytes = 0;\n const { onProgress, onEnd } = options;\n\n // If the current browser supports pipeThrough we use a TransformStream\n // to report progress\n if (isTransformStreamSupported(readableStream)) {\n return readableStream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk === null) {\n controller.terminate();\n return;\n }\n\n controller.enqueue(chunk);\n loadedBytes += chunk.length;\n if (onProgress) {\n onProgress({ loadedBytes });\n }\n },\n flush() {\n onEnd?.();\n },\n })\n );\n } else {\n // If we can't use transform streams, wrap the original stream in a new readable stream\n // and use pull to enqueue each chunk and report progress.\n const reader = readableStream.getReader();\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n // When no more data needs to be consumed, break the reading\n if (done || !value) {\n onEnd?.();\n // Close the stream\n controller.close();\n reader.releaseLock();\n return;\n }\n\n loadedBytes += value?.length ?? 0;\n\n // Enqueue the next data chunk into our target stream\n controller.enqueue(value);\n\n if (onProgress) {\n onProgress({ loadedBytes });\n }\n },\n cancel(reason?: string) {\n onEnd?.();\n return reader.cancel(reason);\n },\n });\n }\n}\n\n/**\n * Create a new HttpClient instance for the browser environment.\n * @internal\n */\nexport function createFetchHttpClient(): HttpClient {\n return new FetchHttpClient();\n}\n\nfunction isTransformStreamSupported(readableStream: ReadableStream): boolean {\n return readableStream.pipeThrough !== undefined && self.TransformStream !== undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fetchHttpClient.js","sourceRoot":"","sources":["../../src/fetchHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAQ3D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAE3E;;GAEG;AACH,SAAS,MAAM,CAAC,IAAa;IAC3B,gFAAgF;IAChF,OAAO,CAAC,OAAO,IAAI,KAAK,UAAU,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,IAAI,IAAI,YAAY,IAAI,CAAC;AAC1F,CAAC;AAED;;;GAGG;AACH,MAAM,eAAe;IACnB;;;OAGG;IACI,KAAK,CAAC,WAAW,CAAC,OAAwB;QAC/C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QACjC,MAAM,UAAU,GAAG,GAAG,CAAC,QAAQ,KAAK,QAAQ,CAAC;QAE7C,IAAI,UAAU,IAAI,CAAC,OAAO,CAAC,uBAAuB,EAAE;YAClD,MAAM,IAAI,KAAK,CAAC,qBAAqB,OAAO,CAAC,GAAG,0CAA0C,CAAC,CAAC;SAC7F;QAED,IAAI,OAAO,CAAC,aAAa,EAAE;YACzB,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACvE;QAED,IAAI;YACF,OAAO,MAAM,WAAW,CAAC,OAAO,CAAC,CAAC;SACnC;QAAC,OAAO,CAAM,EAAE;YACf,MAAM,QAAQ,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;SAC5B;IACH,CAAC;CACF;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rB,OAAO;iBACR;gBAED,WAAW,IAAI,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,mCAAI,CAAC,CAAC;gBAElC,qDAAqD;gBACrD,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;gBAE1B,IAAI,UAAU,EAAE;oBACd,UAAU,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;iBAC7B;YACH,CAAC;YACD,MAAM,CAAC,MAAe;gBACpB,KAAK,aAAL,KAAK,uBAAL,KAAK,EAAI,CAAC;gBACV,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;SACF,CAAC,CAAC;KACJ;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,IAAI,eAAe,EAAE,CAAC;AAC/B,CAAC;AAED,SAAS,0BAA0B,CAAC,cAA8B;IAChE,OAAO,cAAc,CAAC,WAAW,KAAK,SAAS,IAAI,IAAI,CAAC,eAAe,KAAK,SAAS,CAAC;AACxF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError } from \"./abort-controller/AbortError\";\nimport {\n HttpClient,\n HttpHeaders as PipelineHeaders,\n PipelineRequest,\n PipelineResponse,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { RestError } from \"./restError\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { isNodeReadableStream, isReadableStream } from \"./util/typeGuards\";\n\n/**\n * Checks if the body is a Blob or Blob-like\n */\nfunction isBlob(body: unknown): body is Blob {\n // File objects count as a type of Blob, so we want to use instanceof explicitly\n return (typeof Blob === \"function\" || typeof Blob === \"object\") && body instanceof Blob;\n}\n\n/**\n * A HttpClient implementation that uses window.fetch to send HTTP requests.\n * @internal\n */\nclass FetchHttpClient implements HttpClient {\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n const url = new URL(request.url);\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n if (request.proxySettings) {\n throw new Error(\"HTTP proxy is not supported in browser environment\");\n }\n\n try {\n return await makeRequest(request);\n } catch (e: any) {\n throw getError(e, request);\n }\n }\n}\n\n/**\n * Sends a request\n */\nasync function makeRequest(request: PipelineRequest): Promise<PipelineResponse> {\n const { abortController, abortControllerCleanup } = setupAbortSignal(request);\n try {\n const headers = buildFetchHeaders(request.headers);\n const { streaming, body: requestBody } = buildRequestBody(request);\n const requestInit: RequestInit = {\n body: requestBody,\n method: request.method,\n headers: headers,\n signal: abortController.signal,\n // Cloudflare doesn't implement the full Fetch API spec\n // because of some of it doesn't make sense in the edge.\n // See https://github.com/cloudflare/workerd/issues/902\n ...(\"credentials\" in Request.prototype\n ? { credentials: request.withCredentials ? \"include\" : \"same-origin\" }\n : {}),\n ...(\"cache\" in Request.prototype ? { cache: \"no-store\" } : {}),\n };\n\n // According to https://fetch.spec.whatwg.org/#fetch-method,\n // init.duplex must be set when body is a ReadableStream object.\n // currently \"half\" is the only valid value.\n if (streaming) {\n (requestInit as any).duplex = \"half\";\n }\n /**\n * Developers of the future:\n * Do not set redirect: \"manual\" as part\n * of request options.\n * It will not work as you expect.\n */\n const response = await fetch(request.url, requestInit);\n // If we're uploading a blob, we need to fire the progress event manually\n if (isBlob(request.body) && request.onUploadProgress) {\n request.onUploadProgress({ loadedBytes: request.body.size });\n }\n return buildPipelineResponse(response, request, abortControllerCleanup);\n } catch (e) {\n abortControllerCleanup?.();\n throw e;\n }\n}\n\n/**\n * Creates a pipeline response from a Fetch response;\n */\nasync function buildPipelineResponse(\n httpResponse: Response,\n request: PipelineRequest,\n abortControllerCleanup?: () => void\n) {\n const headers = buildPipelineHeaders(httpResponse);\n const response: PipelineResponse = {\n request,\n headers,\n status: httpResponse.status,\n };\n\n const bodyStream = isReadableStream(httpResponse.body)\n ? buildBodyStream(httpResponse.body, {\n onProgress: request.onDownloadProgress,\n onEnd: abortControllerCleanup,\n })\n : httpResponse.body;\n\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(response.status)\n ) {\n if (request.enableBrowserStreams) {\n response.browserStreamBody = bodyStream ?? undefined;\n } else {\n const responseStream = new Response(bodyStream);\n response.blobBody = responseStream.blob();\n abortControllerCleanup?.();\n }\n } else {\n const responseStream = new Response(bodyStream);\n\n response.bodyAsText = await responseStream.text();\n abortControllerCleanup?.();\n }\n\n return response;\n}\n\nfunction setupAbortSignal(request: PipelineRequest): {\n abortController: AbortController;\n abortControllerCleanup: (() => void) | undefined;\n} {\n const abortController = new AbortController();\n\n // Cleanup function\n let abortControllerCleanup: (() => void) | undefined;\n\n /**\n * Attach an abort listener to the request\n */\n let abortListener: ((event: any) => void) | undefined;\n if (request.abortSignal) {\n if (request.abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n abortListener = (event: Event) => {\n if (event.type === \"abort\") {\n abortController.abort();\n }\n };\n request.abortSignal.addEventListener(\"abort\", abortListener);\n abortControllerCleanup = () => {\n if (abortListener) {\n request.abortSignal?.removeEventListener(\"abort\", abortListener);\n }\n };\n }\n\n // If a timeout was passed, call the abort signal once the time elapses\n if (request.timeout > 0) {\n setTimeout(() => {\n abortController.abort();\n }, request.timeout);\n }\n\n return { abortController, abortControllerCleanup };\n}\n\n/**\n * Gets the specific error\n */\nfunction getError(e: RestError, request: PipelineRequest): RestError {\n if (e && e?.name === \"AbortError\") {\n return e;\n } else {\n return new RestError(`Error sending request: ${e.message}`, {\n code: e?.code ?? RestError.REQUEST_SEND_ERROR,\n request,\n });\n }\n}\n\n/**\n * Converts PipelineRequest headers to Fetch headers\n */\nfunction buildFetchHeaders(pipelineHeaders: PipelineHeaders) {\n const headers = new Headers();\n for (const [name, value] of pipelineHeaders) {\n headers.append(name, value);\n }\n\n return headers;\n}\n\nfunction buildPipelineHeaders(httpResponse: Response): PipelineHeaders {\n const responseHeaders = createHttpHeaders();\n for (const [name, value] of httpResponse.headers) {\n responseHeaders.set(name, value);\n }\n\n return responseHeaders;\n}\n\nfunction buildRequestBody(request: PipelineRequest) {\n const body = typeof request.body === \"function\" ? request.body() : request.body;\n if (isNodeReadableStream(body)) {\n throw new Error(\"Node streams are not supported in browser environment.\");\n }\n\n return isReadableStream(body)\n ? { streaming: true, body: buildBodyStream(body, { onProgress: request.onUploadProgress }) }\n : { streaming: false, body };\n}\n\n/**\n * Reads the request/response original stream and stream it through a new\n * ReadableStream, this is done to be able to report progress in a way that\n * all modern browsers support. TransformStreams would be an alternative,\n * however they are not yet supported by all browsers i.e Firefox\n */\nfunction buildBodyStream(\n readableStream: ReadableStream<Uint8Array>,\n options: { onProgress?: (progress: TransferProgressEvent) => void; onEnd?: () => void } = {}\n): ReadableStream<Uint8Array> {\n let loadedBytes = 0;\n const { onProgress, onEnd } = options;\n\n // If the current browser supports pipeThrough we use a TransformStream\n // to report progress\n if (isTransformStreamSupported(readableStream)) {\n return readableStream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk === null) {\n controller.terminate();\n return;\n }\n\n controller.enqueue(chunk);\n loadedBytes += chunk.length;\n if (onProgress) {\n onProgress({ loadedBytes });\n }\n },\n flush() {\n onEnd?.();\n },\n })\n );\n } else {\n // If we can't use transform streams, wrap the original stream in a new readable stream\n // and use pull to enqueue each chunk and report progress.\n const reader = readableStream.getReader();\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n // When no more data needs to be consumed, break the reading\n if (done || !value) {\n onEnd?.();\n // Close the stream\n controller.close();\n reader.releaseLock();\n return;\n }\n\n loadedBytes += value?.length ?? 0;\n\n // Enqueue the next data chunk into our target stream\n controller.enqueue(value);\n\n if (onProgress) {\n onProgress({ loadedBytes });\n }\n },\n cancel(reason?: string) {\n onEnd?.();\n return reader.cancel(reason);\n },\n });\n }\n}\n\n/**\n * Create a new HttpClient instance for the browser environment.\n * @internal\n */\nexport function createFetchHttpClient(): HttpClient {\n return new FetchHttpClient();\n}\n\nfunction isTransformStreamSupported(readableStream: ReadableStream): boolean {\n return readableStream.pipeThrough !== undefined && self.TransformStream !== undefined;\n}\n"]}
|
package/dist-esm/src/index.js
CHANGED
|
@@ -8,6 +8,7 @@ export { createPipelineRequest } from "./pipelineRequest";
|
|
|
8
8
|
export { RestError, isRestError } from "./restError";
|
|
9
9
|
export { decompressResponsePolicy, decompressResponsePolicyName, } from "./policies/decompressResponsePolicy";
|
|
10
10
|
export { logPolicy, logPolicyName } from "./policies/logPolicy";
|
|
11
|
+
export { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy";
|
|
11
12
|
export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./policies/proxyPolicy";
|
|
12
13
|
export { redirectPolicy, redirectPolicyName, } from "./policies/redirectPolicy";
|
|
13
14
|
export { tracingPolicy, tracingPolicyName } from "./policies/tracingPolicy";
|
|
@@ -26,6 +27,7 @@ export { createAbortablePromise, } from "./util/createAbortablePromise";
|
|
|
26
27
|
export { getRandomIntegerInclusive } from "./util/random";
|
|
27
28
|
export { isObject } from "./util/object";
|
|
28
29
|
export { isError, getErrorMessage } from "./util/error";
|
|
30
|
+
export { createFile, createFileFromStream, } from "./util/file";
|
|
29
31
|
export { computeSha256Hash, computeSha256Hmac } from "./util/sha256";
|
|
30
32
|
export { isDefined, isObjectWithProperties, objectHasProperty } from "./util/typeGuards";
|
|
31
33
|
export { randomUUID } from "./util/uuidUtils";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AAC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;AACjB,OAAO,EAAE,KAAK,EAAgB,MAAM,cAAc,CAAC;AACnD,OAAO,EAAgB,qBAAqB,EAA2B,MAAM,qBAAqB,CAAC;AACnG,OAAO,EACL,sBAAsB,GAEvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAiB,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EACL,UAAU,EACV,oBAAoB,GAGrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACzF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EACL,SAAS,EACT,KAAK,EACL,MAAM,EACN,MAAM,EACN,aAAa,EACb,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAgB,MAAM,sBAAsB,CAAC;AAC5F,OAAO,EAEL,qBAAqB,GAGtB,MAAM,iBAAiB,CAAC;AACzB,SAAS;AACT,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EACL,2BAA2B,GAE5B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport {\n Agent,\n BodyPart,\n FormDataMap,\n FormDataValue,\n HttpClient,\n HttpHeaders,\n HttpMethods,\n KeyObject,\n MultipartRequestBody,\n PipelineRequest,\n PipelineResponse,\n PipelineRetryOptions,\n ProxySettings,\n PxfObject,\n RawHttpHeaders,\n RawHttpHeadersInput,\n RequestBodyType,\n SendRequest,\n TlsSettings,\n TransferProgressEvent,\n} from \"./interfaces\";\nexport {\n AddPolicyOptions as AddPipelineOptions,\n PipelinePhase,\n PipelinePolicy,\n Pipeline,\n createEmptyPipeline,\n} from \"./pipeline\";\nexport {\n createPipelineFromOptions,\n TelemetryOptions,\n InternalPipelineOptions,\n PipelineOptions,\n} from \"./createPipelineFromOptions\";\nexport { createDefaultHttpClient } from \"./defaultHttpClient\";\nexport { createHttpHeaders } from \"./httpHeaders\";\nexport { createPipelineRequest, PipelineRequestOptions } from \"./pipelineRequest\";\nexport { RestError, RestErrorOptions, isRestError } from \"./restError\";\nexport {\n decompressResponsePolicy,\n decompressResponsePolicyName,\n} from \"./policies/decompressResponsePolicy\";\nexport { logPolicy, logPolicyName, LogPolicyOptions } from \"./policies/logPolicy\";\nexport { multipartPolicy, multipartPolicyName } from \"./policies/multipartPolicy\";\nexport { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from \"./policies/proxyPolicy\";\nexport {\n redirectPolicy,\n redirectPolicyName,\n RedirectPolicyOptions,\n} from \"./policies/redirectPolicy\";\nexport { tracingPolicy, tracingPolicyName, TracingPolicyOptions } from \"./policies/tracingPolicy\";\nexport { defaultRetryPolicy, DefaultRetryPolicyOptions } from \"./policies/defaultRetryPolicy\";\nexport {\n userAgentPolicy,\n userAgentPolicyName,\n UserAgentPolicyOptions,\n} from \"./policies/userAgentPolicy\";\nexport { tlsPolicy, tlsPolicyName } from \"./policies/tlsPolicy\";\nexport { formDataPolicy, formDataPolicyName } from \"./policies/formDataPolicy\";\nexport {\n bearerTokenAuthenticationPolicy,\n BearerTokenAuthenticationPolicyOptions,\n bearerTokenAuthenticationPolicyName,\n ChallengeCallbacks,\n AuthorizeRequestOptions,\n AuthorizeRequestOnChallengeOptions,\n} from \"./policies/bearerTokenAuthenticationPolicy\";\nexport { AbortSignalLike } from \"./abort-controller/AbortSignalLike\";\nexport { AbortError } from \"./abort-controller/AbortError\";\nexport { AccessToken, GetTokenOptions, TokenCredential } from \"./auth/tokenCredential\";\nexport { KeyCredential } from \"./auth/keyCredential\";\nexport {\n Instrumenter,\n InstrumenterSpanOptions,\n OperationTracingOptions,\n OptionsWithTracingContext,\n Resolved,\n SpanStatus,\n SpanStatusError,\n SpanStatusSuccess,\n TracingClient,\n TracingClientOptions,\n TracingContext,\n TracingSpan,\n TracingSpanKind,\n TracingSpanLink,\n TracingSpanOptions,\n} from \"./tracing/interfaces\";\nexport { useInstrumenter } from \"./tracing/instrumenter\";\nexport { createTracingClient } from \"./tracing/tracingClient\";\n// from core-util\nexport { delay, DelayOptions } from \"./util/delay\";\nexport { AbortOptions, cancelablePromiseRace, AbortablePromiseBuilder } from \"./util/aborterUtils\";\nexport {\n createAbortablePromise,\n CreateAbortablePromiseOptions,\n} from \"./util/createAbortablePromise\";\nexport { getRandomIntegerInclusive } from \"./util/random\";\nexport { isObject, UnknownObject } from \"./util/object\";\nexport { isError, getErrorMessage } from \"./util/error\";\nexport {\n createFile,\n createFileFromStream,\n CreateFileOptions,\n CreateFileFromStreamOptions,\n} from \"./util/file\";\nexport { computeSha256Hash, computeSha256Hmac } from \"./util/sha256\";\nexport { isDefined, isObjectWithProperties, objectHasProperty } from \"./util/typeGuards\";\nexport { randomUUID } from \"./util/uuidUtils\";\nexport {\n isBrowser,\n isBun,\n isNode,\n isDeno,\n isReactNative,\n isWebWorker,\n} from \"./util/checkEnvironment\";\nexport { uint8ArrayToString, stringToUint8Array, EncodingType } from \"./util/bytesEncoding\";\nexport {\n Debugger,\n TypeSpecRuntimeLogger,\n TypeSpecRuntimeLogLevel,\n TypeSpecRuntimeClientLogger,\n} from \"./logger/logger\";\n// client\nexport { createRestError } from \"./client/restError\";\nexport {\n addCredentialPipelinePolicy,\n AddCredentialPipelinePolicyOptions,\n} from \"./client/clientHelpers\";\nexport { operationOptionsToRequestParameters } from \"./client/operationOptionHelpers\";\nexport * from \"./client/getClient\";\nexport * from \"./client/common\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortSignalLike } from \"./abort-controller/AbortSignalLike\";\nimport { OperationTracingOptions } from \"./tracing/interfaces\";\n\n/**\n * A HttpHeaders collection represented as a simple JSON object.\n */\nexport type RawHttpHeaders = { [headerName: string]: string };\n\n/**\n * A HttpHeaders collection for input, represented as a simple JSON object.\n */\nexport type RawHttpHeadersInput = Record<string, string | number | boolean>;\n\n/**\n * Represents a set of HTTP headers on a request/response.\n * Header names are treated as case insensitive.\n */\nexport interface HttpHeaders extends Iterable<[string, string]> {\n /**\n * Returns the value of a specific header or undefined if not set.\n * @param name - The name of the header to retrieve.\n */\n get(name: string): string | undefined;\n /**\n * Returns true if the specified header exists.\n * @param name - The name of the header to check.\n */\n has(name: string): boolean;\n /**\n * Sets a specific header with a given value.\n * @param name - The name of the header to set.\n * @param value - The value to use for the header.\n */\n set(name: string, value: string | number | boolean): void;\n /**\n * Removes a specific header from the collection.\n * @param name - The name of the header to delete.\n */\n delete(name: string): void;\n /**\n * Accesses a raw JS object that acts as a simple map\n * of header names to values.\n */\n toJSON(options?: { preserveCase?: boolean }): RawHttpHeaders;\n}\n\n/**\n * Types of bodies supported on the request.\n * NodeJS.ReadableStream and () =\\> NodeJS.ReadableStream is Node only.\n * Blob, ReadableStream<Uint8Array>, and () =\\> ReadableStream<Uint8Array> are browser only.\n */\nexport type RequestBodyType =\n | NodeJS.ReadableStream\n | (() => NodeJS.ReadableStream)\n | ReadableStream<Uint8Array>\n | (() => ReadableStream<Uint8Array>)\n | Blob\n | ArrayBuffer\n | ArrayBufferView\n | FormData\n | string\n | null;\n\n/**\n * An interface compatible with NodeJS's `http.Agent`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface Agent {\n /**\n * Destroy any sockets that are currently in use by the agent.\n */\n destroy(): void;\n /**\n * For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.\n */\n maxFreeSockets: number;\n /**\n * Determines how many concurrent sockets the agent can have open per origin.\n */\n maxSockets: number;\n /**\n * An object which contains queues of requests that have not yet been assigned to sockets.\n */\n requests: unknown;\n /**\n * An object which contains arrays of sockets currently in use by the agent.\n */\n sockets: unknown;\n}\n\n/**\n * Metadata about a request being made by the pipeline.\n */\nexport interface PipelineRequest {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout: number;\n\n /**\n * Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.\n * Defaults to false.\n */\n withCredentials: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId: string;\n\n /**\n * The HTTP body content (if any)\n */\n body?: RequestBodyType;\n\n /**\n * To simulate a browser form post\n */\n formData?: FormDataMap;\n\n /**\n * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.\n * When streamResponseStatusCodes contains the value Number.POSITIVE_INFINITY any status would be treated as a stream.\n */\n streamResponseStatusCodes?: Set<number>;\n\n /**\n * Proxy configuration.\n */\n proxySettings?: ProxySettings;\n\n /**\n * If the connection should not be reused.\n */\n disableKeepAlive?: boolean;\n\n /**\n * Used to abort the request later.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Tracing options to use for any created Spans.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n\n /**\n * NODEJS ONLY\n *\n * A Node-only option to provide a custom `http.Agent`/`https.Agent`.\n * Does nothing when running in the browser.\n */\n agent?: Agent;\n\n /**\n * BROWSER ONLY\n *\n * A browser only option to enable browser Streams. If this option is set and a response is a stream\n * the response will have a property `browserStream` instead of `blobBody` which will be undefined.\n *\n * Default value is false\n */\n enableBrowserStreams?: boolean;\n\n /** Settings for configuring TLS authentication */\n tlsSettings?: TlsSettings;\n}\n\n/**\n * Metadata about a response received by the pipeline.\n */\nexport interface PipelineResponse {\n /**\n * The request that generated this response.\n */\n request: PipelineRequest;\n /**\n * The HTTP status code of the response.\n */\n status: number;\n /**\n * The HTTP response headers.\n */\n headers: HttpHeaders;\n\n /**\n * The response body as text (string format)\n */\n bodyAsText?: string | null;\n\n /**\n * BROWSER ONLY\n *\n * The response body as a browser Blob.\n * Always undefined in node.js.\n */\n blobBody?: Promise<Blob>;\n\n /**\n * BROWSER ONLY\n *\n * The response body as a browser ReadableStream.\n * Always undefined in node.js.\n */\n browserStreamBody?: ReadableStream<Uint8Array>;\n\n /**\n * NODEJS ONLY\n *\n * The response body as a node.js Readable stream.\n * Always undefined in the browser.\n */\n readableStreamBody?: NodeJS.ReadableStream;\n}\n\n/**\n * A simple interface for making a pipeline request and receiving a response.\n */\nexport type SendRequest = (request: PipelineRequest) => Promise<PipelineResponse>;\n\n/**\n * The required interface for a client that makes HTTP requests\n * on behalf of a pipeline.\n */\nexport interface HttpClient {\n /**\n * The method that makes the request and returns a response.\n */\n sendRequest: SendRequest;\n}\n\n/**\n * Fired in response to upload or download progress.\n */\nexport type TransferProgressEvent = {\n /**\n * The number of bytes loaded so far.\n */\n loadedBytes: number;\n};\n\n/**\n * Supported HTTP methods to use when making requests.\n */\nexport type HttpMethods =\n | \"GET\"\n | \"PUT\"\n | \"POST\"\n | \"DELETE\"\n | \"PATCH\"\n | \"HEAD\"\n | \"OPTIONS\"\n | \"TRACE\";\n\n/**\n * Options to configure a proxy for outgoing requests (Node.js only).\n */\nexport interface ProxySettings {\n /**\n * The proxy's host address.\n */\n host: string;\n\n /**\n * The proxy host's port.\n */\n port: number;\n\n /**\n * The user name to authenticate with the proxy, if required.\n */\n username?: string;\n\n /**\n * The password to authenticate with the proxy, if required.\n */\n password?: string;\n}\n\n/**\n * Each form data entry can be a string or (in the browser) a Blob.\n */\nexport type FormDataValue = string | Blob;\n\n/**\n * A simple object that provides form data, as if from a browser form.\n */\nexport type FormDataMap = { [key: string]: FormDataValue | FormDataValue[] };\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface PipelineRetryOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second). The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * Represents a certificate credential for authentication.\n */\nexport interface CertificateCredential {\n /**\n * Optionally override the trusted CA certificates. Default is to trust\n * the well-known CAs curated by Mozilla. Mozilla's CAs are completely\n * replaced when CAs are explicitly specified using this option.\n */\n ca?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Cert chains in PEM format. One cert chain should be provided per\n * private key. Each cert chain should consist of the PEM formatted\n * certificate for a provided private key, followed by the PEM\n * formatted intermediate certificates (if any), in order, and not\n * including the root CA (the root CA must be pre-known to the peer,\n * see ca). When providing multiple cert chains, they do not have to\n * be in the same order as their private keys in key. If the\n * intermediate certificates are not provided, the peer will not be\n * able to validate the certificate, and the handshake will fail.\n */\n cert?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Private keys in PEM format. PEM allows the option of private keys\n * being encrypted. Encrypted keys will be decrypted with\n * options.passphrase. Multiple keys using different algorithms can be\n * provided either as an array of unencrypted key strings or buffers,\n * or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n key?: string | Buffer | Array<Buffer | KeyObject> | undefined;\n /**\n * Shared passphrase used for a single private key and/or a PFX.\n */\n passphrase?: string | undefined;\n /**\n * PFX or PKCS12 encoded private key and certificate chain. pfx is an\n * alternative to providing key and cert individually. PFX is usually\n * encrypted, if it is, passphrase will be used to decrypt it. Multiple\n * PFX can be provided either as an array of unencrypted PFX buffers,\n * or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;\n}\n\n/**\n * Represents a certificate for TLS authentication.\n */\nexport interface TlsSettings {\n /**\n * Optionally override the trusted CA certificates. Default is to trust\n * the well-known CAs curated by Mozilla. Mozilla's CAs are completely\n * replaced when CAs are explicitly specified using this option.\n */\n ca?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Cert chains in PEM format. One cert chain should be provided per\n * private key. Each cert chain should consist of the PEM formatted\n * certificate for a provided private key, followed by the PEM\n * formatted intermediate certificates (if any), in order, and not\n * including the root CA (the root CA must be pre-known to the peer,\n * see ca). When providing multiple cert chains, they do not have to\n * be in the same order as their private keys in key. If the\n * intermediate certificates are not provided, the peer will not be\n * able to validate the certificate, and the handshake will fail.\n */\n cert?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Private keys in PEM format. PEM allows the option of private keys\n * being encrypted. Encrypted keys will be decrypted with\n * options.passphrase. Multiple keys using different algorithms can be\n * provided either as an array of unencrypted key strings or buffers,\n * or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n key?: string | Buffer | Array<Buffer | KeyObject> | undefined;\n /**\n * Shared passphrase used for a single private key and/or a PFX.\n */\n passphrase?: string | undefined;\n /**\n * PFX or PKCS12 encoded private key and certificate chain. pfx is an\n * alternative to providing key and cert individually. PFX is usually\n * encrypted, if it is, passphrase will be used to decrypt it. Multiple\n * PFX can be provided either as an array of unencrypted PFX buffers,\n * or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;\n}\n\n/**\n * An interface compatible with NodeJS's `tls.KeyObject`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface KeyObject {\n /**\n * Private keys in PEM format.\n */\n pem: string | Buffer;\n /**\n * Optional passphrase.\n */\n passphrase?: string | undefined;\n}\n\n/**\n * An interface compatible with NodeJS's `tls.PxfObject`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface PxfObject {\n /**\n * PFX or PKCS12 encoded private key and certificate chain.\n */\n buf: string | Buffer;\n /**\n * Optional passphrase.\n */\n passphrase?: string | undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortSignalLike } from \"./abort-controller/AbortSignalLike\";\nimport { OperationTracingOptions } from \"./tracing/interfaces\";\n\n/**\n * A HttpHeaders collection represented as a simple JSON object.\n */\nexport type RawHttpHeaders = { [headerName: string]: string };\n\n/**\n * A HttpHeaders collection for input, represented as a simple JSON object.\n */\nexport type RawHttpHeadersInput = Record<string, string | number | boolean>;\n\n/**\n * Represents a set of HTTP headers on a request/response.\n * Header names are treated as case insensitive.\n */\nexport interface HttpHeaders extends Iterable<[string, string]> {\n /**\n * Returns the value of a specific header or undefined if not set.\n * @param name - The name of the header to retrieve.\n */\n get(name: string): string | undefined;\n /**\n * Returns true if the specified header exists.\n * @param name - The name of the header to check.\n */\n has(name: string): boolean;\n /**\n * Sets a specific header with a given value.\n * @param name - The name of the header to set.\n * @param value - The value to use for the header.\n */\n set(name: string, value: string | number | boolean): void;\n /**\n * Removes a specific header from the collection.\n * @param name - The name of the header to delete.\n */\n delete(name: string): void;\n /**\n * Accesses a raw JS object that acts as a simple map\n * of header names to values.\n */\n toJSON(options?: { preserveCase?: boolean }): RawHttpHeaders;\n}\n\n/**\n * A part of the request body in a multipart request.\n */\nexport interface BodyPart {\n /**\n * The headers for this part of the multipart request.\n */\n headers: HttpHeaders;\n\n /**\n * The body of this part of the multipart request.\n */\n body:\n | ((() => ReadableStream<Uint8Array>) | (() => NodeJS.ReadableStream))\n | ReadableStream<Uint8Array>\n | NodeJS.ReadableStream\n | Uint8Array\n | Blob;\n}\n\n/**\n * A request body consisting of multiple parts.\n */\nexport interface MultipartRequestBody {\n /**\n * The parts of the request body.\n */\n parts: BodyPart[];\n\n /**\n * The boundary separating each part of the request body.\n * If not specified, a random boundary will be generated.\n *\n * When specified, '--' will be prepended to the boundary in the request to ensure the boundary follows the specification.\n */\n boundary?: string;\n}\n\n/**\n * Types of bodies supported on the request.\n * NodeJS.ReadableStream and () =\\> NodeJS.ReadableStream is Node only.\n * Blob, ReadableStream<Uint8Array>, and () =\\> ReadableStream<Uint8Array> are browser only.\n */\nexport type RequestBodyType =\n | NodeJS.ReadableStream\n | (() => NodeJS.ReadableStream)\n | ReadableStream<Uint8Array>\n | (() => ReadableStream<Uint8Array>)\n | Blob\n | ArrayBuffer\n | ArrayBufferView\n | FormData\n | string\n | null;\n\n/**\n * An interface compatible with NodeJS's `http.Agent`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface Agent {\n /**\n * Destroy any sockets that are currently in use by the agent.\n */\n destroy(): void;\n /**\n * For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.\n */\n maxFreeSockets: number;\n /**\n * Determines how many concurrent sockets the agent can have open per origin.\n */\n maxSockets: number;\n /**\n * An object which contains queues of requests that have not yet been assigned to sockets.\n */\n requests: unknown;\n /**\n * An object which contains arrays of sockets currently in use by the agent.\n */\n sockets: unknown;\n}\n\n/**\n * Metadata about a request being made by the pipeline.\n */\nexport interface PipelineRequest {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout: number;\n\n /**\n * Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.\n * Defaults to false.\n */\n withCredentials: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId: string;\n\n /**\n * The HTTP body content (if any)\n */\n body?: RequestBodyType;\n\n /**\n * Body for a multipart request.\n */\n multipartBody?: MultipartRequestBody;\n\n /**\n * To simulate a browser form post\n */\n formData?: FormDataMap;\n\n /**\n * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.\n * When streamResponseStatusCodes contains the value Number.POSITIVE_INFINITY any status would be treated as a stream.\n */\n streamResponseStatusCodes?: Set<number>;\n\n /**\n * Proxy configuration.\n */\n proxySettings?: ProxySettings;\n\n /**\n * If the connection should not be reused.\n */\n disableKeepAlive?: boolean;\n\n /**\n * Used to abort the request later.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Tracing options to use for any created Spans.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n\n /**\n * NODEJS ONLY\n *\n * A Node-only option to provide a custom `http.Agent`/`https.Agent`.\n * Does nothing when running in the browser.\n */\n agent?: Agent;\n\n /**\n * BROWSER ONLY\n *\n * A browser only option to enable browser Streams. If this option is set and a response is a stream\n * the response will have a property `browserStream` instead of `blobBody` which will be undefined.\n *\n * Default value is false\n */\n enableBrowserStreams?: boolean;\n\n /** Settings for configuring TLS authentication */\n tlsSettings?: TlsSettings;\n}\n\n/**\n * Metadata about a response received by the pipeline.\n */\nexport interface PipelineResponse {\n /**\n * The request that generated this response.\n */\n request: PipelineRequest;\n /**\n * The HTTP status code of the response.\n */\n status: number;\n /**\n * The HTTP response headers.\n */\n headers: HttpHeaders;\n\n /**\n * The response body as text (string format)\n */\n bodyAsText?: string | null;\n\n /**\n * BROWSER ONLY\n *\n * The response body as a browser Blob.\n * Always undefined in node.js.\n */\n blobBody?: Promise<Blob>;\n\n /**\n * BROWSER ONLY\n *\n * The response body as a browser ReadableStream.\n * Always undefined in node.js.\n */\n browserStreamBody?: ReadableStream<Uint8Array>;\n\n /**\n * NODEJS ONLY\n *\n * The response body as a node.js Readable stream.\n * Always undefined in the browser.\n */\n readableStreamBody?: NodeJS.ReadableStream;\n}\n\n/**\n * A simple interface for making a pipeline request and receiving a response.\n */\nexport type SendRequest = (request: PipelineRequest) => Promise<PipelineResponse>;\n\n/**\n * The required interface for a client that makes HTTP requests\n * on behalf of a pipeline.\n */\nexport interface HttpClient {\n /**\n * The method that makes the request and returns a response.\n */\n sendRequest: SendRequest;\n}\n\n/**\n * Fired in response to upload or download progress.\n */\nexport type TransferProgressEvent = {\n /**\n * The number of bytes loaded so far.\n */\n loadedBytes: number;\n};\n\n/**\n * Supported HTTP methods to use when making requests.\n */\nexport type HttpMethods =\n | \"GET\"\n | \"PUT\"\n | \"POST\"\n | \"DELETE\"\n | \"PATCH\"\n | \"HEAD\"\n | \"OPTIONS\"\n | \"TRACE\";\n\n/**\n * Options to configure a proxy for outgoing requests (Node.js only).\n */\nexport interface ProxySettings {\n /**\n * The proxy's host address.\n */\n host: string;\n\n /**\n * The proxy host's port.\n */\n port: number;\n\n /**\n * The user name to authenticate with the proxy, if required.\n */\n username?: string;\n\n /**\n * The password to authenticate with the proxy, if required.\n */\n password?: string;\n}\n\n/**\n * Each form data entry can be a string, Blob, or a File. If you wish to pass a file with a name but do not have\n * access to the File class, you can use the createFile helper to create one.\n */\nexport type FormDataValue = string | Blob | File;\n\n/**\n * A simple object that provides form data, as if from a browser form.\n */\nexport type FormDataMap = { [key: string]: FormDataValue | FormDataValue[] };\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface PipelineRetryOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second). The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * Represents a certificate credential for authentication.\n */\nexport interface CertificateCredential {\n /**\n * Optionally override the trusted CA certificates. Default is to trust\n * the well-known CAs curated by Mozilla. Mozilla's CAs are completely\n * replaced when CAs are explicitly specified using this option.\n */\n ca?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Cert chains in PEM format. One cert chain should be provided per\n * private key. Each cert chain should consist of the PEM formatted\n * certificate for a provided private key, followed by the PEM\n * formatted intermediate certificates (if any), in order, and not\n * including the root CA (the root CA must be pre-known to the peer,\n * see ca). When providing multiple cert chains, they do not have to\n * be in the same order as their private keys in key. If the\n * intermediate certificates are not provided, the peer will not be\n * able to validate the certificate, and the handshake will fail.\n */\n cert?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Private keys in PEM format. PEM allows the option of private keys\n * being encrypted. Encrypted keys will be decrypted with\n * options.passphrase. Multiple keys using different algorithms can be\n * provided either as an array of unencrypted key strings or buffers,\n * or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n key?: string | Buffer | Array<Buffer | KeyObject> | undefined;\n /**\n * Shared passphrase used for a single private key and/or a PFX.\n */\n passphrase?: string | undefined;\n /**\n * PFX or PKCS12 encoded private key and certificate chain. pfx is an\n * alternative to providing key and cert individually. PFX is usually\n * encrypted, if it is, passphrase will be used to decrypt it. Multiple\n * PFX can be provided either as an array of unencrypted PFX buffers,\n * or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;\n}\n\n/**\n * Represents a certificate for TLS authentication.\n */\nexport interface TlsSettings {\n /**\n * Optionally override the trusted CA certificates. Default is to trust\n * the well-known CAs curated by Mozilla. Mozilla's CAs are completely\n * replaced when CAs are explicitly specified using this option.\n */\n ca?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Cert chains in PEM format. One cert chain should be provided per\n * private key. Each cert chain should consist of the PEM formatted\n * certificate for a provided private key, followed by the PEM\n * formatted intermediate certificates (if any), in order, and not\n * including the root CA (the root CA must be pre-known to the peer,\n * see ca). When providing multiple cert chains, they do not have to\n * be in the same order as their private keys in key. If the\n * intermediate certificates are not provided, the peer will not be\n * able to validate the certificate, and the handshake will fail.\n */\n cert?: string | Buffer | Array<string | Buffer> | undefined;\n /**\n * Private keys in PEM format. PEM allows the option of private keys\n * being encrypted. Encrypted keys will be decrypted with\n * options.passphrase. Multiple keys using different algorithms can be\n * provided either as an array of unencrypted key strings or buffers,\n * or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n key?: string | Buffer | Array<Buffer | KeyObject> | undefined;\n /**\n * Shared passphrase used for a single private key and/or a PFX.\n */\n passphrase?: string | undefined;\n /**\n * PFX or PKCS12 encoded private key and certificate chain. pfx is an\n * alternative to providing key and cert individually. PFX is usually\n * encrypted, if it is, passphrase will be used to decrypt it. Multiple\n * PFX can be provided either as an array of unencrypted PFX buffers,\n * or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;\n}\n\n/**\n * An interface compatible with NodeJS's `tls.KeyObject`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface KeyObject {\n /**\n * Private keys in PEM format.\n */\n pem: string | Buffer;\n /**\n * Optional passphrase.\n */\n passphrase?: string | undefined;\n}\n\n/**\n * An interface compatible with NodeJS's `tls.PxfObject`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface PxfObject {\n /**\n * PFX or PKCS12 encoded private key and certificate chain.\n */\n buf: string | Buffer;\n /**\n * Optional passphrase.\n */\n passphrase?: string | undefined;\n}\n"]}
|
|
@@ -10,6 +10,7 @@ class PipelineRequestImpl {
|
|
|
10
10
|
this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : createHttpHeaders();
|
|
11
11
|
this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
|
|
12
12
|
this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
|
|
13
|
+
this.multipartBody = options.multipartBody;
|
|
13
14
|
this.formData = options.formData;
|
|
14
15
|
this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
|
|
15
16
|
this.proxySettings = options.proxySettings;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipelineRequest.js","sourceRoot":"","sources":["../../src/pipelineRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;
|
|
1
|
+
{"version":3,"file":"pipelineRequest.js","sourceRoot":"","sources":["../../src/pipelineRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAYlC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAwG9C,MAAM,mBAAmB;IAqBvB,YAAY,OAA+B;;QACzC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,MAAA,OAAO,CAAC,OAAO,mCAAI,iBAAiB,EAAE,CAAC;QACtD,IAAI,CAAC,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,KAAK,CAAC;QACtC,IAAI,CAAC,OAAO,GAAG,MAAA,OAAO,CAAC,OAAO,mCAAI,CAAC,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,MAAA,OAAO,CAAC,gBAAgB,mCAAI,KAAK,CAAC;QAC1D,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;QACnE,IAAI,CAAC,eAAe,GAAG,MAAA,OAAO,CAAC,eAAe,mCAAI,KAAK,CAAC;QACxD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;QAC7C,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;QACjD,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACrD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,UAAU,EAAE,CAAC;QACnD,IAAI,CAAC,uBAAuB,GAAG,MAAA,OAAO,CAAC,uBAAuB,mCAAI,KAAK,CAAC;QACxE,IAAI,CAAC,oBAAoB,GAAG,MAAA,OAAO,CAAC,oBAAoB,mCAAI,KAAK,CAAC;IACpE,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAA+B;IACnE,OAAO,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n FormDataMap,\n HttpHeaders,\n HttpMethods,\n MultipartRequestBody,\n PipelineRequest,\n ProxySettings,\n RequestBodyType,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { AbortSignalLike } from \"./abort-controller/AbortSignalLike\";\nimport { randomUUID } from \"./util/uuidUtils\";\nimport { OperationTracingOptions } from \"./tracing/interfaces\";\n\n/**\n * Settings to initialize a request.\n * Almost equivalent to Partial<PipelineRequest>, but url is mandatory.\n */\nexport interface PipelineRequestOptions {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method?: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers?: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout?: number;\n\n /**\n * If credentials (cookies) should be sent along during an XHR.\n * Defaults to false.\n */\n withCredentials?: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId?: string;\n\n /**\n * The HTTP body content (if any)\n */\n body?: RequestBodyType;\n\n /**\n * Body for a multipart request.\n */\n multipartBody?: MultipartRequestBody;\n\n /**\n * To simulate a browser form post\n */\n formData?: FormDataMap;\n\n /**\n * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.\n */\n streamResponseStatusCodes?: Set<number>;\n\n /**\n * BROWSER ONLY\n *\n * A browser only option to enable use of the Streams API. If this option is set and streaming is used\n * (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of\n * `blobBody` which will be undefined.\n *\n * Default value is false\n */\n enableBrowserStreams?: boolean;\n\n /**\n * Proxy configuration.\n */\n proxySettings?: ProxySettings;\n\n /**\n * If the connection should not be reused.\n */\n disableKeepAlive?: boolean;\n\n /**\n * Used to abort the request later.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Options used to create a span when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n}\n\nclass PipelineRequestImpl implements PipelineRequest {\n public url: string;\n public method: HttpMethods;\n public headers: HttpHeaders;\n public timeout: number;\n public withCredentials: boolean;\n public body?: RequestBodyType;\n public multipartBody?: MultipartRequestBody;\n public formData?: FormDataMap;\n public streamResponseStatusCodes?: Set<number>;\n public enableBrowserStreams: boolean;\n\n public proxySettings?: ProxySettings;\n public disableKeepAlive: boolean;\n public abortSignal?: AbortSignalLike;\n public requestId: string;\n public tracingOptions?: OperationTracingOptions;\n public allowInsecureConnection?: boolean;\n public onUploadProgress?: (progress: TransferProgressEvent) => void;\n public onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n constructor(options: PipelineRequestOptions) {\n this.url = options.url;\n this.body = options.body;\n this.headers = options.headers ?? createHttpHeaders();\n this.method = options.method ?? \"GET\";\n this.timeout = options.timeout ?? 0;\n this.multipartBody = options.multipartBody;\n this.formData = options.formData;\n this.disableKeepAlive = options.disableKeepAlive ?? false;\n this.proxySettings = options.proxySettings;\n this.streamResponseStatusCodes = options.streamResponseStatusCodes;\n this.withCredentials = options.withCredentials ?? false;\n this.abortSignal = options.abortSignal;\n this.tracingOptions = options.tracingOptions;\n this.onUploadProgress = options.onUploadProgress;\n this.onDownloadProgress = options.onDownloadProgress;\n this.requestId = options.requestId || randomUUID();\n this.allowInsecureConnection = options.allowInsecureConnection ?? false;\n this.enableBrowserStreams = options.enableBrowserStreams ?? false;\n }\n}\n\n/**\n * Creates a new pipeline request with the given options.\n * This method is to allow for the easy setting of default values and not required.\n * @param options - The options to create the request with.\n */\nexport function createPipelineRequest(options: PipelineRequestOptions): PipelineRequest {\n return new PipelineRequestImpl(options);\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
|
2
2
|
// Licensed under the MIT license.
|
|
3
|
-
import
|
|
3
|
+
import { stringToUint8Array } from "../util/bytesEncoding";
|
|
4
|
+
import { createHttpHeaders } from "../httpHeaders";
|
|
4
5
|
/**
|
|
5
6
|
* The programmatic identifier of the formDataPolicy.
|
|
6
7
|
*/
|
|
@@ -16,11 +17,11 @@ export function formDataPolicy() {
|
|
|
16
17
|
const contentType = request.headers.get("Content-Type");
|
|
17
18
|
if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
|
|
18
19
|
request.body = wwwFormUrlEncode(request.formData);
|
|
19
|
-
request.formData = undefined;
|
|
20
20
|
}
|
|
21
21
|
else {
|
|
22
22
|
await prepareFormData(request.formData, request);
|
|
23
23
|
}
|
|
24
|
+
request.formData = undefined;
|
|
24
25
|
}
|
|
25
26
|
return next(request);
|
|
26
27
|
},
|
|
@@ -41,39 +42,40 @@ function wwwFormUrlEncode(formData) {
|
|
|
41
42
|
return urlSearchParams.toString();
|
|
42
43
|
}
|
|
43
44
|
async function prepareFormData(formData, request) {
|
|
44
|
-
|
|
45
|
-
for (const formKey of Object.keys(formData)) {
|
|
46
|
-
const formValue = formData[formKey];
|
|
47
|
-
if (Array.isArray(formValue)) {
|
|
48
|
-
for (const subValue of formValue) {
|
|
49
|
-
requestForm.append(formKey, subValue);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
else {
|
|
53
|
-
requestForm.append(formKey, formValue);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
request.body = requestForm;
|
|
57
|
-
request.formData = undefined;
|
|
45
|
+
// validate content type (multipart/form-data)
|
|
58
46
|
const contentType = request.headers.get("Content-Type");
|
|
59
|
-
if (contentType && contentType.
|
|
60
|
-
|
|
47
|
+
if (contentType && !contentType.startsWith("multipart/form-data")) {
|
|
48
|
+
// content type is specified and is not multipart/form-data. Exit.
|
|
49
|
+
return;
|
|
61
50
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
51
|
+
request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
|
|
52
|
+
// set body to MultipartRequestBody using content from FormDataMap
|
|
53
|
+
const parts = [];
|
|
54
|
+
for (const [fieldName, values] of Object.entries(formData)) {
|
|
55
|
+
for (const value of Array.isArray(values) ? values : [values]) {
|
|
56
|
+
if (typeof value === "string") {
|
|
57
|
+
parts.push({
|
|
58
|
+
headers: createHttpHeaders({
|
|
59
|
+
"Content-Disposition": `form-data; name="${fieldName}"`,
|
|
60
|
+
}),
|
|
61
|
+
body: stringToUint8Array(value, "utf-8"),
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
// using || instead of ?? here since if value.name is empty we should create a file name
|
|
66
|
+
const fileName = value.name || "blob";
|
|
67
|
+
const headers = createHttpHeaders();
|
|
68
|
+
headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
|
|
69
|
+
if (value.type) {
|
|
70
|
+
headers.set("Content-Type", value.type);
|
|
70
71
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
72
|
+
parts.push({
|
|
73
|
+
headers,
|
|
74
|
+
body: value,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
request.multipartBody = { parts };
|
|
77
79
|
}
|
|
78
80
|
}
|
|
79
81
|
//# sourceMappingURL=formDataPolicy.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formDataPolicy.js","sourceRoot":"","sources":["../../../src/policies/formDataPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,
|
|
1
|
+
{"version":3,"file":"formDataPolicy.js","sourceRoot":"","sources":["../../../src/policies/formDataPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAUnD;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,gBAAgB,CAAC;AAEnD;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,OAAO;QACL,IAAI,EAAE,kBAAkB;QACxB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,OAAO,CAAC,QAAQ,EAAE;gBACpB,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;gBACxD,IAAI,WAAW,IAAI,WAAW,CAAC,OAAO,CAAC,mCAAmC,CAAC,KAAK,CAAC,CAAC,EAAE;oBAClF,OAAO,CAAC,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;iBACnD;qBAAM;oBACL,MAAM,eAAe,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;iBAClD;gBAED,OAAO,C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AAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE;YAC7D,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;gBAC7B,KAAK,CAAC,IAAI,CAAC;oBACT,OAAO,EAAE,iBAAiB,CAAC;wBACzB,qBAAqB,EAAE,oBAAoB,SAAS,GAAG;qBACxD,CAAC;oBACF,IAAI,EAAE,kBAAkB,CAAC,KAAK,EAAE,OAAO,CAAC;iBACzC,CAAC,CAAC;aACJ;iBAAM;gBACL,wFAAwF;gBACxF,MAAM,QAAQ,GAAI,KAAc,CAAC,IAAI,IAAI,MAAM,CAAC;gBAChD,MAAM,OAAO,GAAG,iBAAiB,EAAE,CAAC;gBACpC,OAAO,CAAC,GAAG,CACT,qBAAqB,EACrB,oBAAoB,SAAS,gBAAgB,QAAQ,GAAG,CACzD,CAAC;gBACF,IAAI,KAAK,CAAC,IAAI,EAAE;oBACd,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;iBACzC;gBAED,KAAK,CAAC,IAAI,CAAC;oBACT,OAAO;oBACP,IAAI,EAAE,KAAK;iBACZ,CAAC,CAAC;aACJ;SACF;QAED,OAAO,CAAC,aAAa,GAAG,EAAE,KAAK,EAAE,CAAC;KACnC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { stringToUint8Array } from \"../util/bytesEncoding\";\nimport { createHttpHeaders } from \"../httpHeaders\";\nimport {\n BodyPart,\n FormDataMap,\n PipelineRequest,\n PipelineResponse,\n SendRequest,\n} from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the formDataPolicy.\n */\nexport const formDataPolicyName = \"formDataPolicy\";\n\n/**\n * A policy that encodes FormData on the request into the body.\n */\nexport function formDataPolicy(): PipelinePolicy {\n return {\n name: formDataPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (request.formData) {\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"application/x-www-form-urlencoded\") !== -1) {\n request.body = wwwFormUrlEncode(request.formData);\n } else {\n await prepareFormData(request.formData, request);\n }\n\n request.formData = undefined;\n }\n return next(request);\n },\n };\n}\n\nfunction wwwFormUrlEncode(formData: FormDataMap): string {\n const urlSearchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(formData)) {\n if (Array.isArray(value)) {\n for (const subValue of value) {\n urlSearchParams.append(key, subValue.toString());\n }\n } else {\n urlSearchParams.append(key, value.toString());\n }\n }\n return urlSearchParams.toString();\n}\n\nasync function prepareFormData(formData: FormDataMap, request: PipelineRequest): Promise<void> {\n // validate content type (multipart/form-data)\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && !contentType.startsWith(\"multipart/form-data\")) {\n // content type is specified and is not multipart/form-data. Exit.\n return;\n }\n\n request.headers.set(\"Content-Type\", contentType ?? \"multipart/form-data\");\n\n // set body to MultipartRequestBody using content from FormDataMap\n const parts: BodyPart[] = [];\n\n for (const [fieldName, values] of Object.entries(formData)) {\n for (const value of Array.isArray(values) ? values : [values]) {\n if (typeof value === \"string\") {\n parts.push({\n headers: createHttpHeaders({\n \"Content-Disposition\": `form-data; name=\"${fieldName}\"`,\n }),\n body: stringToUint8Array(value, \"utf-8\"),\n });\n } else {\n // using || instead of ?? here since if value.name is empty we should create a file name\n const fileName = (value as File).name || \"blob\";\n const headers = createHttpHeaders();\n headers.set(\n \"Content-Disposition\",\n `form-data; name=\"${fieldName}\"; filename=\"${fileName}\"`\n );\n if (value.type) {\n headers.set(\"Content-Type\", value.type);\n }\n\n parts.push({\n headers,\n body: value,\n });\n }\n }\n\n request.multipartBody = { parts };\n }\n}\n"]}
|