open ai api

This commit is contained in:
2025-09-16 09:38:01 +08:00
parent c71c3ab417
commit 5f9a2bc78c
7168 changed files with 352600 additions and 209 deletions

View File

@@ -0,0 +1,3 @@
export declare const SDK_VERSION: string;
export declare const DEFAULT_RETRY_POLICY_COUNT = 3;
//# sourceMappingURL=constants.d.ts.map

View File

@@ -0,0 +1,5 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export const SDK_VERSION = "1.22.1";
export const DEFAULT_RETRY_POLICY_COUNT = 3;
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,CAAC,MAAM,WAAW,GAAW,QAAQ,CAAC;AAE5C,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport const SDK_VERSION: string = \"1.22.1\";\n\nexport const DEFAULT_RETRY_POLICY_COUNT = 3;\n"]}

View File

@@ -0,0 +1,60 @@
import { type LogPolicyOptions } from "./policies/logPolicy.js";
import { type Pipeline } from "./pipeline.js";
import type { Agent, PipelineRetryOptions, ProxySettings, TlsSettings } from "./interfaces.js";
import { type RedirectPolicyOptions } from "./policies/redirectPolicy.js";
import { type UserAgentPolicyOptions } from "./policies/userAgentPolicy.js";
/**
* Defines options that are used to configure the HTTP pipeline for
* an SDK client.
*/
export interface PipelineOptions {
/**
* Options that control how to retry failed requests.
*/
retryOptions?: PipelineRetryOptions;
/**
* Options to configure a proxy for outgoing requests.
*/
proxyOptions?: ProxySettings;
/** Options for configuring Agent instance for outgoing requests */
agent?: Agent;
/** Options for configuring TLS authentication */
tlsOptions?: TlsSettings;
/**
* Options for how redirect responses are handled.
*/
redirectOptions?: RedirectPolicyOptions;
/**
* Options for adding user agent details to outgoing requests.
*/
userAgentOptions?: UserAgentPolicyOptions;
/**
* Options for setting common telemetry and tracing info to outgoing requests.
*/
telemetryOptions?: TelemetryOptions;
}
/**
* Defines options that are used to configure common telemetry and tracing info
*/
export interface TelemetryOptions {
/**
* The name of the header to pass the request ID to.
*/
clientRequestIdHeaderName?: string;
}
/**
* Defines options that are used to configure internal options of
* the HTTP pipeline for an SDK client.
*/
export interface InternalPipelineOptions extends PipelineOptions {
/**
* Options to configure request/response logging.
*/
loggingOptions?: LogPolicyOptions;
}
/**
* Create a new pipeline with a default set of customizable policies.
* @param options - Options to configure a custom pipeline.
*/
export declare function createPipelineFromOptions(options: InternalPipelineOptions): Pipeline;
//# sourceMappingURL=createPipelineFromOptions.d.ts.map

View File

@@ -0,0 +1,54 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { logPolicy } from "./policies/logPolicy.js";
import { createEmptyPipeline } from "./pipeline.js";
import { redirectPolicy } from "./policies/redirectPolicy.js";
import { userAgentPolicy } from "./policies/userAgentPolicy.js";
import { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js";
import { decompressResponsePolicy } from "./policies/decompressResponsePolicy.js";
import { defaultRetryPolicy } from "./policies/defaultRetryPolicy.js";
import { formDataPolicy } from "./policies/formDataPolicy.js";
import { isNodeLike } from "@azure/core-util";
import { proxyPolicy } from "./policies/proxyPolicy.js";
import { setClientRequestIdPolicy } from "./policies/setClientRequestIdPolicy.js";
import { agentPolicy } from "./policies/agentPolicy.js";
import { tlsPolicy } from "./policies/tlsPolicy.js";
import { tracingPolicy } from "./policies/tracingPolicy.js";
import { wrapAbortSignalLikePolicy } from "./policies/wrapAbortSignalLikePolicy.js";
/**
* Create a new pipeline with a default set of customizable policies.
* @param options - Options to configure a custom pipeline.
*/
export function createPipelineFromOptions(options) {
const pipeline = createEmptyPipeline();
if (isNodeLike) {
if (options.agent) {
pipeline.addPolicy(agentPolicy(options.agent));
}
if (options.tlsOptions) {
pipeline.addPolicy(tlsPolicy(options.tlsOptions));
}
pipeline.addPolicy(proxyPolicy(options.proxyOptions));
pipeline.addPolicy(decompressResponsePolicy());
}
pipeline.addPolicy(wrapAbortSignalLikePolicy());
pipeline.addPolicy(formDataPolicy(), { beforePolicies: [multipartPolicyName] });
pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));
pipeline.addPolicy(setClientRequestIdPolicy(options.telemetryOptions?.clientRequestIdHeaderName));
// The multipart policy is added after policies with no phase, so that
// policies can be added between it and formDataPolicy to modify
// properties (e.g., making the boundary constant in recorded tests).
pipeline.addPolicy(multipartPolicy(), { afterPhase: "Deserialize" });
pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
pipeline.addPolicy(tracingPolicy({ ...options.userAgentOptions, ...options.loggingOptions }), {
afterPhase: "Retry",
});
if (isNodeLike) {
// Both XHR and Fetch expect to handle redirects automatically,
// so only include this policy when we're in Node.
pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
}
pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: "Sign" });
return pipeline;
}
//# sourceMappingURL=createPipelineFromOptions.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import type { HttpClient } from "./interfaces.js";
/**
* Create the correct HttpClient for the current environment.
*/
export declare function createDefaultHttpClient(): HttpClient;
//# sourceMappingURL=defaultHttpClient.d.ts.map

View File

@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createDefaultHttpClient as tspCreateDefaultHttpClient } from "@typespec/ts-http-runtime";
import { wrapAbortSignalLike } from "./util/wrapAbortSignal.js";
/**
* Create the correct HttpClient for the current environment.
*/
export function createDefaultHttpClient() {
const client = tspCreateDefaultHttpClient();
return {
async sendRequest(request) {
// we wrap any AbortSignalLike here since the TypeSpec runtime expects a native AbortSignal.
// 99% of the time, this should be a no-op since a native AbortSignal is passed in.
const { abortSignal, cleanup } = request.abortSignal
? wrapAbortSignalLike(request.abortSignal)
: {};
try {
// eslint-disable-next-line no-param-reassign
request.abortSignal = abortSignal;
return await client.sendRequest(request);
}
finally {
cleanup?.();
}
},
};
}
//# sourceMappingURL=defaultHttpClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"defaultHttpClient.js","sourceRoot":"","sources":["../../src/defaultHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,IAAI,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AAClG,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAGhE;;GAEG;AACH,MAAM,UAAU,uBAAuB;IACrC,MAAM,MAAM,GAAG,0BAA0B,EAAE,CAAC;IAC5C,OAAO;QACL,KAAK,CAAC,WAAW,CAAC,OAAO;YACvB,4FAA4F;YAC5F,mFAAmF;YACnF,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,WAAW;gBAClD,CAAC,CAAC,mBAAmB,CAAC,OAAO,CAAC,WAAW,CAAC;gBAC1C,CAAC,CAAC,EAAE,CAAC;YACP,IAAI,CAAC;gBACH,6CAA6C;gBAC7C,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC;gBAClC,OAAO,MAAM,MAAM,CAAC,WAAW,CAAC,OAA6B,CAAC,CAAC;YACjE,CAAC;oBAAS,CAAC;gBACT,OAAO,EAAE,EAAE,CAAC;YACd,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { HttpClient } from \"./interfaces.js\";\nimport { createDefaultHttpClient as tspCreateDefaultHttpClient } from \"@typespec/ts-http-runtime\";\nimport { wrapAbortSignalLike } from \"./util/wrapAbortSignal.js\";\nimport { type PipelineRequest as TspPipelineRequest } from \"@typespec/ts-http-runtime\";\n\n/**\n * Create the correct HttpClient for the current environment.\n */\nexport function createDefaultHttpClient(): HttpClient {\n const client = tspCreateDefaultHttpClient();\n return {\n async sendRequest(request) {\n // we wrap any AbortSignalLike here since the TypeSpec runtime expects a native AbortSignal.\n // 99% of the time, this should be a no-op since a native AbortSignal is passed in.\n const { abortSignal, cleanup } = request.abortSignal\n ? wrapAbortSignalLike(request.abortSignal)\n : {};\n try {\n // eslint-disable-next-line no-param-reassign\n request.abortSignal = abortSignal;\n return await client.sendRequest(request as TspPipelineRequest);\n } finally {\n cleanup?.();\n }\n },\n };\n}\n"]}

View File

@@ -0,0 +1,7 @@
import type { HttpHeaders, RawHttpHeadersInput } from "./interfaces.js";
/**
* Creates an object that satisfies the `HttpHeaders` interface.
* @param rawHeaders - A simple object representing initial headers
*/
export declare function createHttpHeaders(rawHeaders?: RawHttpHeadersInput): HttpHeaders;
//# sourceMappingURL=httpHeaders.d.ts.map

View File

@@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createHttpHeaders as tspCreateHttpHeaders } from "@typespec/ts-http-runtime";
/**
* Creates an object that satisfies the `HttpHeaders` interface.
* @param rawHeaders - A simple object representing initial headers
*/
export function createHttpHeaders(rawHeaders) {
return tspCreateHttpHeaders(rawHeaders);
}
//# sourceMappingURL=httpHeaders.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"httpHeaders.js","sourceRoot":"","sources":["../../src/httpHeaders.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,iBAAiB,IAAI,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEtF;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAgC;IAChE,OAAO,oBAAoB,CAAC,UAAU,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { HttpHeaders, RawHttpHeadersInput } from \"./interfaces.js\";\n\nimport { createHttpHeaders as tspCreateHttpHeaders } from \"@typespec/ts-http-runtime\";\n\n/**\n * Creates an object that satisfies the `HttpHeaders` interface.\n * @param rawHeaders - A simple object representing initial headers\n */\nexport function createHttpHeaders(rawHeaders?: RawHttpHeadersInput): HttpHeaders {\n return tspCreateHttpHeaders(rawHeaders);\n}\n"]}

View File

@@ -0,0 +1,41 @@
declare global {
interface FormData {
}
interface Blob {
}
interface File {
}
interface ReadableStream<R = any> {
}
interface TransformStream<I = any, O = any> {
}
}
export type { HttpMethods } from "@azure/core-util";
export type { Agent, BodyPart, FormDataMap, FormDataValue, HttpClient, HttpHeaders, KeyObject, MultipartRequestBody, PipelineRequest, PipelineResponse, PipelineRetryOptions, ProxySettings, PxfObject, RawHttpHeaders, RawHttpHeadersInput, RequestBodyType, SendRequest, TlsSettings, TransferProgressEvent, } from "./interfaces.js";
export { type AddPolicyOptions as AddPipelineOptions, type PipelinePhase, type PipelinePolicy, type Pipeline, createEmptyPipeline, } from "./pipeline.js";
export { createPipelineFromOptions, type TelemetryOptions, type InternalPipelineOptions, type PipelineOptions, } from "./createPipelineFromOptions.js";
export { createDefaultHttpClient } from "./defaultHttpClient.js";
export { createHttpHeaders } from "./httpHeaders.js";
export { createPipelineRequest, type PipelineRequestOptions } from "./pipelineRequest.js";
export { RestError, type RestErrorOptions, type RestErrorConstructor, isRestError, } from "./restError.js";
export { decompressResponsePolicy, decompressResponsePolicyName, } from "./policies/decompressResponsePolicy.js";
export { exponentialRetryPolicy, type ExponentialRetryPolicyOptions, exponentialRetryPolicyName, } from "./policies/exponentialRetryPolicy.js";
export { setClientRequestIdPolicy, setClientRequestIdPolicyName, } from "./policies/setClientRequestIdPolicy.js";
export { logPolicy, logPolicyName, type LogPolicyOptions } from "./policies/logPolicy.js";
export { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js";
export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./policies/proxyPolicy.js";
export { redirectPolicy, redirectPolicyName, type RedirectPolicyOptions, } from "./policies/redirectPolicy.js";
export { systemErrorRetryPolicy, type SystemErrorRetryPolicyOptions, systemErrorRetryPolicyName, } from "./policies/systemErrorRetryPolicy.js";
export { throttlingRetryPolicy, throttlingRetryPolicyName, type ThrottlingRetryPolicyOptions, } from "./policies/throttlingRetryPolicy.js";
export { retryPolicy, type RetryPolicyOptions, type RetryStrategy, type RetryInformation, type RetryModifiers, } from "./policies/retryPolicy.js";
export { tracingPolicy, tracingPolicyName, type TracingPolicyOptions, } from "./policies/tracingPolicy.js";
export { defaultRetryPolicy, type DefaultRetryPolicyOptions, } from "./policies/defaultRetryPolicy.js";
export { userAgentPolicy, userAgentPolicyName, type UserAgentPolicyOptions, } from "./policies/userAgentPolicy.js";
export { tlsPolicy, tlsPolicyName } from "./policies/tlsPolicy.js";
export { formDataPolicy, formDataPolicyName } from "./policies/formDataPolicy.js";
export { bearerTokenAuthenticationPolicy, type BearerTokenAuthenticationPolicyOptions, bearerTokenAuthenticationPolicyName, type ChallengeCallbacks, type AuthorizeRequestOptions, type AuthorizeRequestOnChallengeOptions, } from "./policies/bearerTokenAuthenticationPolicy.js";
export { ndJsonPolicy, ndJsonPolicyName } from "./policies/ndJsonPolicy.js";
export { auxiliaryAuthenticationHeaderPolicy, type AuxiliaryAuthenticationHeaderPolicyOptions, auxiliaryAuthenticationHeaderPolicyName, } from "./policies/auxiliaryAuthenticationHeaderPolicy.js";
export { agentPolicy, agentPolicyName } from "./policies/agentPolicy.js";
export { createFile, createFileFromStream, type CreateFileOptions, type CreateFileFromStreamOptions, } from "./util/file.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,29 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export { createEmptyPipeline, } from "./pipeline.js";
export { createPipelineFromOptions, } from "./createPipelineFromOptions.js";
export { createDefaultHttpClient } from "./defaultHttpClient.js";
export { createHttpHeaders } from "./httpHeaders.js";
export { createPipelineRequest } from "./pipelineRequest.js";
export { RestError, isRestError, } from "./restError.js";
export { decompressResponsePolicy, decompressResponsePolicyName, } from "./policies/decompressResponsePolicy.js";
export { exponentialRetryPolicy, exponentialRetryPolicyName, } from "./policies/exponentialRetryPolicy.js";
export { setClientRequestIdPolicy, setClientRequestIdPolicyName, } from "./policies/setClientRequestIdPolicy.js";
export { logPolicy, logPolicyName } from "./policies/logPolicy.js";
export { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js";
export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./policies/proxyPolicy.js";
export { redirectPolicy, redirectPolicyName, } from "./policies/redirectPolicy.js";
export { systemErrorRetryPolicy, systemErrorRetryPolicyName, } from "./policies/systemErrorRetryPolicy.js";
export { throttlingRetryPolicy, throttlingRetryPolicyName, } from "./policies/throttlingRetryPolicy.js";
export { retryPolicy, } from "./policies/retryPolicy.js";
export { tracingPolicy, tracingPolicyName, } from "./policies/tracingPolicy.js";
export { defaultRetryPolicy, } from "./policies/defaultRetryPolicy.js";
export { userAgentPolicy, userAgentPolicyName, } from "./policies/userAgentPolicy.js";
export { tlsPolicy, tlsPolicyName } from "./policies/tlsPolicy.js";
export { formDataPolicy, formDataPolicyName } from "./policies/formDataPolicy.js";
export { bearerTokenAuthenticationPolicy, bearerTokenAuthenticationPolicyName, } from "./policies/bearerTokenAuthenticationPolicy.js";
export { ndJsonPolicy, ndJsonPolicyName } from "./policies/ndJsonPolicy.js";
export { auxiliaryAuthenticationHeaderPolicy, auxiliaryAuthenticationHeaderPolicyName, } from "./policies/auxiliaryAuthenticationHeaderPolicy.js";
export { agentPolicy, agentPolicyName } from "./policies/agentPolicy.js";
export { createFile, createFileFromStream, } from "./util/file.js";
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,454 @@
import type { AbortSignalLike } from "@azure/abort-controller";
import type { OperationTracingOptions } from "@azure/core-tracing";
import type { HttpMethods } from "@azure/core-util";
/**
* A HttpHeaders collection represented as a simple JSON object.
*/
export type RawHttpHeaders = {
[headerName: string]: string;
};
/**
* A HttpHeaders collection for input, represented as a simple JSON object.
*/
export type RawHttpHeadersInput = Record<string, string | number | boolean>;
/**
* Represents a set of HTTP headers on a request/response.
* Header names are treated as case insensitive.
*/
export interface HttpHeaders extends Iterable<[string, string]> {
/**
* Returns the value of a specific header or undefined if not set.
* @param name - The name of the header to retrieve.
*/
get(name: string): string | undefined;
/**
* Returns true if the specified header exists.
* @param name - The name of the header to check.
*/
has(name: string): boolean;
/**
* Sets a specific header with a given value.
* @param name - The name of the header to set.
* @param value - The value to use for the header.
*/
set(name: string, value: string | number | boolean): void;
/**
* Removes a specific header from the collection.
* @param name - The name of the header to delete.
*/
delete(name: string): void;
/**
* Accesses a raw JS object that acts as a simple map
* of header names to values.
*/
toJSON(options?: {
preserveCase?: boolean;
}): RawHttpHeaders;
}
/**
* A part of the request body in a multipart request.
*/
export interface BodyPart {
/**
* The headers for this part of the multipart request.
*/
headers: HttpHeaders;
/**
* The body of this part of the multipart request.
*/
body: ((() => ReadableStream<Uint8Array>) | (() => NodeJS.ReadableStream)) | ReadableStream<Uint8Array> | NodeJS.ReadableStream | Uint8Array | Blob;
}
/**
* A request body consisting of multiple parts.
*/
export interface MultipartRequestBody {
/**
* The parts of the request body.
*/
parts: BodyPart[];
/**
* The boundary separating each part of the request body.
* If not specified, a random boundary will be generated.
*
* When specified, '--' will be prepended to the boundary in the request to ensure the boundary follows the specification.
*/
boundary?: string;
}
/**
* Types of bodies supported on the request.
* NodeJS.ReadableStream and () =\> NodeJS.ReadableStream is Node only.
* Blob, ReadableStream<Uint8Array>, and () =\> ReadableStream<Uint8Array> are browser only.
*/
export type RequestBodyType = NodeJS.ReadableStream | (() => NodeJS.ReadableStream) | ReadableStream<Uint8Array> | (() => ReadableStream<Uint8Array>) | Blob | ArrayBuffer | ArrayBufferView | FormData | string | null;
/**
* An interface compatible with NodeJS's `http.Agent`.
* We want to avoid publicly re-exporting the actual interface,
* since it might vary across runtime versions.
*/
export interface Agent {
/**
* Destroy any sockets that are currently in use by the agent.
*/
destroy(): void;
/**
* For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.
*/
maxFreeSockets: number;
/**
* Determines how many concurrent sockets the agent can have open per origin.
*/
maxSockets: number;
/**
* An object which contains queues of requests that have not yet been assigned to sockets.
*/
requests: unknown;
/**
* An object which contains arrays of sockets currently in use by the agent.
*/
sockets: unknown;
}
/**
* Metadata about a request being made by the pipeline.
*/
export interface PipelineRequest {
/**
* The URL to make the request to.
*/
url: string;
/**
* The HTTP method to use when making the request.
*/
method: HttpMethods;
/**
* The HTTP headers to use when making the request.
*/
headers: HttpHeaders;
/**
* The number of milliseconds a request can take before automatically being terminated.
* If the request is terminated, an `AbortError` is thrown.
* Defaults to 0, which disables the timeout.
*/
timeout: number;
/**
* Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.
* Defaults to false.
*/
withCredentials: boolean;
/**
* A unique identifier for the request. Used for logging and tracing.
*/
requestId: string;
/**
* The HTTP body content (if any)
*/
body?: RequestBodyType;
/**
* Body for a multipart request.
*/
multipartBody?: MultipartRequestBody;
/**
* To simulate a browser form post
*/
formData?: FormDataMap;
/**
* A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.
* When streamResponseStatusCodes contains the value Number.POSITIVE_INFINITY any status would be treated as a stream.
*/
streamResponseStatusCodes?: Set<number>;
/**
* Proxy configuration.
*/
proxySettings?: ProxySettings;
/**
* If the connection should not be reused.
*/
disableKeepAlive?: boolean;
/**
* Used to abort the request later.
*/
abortSignal?: AbortSignalLike;
/**
* Tracing options to use for any created Spans.
*/
tracingOptions?: OperationTracingOptions;
/**
* Callback which fires upon upload progress.
*/
onUploadProgress?: (progress: TransferProgressEvent) => void;
/** Callback which fires upon download progress. */
onDownloadProgress?: (progress: TransferProgressEvent) => void;
/** Set to true if the request is sent over HTTP instead of HTTPS */
allowInsecureConnection?: boolean;
/**
* NODEJS ONLY
*
* A Node-only option to provide a custom `http.Agent`/`https.Agent`.
* Does nothing when running in the browser.
*/
agent?: Agent;
/**
* BROWSER ONLY
*
* A browser only option to enable browser Streams. If this option is set and a response is a stream
* the response will have a property `browserStream` instead of `blobBody` which will be undefined.
*
* Default value is false
*/
enableBrowserStreams?: boolean;
/** Settings for configuring TLS authentication */
tlsSettings?: TlsSettings;
/**
* Additional options to set on the request. This provides a way to override
* existing ones or provide request properties that are not declared.
*
* For possible valid properties, see
* - NodeJS https.request options: https://nodejs.org/api/http.html#httprequestoptions-callback
* - Browser RequestInit: https://developer.mozilla.org/en-US/docs/Web/API/RequestInit
*
* WARNING: Options specified here will override any properties of same names when request is sent by {@link HttpClient}.
*/
requestOverrides?: Record<string, unknown>;
}
/**
* Metadata about a response received by the pipeline.
*/
export interface PipelineResponse {
/**
* The request that generated this response.
*/
request: PipelineRequest;
/**
* The HTTP status code of the response.
*/
status: number;
/**
* The HTTP response headers.
*/
headers: HttpHeaders;
/**
* The response body as text (string format)
*/
bodyAsText?: string | null;
/**
* BROWSER ONLY
*
* The response body as a browser Blob.
* Always undefined in node.js.
*/
blobBody?: Promise<Blob>;
/**
* BROWSER ONLY
*
* The response body as a browser ReadableStream.
* Always undefined in node.js.
*/
browserStreamBody?: ReadableStream<Uint8Array>;
/**
* NODEJS ONLY
*
* The response body as a node.js Readable stream.
* Always undefined in the browser.
*/
readableStreamBody?: NodeJS.ReadableStream;
}
/**
* A simple interface for making a pipeline request and receiving a response.
*/
export type SendRequest = (request: PipelineRequest) => Promise<PipelineResponse>;
/**
* The required interface for a client that makes HTTP requests
* on behalf of a pipeline.
*/
export interface HttpClient {
/**
* The method that makes the request and returns a response.
*/
sendRequest: SendRequest;
}
/**
* Fired in response to upload or download progress.
*/
export type TransferProgressEvent = {
/**
* The number of bytes loaded so far.
*/
loadedBytes: number;
};
/**
* Options to configure a proxy for outgoing requests (Node.js only).
*/
export interface ProxySettings {
/**
* The proxy's host address.
* Must include the protocol (e.g., http:// or https://).
*/
host: string;
/**
* The proxy host's port.
*/
port: number;
/**
* The user name to authenticate with the proxy, if required.
*/
username?: string;
/**
* The password to authenticate with the proxy, if required.
*/
password?: string;
}
/**
* 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
* access to the File class, you can use the createFile helper to create one.
*/
export type FormDataValue = string | Blob | File;
/**
* A simple object that provides form data, as if from a browser form.
*/
export type FormDataMap = {
[key: string]: FormDataValue | FormDataValue[];
};
/**
* Options that control how to retry failed requests.
*/
export interface PipelineRetryOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
/**
* The amount of delay in milliseconds between retry attempts. Defaults to 1000
* (1 second). The delay increases exponentially with each retry up to a maximum
* specified by maxRetryDelayInMs.
*/
retryDelayInMs?: number;
/**
* The maximum delay in milliseconds allowed before retrying an operation. Defaults
* to 64000 (64 seconds).
*/
maxRetryDelayInMs?: number;
}
/**
* Represents a certificate credential for authentication.
*/
export interface CertificateCredential {
/**
* Optionally override the trusted CA certificates. Default is to trust
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
* certificate for a provided private key, followed by the PEM
* formatted intermediate certificates (if any), in order, and not
* including the root CA (the root CA must be pre-known to the peer,
* see ca). When providing multiple cert chains, they do not have to
* be in the same order as their private keys in key. If the
* intermediate certificates are not provided, the peer will not be
* able to validate the certificate, and the handshake will fail.
*/
cert?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
* being encrypted. Encrypted keys will be decrypted with
* options.passphrase. Multiple keys using different algorithms can be
* provided either as an array of unencrypted key strings or buffers,
* or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
key?: string | Buffer | Array<Buffer | KeyObject> | undefined;
/**
* Shared passphrase used for a single private key and/or a PFX.
*/
passphrase?: string | undefined;
/**
* PFX or PKCS12 encoded private key and certificate chain. pfx is an
* alternative to providing key and cert individually. PFX is usually
* encrypted, if it is, passphrase will be used to decrypt it. Multiple
* PFX can be provided either as an array of unencrypted PFX buffers,
* or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
}
/**
* Represents a certificate for TLS authentication.
*/
export interface TlsSettings {
/**
* Optionally override the trusted CA certificates. Default is to trust
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
* certificate for a provided private key, followed by the PEM
* formatted intermediate certificates (if any), in order, and not
* including the root CA (the root CA must be pre-known to the peer,
* see ca). When providing multiple cert chains, they do not have to
* be in the same order as their private keys in key. If the
* intermediate certificates are not provided, the peer will not be
* able to validate the certificate, and the handshake will fail.
*/
cert?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
* being encrypted. Encrypted keys will be decrypted with
* options.passphrase. Multiple keys using different algorithms can be
* provided either as an array of unencrypted key strings or buffers,
* or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
key?: string | Buffer | Array<Buffer | KeyObject> | undefined;
/**
* Shared passphrase used for a single private key and/or a PFX.
*/
passphrase?: string | undefined;
/**
* PFX or PKCS12 encoded private key and certificate chain. pfx is an
* alternative to providing key and cert individually. PFX is usually
* encrypted, if it is, passphrase will be used to decrypt it. Multiple
* PFX can be provided either as an array of unencrypted PFX buffers,
* or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
}
/**
* An interface compatible with NodeJS's `tls.KeyObject`.
* We want to avoid publicly re-exporting the actual interface,
* since it might vary across runtime versions.
*/
export interface KeyObject {
/**
* Private keys in PEM format.
*/
pem: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
/**
* An interface compatible with NodeJS's `tls.PxfObject`.
* We want to avoid publicly re-exporting the actual interface,
* since it might vary across runtime versions.
*/
export interface PxfObject {
/**
* PFX or PKCS12 encoded private key and certificate chain.
*/
buf: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
//# sourceMappingURL=interfaces.d.ts.map

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=interfaces.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export declare const logger: import("@azure/logger").AzureLogger;
//# sourceMappingURL=log.d.ts.map

View File

@@ -0,0 +1,5 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createClientLogger } from "@azure/logger";
export const logger = createClientLogger("core-rest-pipeline");
//# sourceMappingURL=log.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"log.js","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,oBAAoB,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { createClientLogger } from \"@azure/logger\";\nexport const logger = createClientLogger(\"core-rest-pipeline\");\n"]}

View File

@@ -0,0 +1,3 @@
{
"type": "module"
}

View File

@@ -0,0 +1,93 @@
import type { HttpClient, PipelineRequest, PipelineResponse, SendRequest } from "./interfaces.js";
/**
* Policies are executed in phases.
* The execution order is:
* 1. Serialize Phase
* 2. Policies not in a phase
* 3. Deserialize Phase
* 4. Retry Phase
* 5. Sign Phase
*/
export type PipelinePhase = "Deserialize" | "Serialize" | "Retry" | "Sign";
/**
* Options when adding a policy to the pipeline.
* Used to express dependencies on other policies.
*/
export interface AddPolicyOptions {
/**
* Policies that this policy must come before.
*/
beforePolicies?: string[];
/**
* Policies that this policy must come after.
*/
afterPolicies?: string[];
/**
* The phase that this policy must come after.
*/
afterPhase?: PipelinePhase;
/**
* The phase this policy belongs to.
*/
phase?: PipelinePhase;
}
/**
* A pipeline policy manipulates a request as it travels through the pipeline.
* It is conceptually a middleware that is allowed to modify the request before
* it is made as well as the response when it is received.
*/
export interface PipelinePolicy {
/**
* The policy name. Must be a unique string in the pipeline.
*/
name: string;
/**
* The main method to implement that manipulates a request/response.
* @param request - The request being performed.
* @param next - The next policy in the pipeline. Must be called to continue the pipeline.
*/
sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse>;
}
/**
* Represents a pipeline for making a HTTP request to a URL.
* Pipelines can have multiple policies to manage manipulating each request
* before and after it is made to the server.
*/
export interface Pipeline {
/**
* Add a new policy to the pipeline.
* @param policy - A policy that manipulates a request.
* @param options - A set of options for when the policy should run.
*/
addPolicy(policy: PipelinePolicy, options?: AddPolicyOptions): void;
/**
* Remove a policy from the pipeline.
* @param options - Options that let you specify which policies to remove.
*/
removePolicy(options: {
name?: string;
phase?: PipelinePhase;
}): PipelinePolicy[];
/**
* Uses the pipeline to make a HTTP request.
* @param httpClient - The HttpClient that actually performs the request.
* @param request - The request to be made.
*/
sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise<PipelineResponse>;
/**
* Returns the current set of policies in the pipeline in the order in which
* they will be applied to the request. Later in the list is closer to when
* the request is performed.
*/
getOrderedPolicies(): PipelinePolicy[];
/**
* Duplicates this pipeline to allow for modifying an existing one without mutating it.
*/
clone(): Pipeline;
}
/**
* Creates a totally empty pipeline.
* Useful for testing or creating a custom one.
*/
export declare function createEmptyPipeline(): Pipeline;
//# sourceMappingURL=pipeline.d.ts.map

View File

@@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createEmptyPipeline as tspCreateEmptyPipeline } from "@typespec/ts-http-runtime";
/**
* Creates a totally empty pipeline.
* Useful for testing or creating a custom one.
*/
export function createEmptyPipeline() {
return tspCreateEmptyPipeline();
}
//# sourceMappingURL=pipeline.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/pipeline.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,mBAAmB,IAAI,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAyF1F;;;GAGG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,sBAAsB,EAAc,CAAC;AAC9C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { HttpClient, PipelineRequest, PipelineResponse, SendRequest } from \"./interfaces.js\";\nimport { createEmptyPipeline as tspCreateEmptyPipeline } from \"@typespec/ts-http-runtime\";\n\n/**\n * Policies are executed in phases.\n * The execution order is:\n * 1. Serialize Phase\n * 2. Policies not in a phase\n * 3. Deserialize Phase\n * 4. Retry Phase\n * 5. Sign Phase\n */\nexport type PipelinePhase = \"Deserialize\" | \"Serialize\" | \"Retry\" | \"Sign\";\n\n/**\n * Options when adding a policy to the pipeline.\n * Used to express dependencies on other policies.\n */\nexport interface AddPolicyOptions {\n /**\n * Policies that this policy must come before.\n */\n beforePolicies?: string[];\n /**\n * Policies that this policy must come after.\n */\n afterPolicies?: string[];\n /**\n * The phase that this policy must come after.\n */\n afterPhase?: PipelinePhase;\n /**\n * The phase this policy belongs to.\n */\n phase?: PipelinePhase;\n}\n\n/**\n * A pipeline policy manipulates a request as it travels through the pipeline.\n * It is conceptually a middleware that is allowed to modify the request before\n * it is made as well as the response when it is received.\n */\nexport interface PipelinePolicy {\n /**\n * The policy name. Must be a unique string in the pipeline.\n */\n name: string;\n /**\n * The main method to implement that manipulates a request/response.\n * @param request - The request being performed.\n * @param next - The next policy in the pipeline. Must be called to continue the pipeline.\n */\n sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse>;\n}\n\n/**\n * Represents a pipeline for making a HTTP request to a URL.\n * Pipelines can have multiple policies to manage manipulating each request\n * before and after it is made to the server.\n */\nexport interface Pipeline {\n /**\n * Add a new policy to the pipeline.\n * @param policy - A policy that manipulates a request.\n * @param options - A set of options for when the policy should run.\n */\n addPolicy(policy: PipelinePolicy, options?: AddPolicyOptions): void;\n /**\n * Remove a policy from the pipeline.\n * @param options - Options that let you specify which policies to remove.\n */\n removePolicy(options: { name?: string; phase?: PipelinePhase }): PipelinePolicy[];\n /**\n * Uses the pipeline to make a HTTP request.\n * @param httpClient - The HttpClient that actually performs the request.\n * @param request - The request to be made.\n */\n sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise<PipelineResponse>;\n /**\n * Returns the current set of policies in the pipeline in the order in which\n * they will be applied to the request. Later in the list is closer to when\n * the request is performed.\n */\n getOrderedPolicies(): PipelinePolicy[];\n /**\n * Duplicates this pipeline to allow for modifying an existing one without mutating it.\n */\n clone(): Pipeline;\n}\n\n/**\n * Creates a totally empty pipeline.\n * Useful for testing or creating a custom one.\n */\nexport function createEmptyPipeline(): Pipeline {\n return tspCreateEmptyPipeline() as Pipeline;\n}\n"]}

View File

@@ -0,0 +1,116 @@
import type { Agent, FormDataMap, HttpHeaders, MultipartRequestBody, PipelineRequest, ProxySettings, RequestBodyType, TlsSettings, TransferProgressEvent } from "./interfaces.js";
import type { AbortSignalLike } from "@azure/abort-controller";
import type { OperationTracingOptions } from "@azure/core-tracing";
import type { HttpMethods } from "@azure/core-util";
/**
* Settings to initialize a request.
* Almost equivalent to Partial<PipelineRequest>, but url is mandatory.
*/
export interface PipelineRequestOptions {
/**
* The URL to make the request to.
*/
url: string;
/**
* The HTTP method to use when making the request.
*/
method?: HttpMethods;
/**
* The HTTP headers to use when making the request.
*/
headers?: HttpHeaders;
/**
* The number of milliseconds a request can take before automatically being terminated.
* If the request is terminated, an `AbortError` is thrown.
* Defaults to 0, which disables the timeout.
*/
timeout?: number;
/**
* If credentials (cookies) should be sent along during an XHR.
* Defaults to false.
*/
withCredentials?: boolean;
/**
* A unique identifier for the request. Used for logging and tracing.
*/
requestId?: string;
/**
* The HTTP body content (if any)
*/
body?: RequestBodyType;
/**
* Body for a multipart request.
*/
multipartBody?: MultipartRequestBody;
/**
* To simulate a browser form post
*/
formData?: FormDataMap;
/**
* A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.
*/
streamResponseStatusCodes?: Set<number>;
/**
* NODEJS ONLY
*
* A Node-only option to provide a custom `http.Agent`/`https.Agent`.
* NOTE: usually this should be one instance shared by multiple requests so that the underlying
* connection to the service can be reused.
* Does nothing when running in the browser.
*/
agent?: Agent;
/**
* BROWSER ONLY
*
* A browser only option to enable use of the Streams API. If this option is set and streaming is used
* (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of
* `blobBody` which will be undefined.
*
* Default value is false
*/
enableBrowserStreams?: boolean;
/** Settings for configuring TLS authentication */
tlsSettings?: TlsSettings;
/**
* Proxy configuration.
*/
proxySettings?: ProxySettings;
/**
* If the connection should not be reused.
*/
disableKeepAlive?: boolean;
/**
* Used to abort the request later.
*/
abortSignal?: AbortSignalLike;
/**
* Options used to create a span when tracing is enabled.
*/
tracingOptions?: OperationTracingOptions;
/**
* Callback which fires upon upload progress.
*/
onUploadProgress?: (progress: TransferProgressEvent) => void;
/** Callback which fires upon download progress. */
onDownloadProgress?: (progress: TransferProgressEvent) => void;
/** Set to true if the request is sent over HTTP instead of HTTPS */
allowInsecureConnection?: boolean;
/**
* Additional options to set on the request. This provides a way to override
* existing ones or provide request properties that are not declared.
*
* For possible valid properties, see
* - NodeJS https.request options: https://nodejs.org/api/http.html#httprequestoptions-callback
* - Browser RequestInit: https://developer.mozilla.org/en-US/docs/Web/API/RequestInit
*
* WARNING: Options specified here will override any properties of same names when request is sent by {@link HttpClient}.
*/
requestOverrides?: Record<string, unknown>;
}
/**
* Creates a new pipeline request with the given options.
* This method is to allow for the easy setting of default values and not required.
* @param options - The options to create the request with.
*/
export declare function createPipelineRequest(options: PipelineRequestOptions): PipelineRequest;
//# sourceMappingURL=pipelineRequest.d.ts.map

View File

@@ -0,0 +1,15 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createPipelineRequest as tspCreatePipelineRequest, } from "@typespec/ts-http-runtime";
/**
* Creates a new pipeline request with the given options.
* This method is to allow for the easy setting of default values and not required.
* @param options - The options to create the request with.
*/
export function createPipelineRequest(options) {
// Cast required due to difference between ts-http-runtime requiring AbortSignal while core-rest-pipeline allows
// the more generic AbortSignalLike. The wrapAbortSignalLike pipeline policy will take care of ensuring that any AbortSignalLike in the request
// is converted into a true AbortSignal.
return tspCreatePipelineRequest(options);
}
//# sourceMappingURL=pipelineRequest.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
import type { PipelinePolicy } from "../pipeline.js";
import type { Agent } from "../interfaces.js";
/**
* Name of the Agent Policy
*/
export declare const agentPolicyName = "agentPolicy";
/**
* Gets a pipeline policy that sets http.agent
*/
export declare function agentPolicy(agent?: Agent): PipelinePolicy;
//# sourceMappingURL=agentPolicy.d.ts.map

View File

@@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { agentPolicyName as tspAgentPolicyName, agentPolicy as tspAgentPolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* Name of the Agent Policy
*/
export const agentPolicyName = tspAgentPolicyName;
/**
* Gets a pipeline policy that sets http.agent
*/
export function agentPolicy(agent) {
return tspAgentPolicy(agent);
}
//# sourceMappingURL=agentPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"agentPolicy.js","sourceRoot":"","sources":["../../../src/policies/agentPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,eAAe,IAAI,kBAAkB,EACrC,WAAW,IAAI,cAAc,GAC9B,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,kBAAkB,CAAC;AAElD;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa;IACvC,OAAO,cAAc,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport type { Agent } from \"../interfaces.js\";\nimport {\n agentPolicyName as tspAgentPolicyName,\n agentPolicy as tspAgentPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * Name of the Agent Policy\n */\nexport const agentPolicyName = tspAgentPolicyName;\n\n/**\n * Gets a pipeline policy that sets http.agent\n */\nexport function agentPolicy(agent?: Agent): PipelinePolicy {\n return tspAgentPolicy(agent);\n}\n"]}

View File

@@ -0,0 +1,33 @@
import type { TokenCredential } from "@azure/core-auth";
import type { AzureLogger } from "@azure/logger";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
*/
export declare const auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
/**
* Options to configure the auxiliaryAuthenticationHeaderPolicy
*/
export interface AuxiliaryAuthenticationHeaderPolicyOptions {
/**
* TokenCredential list used to get token from auxiliary tenants and
* one credential for each tenant the client may need to access
*/
credentials?: TokenCredential[];
/**
* Scopes depend on the cloud your application runs in
*/
scopes: string | string[];
/**
* A logger can be sent for debugging purposes.
*/
logger?: AzureLogger;
}
/**
* A policy for external tokens to `x-ms-authorization-auxiliary` header.
* This header will be used when creating a cross-tenant application we may need to handle authentication requests
* for resources that are in different tenants.
* You could see [ARM docs](https://learn.microsoft.com/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
*/
export declare function auxiliaryAuthenticationHeaderPolicy(options: AuxiliaryAuthenticationHeaderPolicyOptions): PipelinePolicy;
//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.d.ts.map

View File

@@ -0,0 +1,62 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createTokenCycler } from "../util/tokenCycler.js";
import { logger as coreLogger } from "../log.js";
/**
* The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
*/
export const auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
async function sendAuthorizeRequest(options) {
const { scopes, getAccessToken, request } = options;
const getTokenOptions = {
abortSignal: request.abortSignal,
tracingOptions: request.tracingOptions,
};
return (await getAccessToken(scopes, getTokenOptions))?.token ?? "";
}
/**
* A policy for external tokens to `x-ms-authorization-auxiliary` header.
* This header will be used when creating a cross-tenant application we may need to handle authentication requests
* for resources that are in different tenants.
* You could see [ARM docs](https://learn.microsoft.com/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
*/
export function auxiliaryAuthenticationHeaderPolicy(options) {
const { credentials, scopes } = options;
const logger = options.logger || coreLogger;
const tokenCyclerMap = new WeakMap();
return {
name: auxiliaryAuthenticationHeaderPolicyName,
async sendRequest(request, next) {
if (!request.url.toLowerCase().startsWith("https://")) {
throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
}
if (!credentials || credentials.length === 0) {
logger.info(`${auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
return next(request);
}
const tokenPromises = [];
for (const credential of credentials) {
let getAccessToken = tokenCyclerMap.get(credential);
if (!getAccessToken) {
getAccessToken = createTokenCycler(credential);
tokenCyclerMap.set(credential, getAccessToken);
}
tokenPromises.push(sendAuthorizeRequest({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
getAccessToken,
logger,
}));
}
const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
if (auxiliaryTokens.length === 0) {
logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
return next(request);
}
request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
return next(request);
},
};
}
//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,117 @@
import type { AccessToken, GetTokenOptions, TokenCredential } from "@azure/core-auth";
import type { AzureLogger } from "@azure/logger";
import type { PipelineRequest, PipelineResponse } from "../interfaces.js";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the bearerTokenAuthenticationPolicy.
*/
export declare const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
/**
* Options sent to the authorizeRequest callback
*/
export interface AuthorizeRequestOptions {
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Function that retrieves either a cached access token or a new access token.
*/
getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;
/**
* Request that the policy is trying to fulfill.
*/
request: PipelineRequest;
/**
* A logger, if one was sent through the HTTP pipeline.
*/
logger?: AzureLogger;
}
/**
* Options sent to the authorizeRequestOnChallenge callback
*/
export interface AuthorizeRequestOnChallengeOptions {
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Function that retrieves either a cached access token or a new access token.
*/
getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;
/**
* Request that the policy is trying to fulfill.
*/
request: PipelineRequest;
/**
* Response containing the challenge.
*/
response: PipelineResponse;
/**
* A logger, if one was sent through the HTTP pipeline.
*/
logger?: AzureLogger;
}
/**
* Options to override the processing of [Continuous Access Evaluation](https://learn.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.
*/
export interface ChallengeCallbacks {
/**
* Allows for the authorization of the main request of this policy before it's sent.
*/
authorizeRequest?(options: AuthorizeRequestOptions): Promise<void>;
/**
* Allows to handle authentication challenges and to re-authorize the request.
* The response containing the challenge is `options.response`.
* If this method returns true, the underlying request will be sent once again.
* The request may be modified before being sent.
*/
authorizeRequestOnChallenge?(options: AuthorizeRequestOnChallengeOptions): Promise<boolean>;
}
/**
* Options to configure the bearerTokenAuthenticationPolicy
*/
export interface BearerTokenAuthenticationPolicyOptions {
/**
* The TokenCredential implementation that can supply the bearer token.
*/
credential?: TokenCredential;
/**
* The scopes for which the bearer token applies.
*/
scopes: string | string[];
/**
* Allows for the processing of [Continuous Access Evaluation](https://learn.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.
* If provided, it must contain at least the `authorizeRequestOnChallenge` method.
* If provided, after a request is sent, if it has a challenge, it can be processed to re-send the original request with the relevant challenge information.
*/
challengeCallbacks?: ChallengeCallbacks;
/**
* A logger can be sent for debugging purposes.
*/
logger?: AzureLogger;
}
/**
* A policy that can request a token from a TokenCredential implementation and
* then apply it to the Authorization header of a request as a Bearer token.
*/
export declare function bearerTokenAuthenticationPolicy(options: BearerTokenAuthenticationPolicyOptions): PipelinePolicy;
/**
*
* Interface to represent a parsed challenge.
*
* @internal
*/
interface AuthChallenge {
scheme: string;
params: Record<string, string>;
}
/**
* Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
* Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
*
* @internal
*/
export declare function parseChallenges(challenges: string): AuthChallenge[];
export {};
//# sourceMappingURL=bearerTokenAuthenticationPolicy.d.ts.map

View File

@@ -0,0 +1,235 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createTokenCycler } from "../util/tokenCycler.js";
import { logger as coreLogger } from "../log.js";
import { isRestError } from "../restError.js";
/**
* The programmatic identifier of the bearerTokenAuthenticationPolicy.
*/
export const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
/**
* Try to send the given request.
*
* When a response is received, returns a tuple of the response received and, if the response was received
* inside a thrown RestError, the RestError that was thrown.
*
* Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
* will be rethrown.
*/
async function trySendRequest(request, next) {
try {
return [await next(request), undefined];
}
catch (e) {
if (isRestError(e) && e.response) {
return [e.response, e];
}
else {
throw e;
}
}
}
/**
* Default authorize request handler
*/
async function defaultAuthorizeRequest(options) {
const { scopes, getAccessToken, request } = options;
// Enable CAE true by default
const getTokenOptions = {
abortSignal: request.abortSignal,
tracingOptions: request.tracingOptions,
enableCae: true,
};
const accessToken = await getAccessToken(scopes, getTokenOptions);
if (accessToken) {
options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
}
/**
* We will retrieve the challenge only if the response status code was 401,
* and if the response contained the header "WWW-Authenticate" with a non-empty value.
*/
function isChallengeResponse(response) {
return response.status === 401 && response.headers.has("WWW-Authenticate");
}
/**
* Re-authorize the request for CAE challenge.
* The response containing the challenge is `options.response`.
* If this method returns true, the underlying request will be sent once again.
*/
async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
const { scopes } = onChallengeOptions;
const accessToken = await onChallengeOptions.getAccessToken(scopes, {
enableCae: true,
claims: caeClaims,
});
if (!accessToken) {
return false;
}
onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
return true;
}
/**
* A policy that can request a token from a TokenCredential implementation and
* then apply it to the Authorization header of a request as a Bearer token.
*/
export function bearerTokenAuthenticationPolicy(options) {
const { credential, scopes, challengeCallbacks } = options;
const logger = options.logger || coreLogger;
const callbacks = {
authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest,
authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks),
};
// This function encapsulates the entire process of reliably retrieving the token
// The options are left out of the public API until there's demand to configure this.
// Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
// in order to pass through the `options` object.
const getAccessToken = credential
? createTokenCycler(credential /* , options */)
: () => Promise.resolve(null);
return {
name: bearerTokenAuthenticationPolicyName,
/**
* If there's no challenge parameter:
* - It will try to retrieve the token using the cache, or the credential's getToken.
* - Then it will try the next policy with or without the retrieved token.
*
* It uses the challenge parameters to:
* - Skip a first attempt to get the token from the credential if there's no cached token,
* since it expects the token to be retrievable only after the challenge.
* - Prepare the outgoing request if the `prepareRequest` method has been provided.
* - Send an initial request to receive the challenge if it fails.
* - Process a challenge if the response contains it.
* - Retrieve a token with the challenge information, then re-send the request.
*/
async sendRequest(request, next) {
if (!request.url.toLowerCase().startsWith("https://")) {
throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
}
await callbacks.authorizeRequest({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
getAccessToken,
logger,
});
let response;
let error;
let shouldSendRequest;
[response, error] = await trySendRequest(request, next);
if (isChallengeResponse(response)) {
let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
// Handle CAE by default when receive CAE claim
if (claims) {
let parsedClaim;
// Return the response immediately if claims is not a valid base64 encoded string
try {
parsedClaim = atob(claims);
}
catch (e) {
logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
return response;
}
shouldSendRequest = await authorizeRequestOnCaeChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
response,
request,
getAccessToken,
logger,
}, parsedClaim);
// Send updated request and handle response for RestError
if (shouldSendRequest) {
[response, error] = await trySendRequest(request, next);
}
}
else if (callbacks.authorizeRequestOnChallenge) {
// Handle custom challenges when client provides custom callback
shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
response,
getAccessToken,
logger,
});
// Send updated request and handle response for RestError
if (shouldSendRequest) {
[response, error] = await trySendRequest(request, next);
}
// If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
if (isChallengeResponse(response)) {
claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
if (claims) {
let parsedClaim;
try {
parsedClaim = atob(claims);
}
catch (e) {
logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
return response;
}
shouldSendRequest = await authorizeRequestOnCaeChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
response,
request,
getAccessToken,
logger,
}, parsedClaim);
// Send updated request and handle response for RestError
if (shouldSendRequest) {
[response, error] = await trySendRequest(request, next);
}
}
}
}
}
if (error) {
throw error;
}
else {
return response;
}
},
};
}
/**
* Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
* Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
*
* @internal
*/
export function parseChallenges(challenges) {
// Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
// The challenge regex captures parameteres with either quotes values or unquoted values
const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
// Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
// CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
const paramRegex = /(\w+)="([^"]*)"/g;
const parsedChallenges = [];
let match;
// Iterate over each challenge match
while ((match = challengeRegex.exec(challenges)) !== null) {
const scheme = match[1];
const paramsString = match[2];
const params = {};
let paramMatch;
// Iterate over each parameter match
while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
params[paramMatch[1]] = paramMatch[2];
}
parsedChallenges.push({ scheme, params });
}
return parsedChallenges;
}
/**
* Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
* Return the value in the header without parsing the challenge
* @internal
*/
function getCaeChallengeClaims(challenges) {
if (!challenges) {
return;
}
// Find all challenges present in the header
const parsedChallenges = parseChallenges(challenges);
return parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")?.params.claims;
}
//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the decompressResponsePolicy.
*/
export declare const decompressResponsePolicyName = "decompressResponsePolicy";
/**
* A policy to enable response decompression according to Accept-Encoding header
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
*/
export declare function decompressResponsePolicy(): PipelinePolicy;
//# sourceMappingURL=decompressResponsePolicy.d.ts.map

View File

@@ -0,0 +1,15 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { decompressResponsePolicyName as tspDecompressResponsePolicyName, decompressResponsePolicy as tspDecompressResponsePolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* The programmatic identifier of the decompressResponsePolicy.
*/
export const decompressResponsePolicyName = tspDecompressResponsePolicyName;
/**
* A policy to enable response decompression according to Accept-Encoding header
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
*/
export function decompressResponsePolicy() {
return tspDecompressResponsePolicy();
}
//# sourceMappingURL=decompressResponsePolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"decompressResponsePolicy.js","sourceRoot":"","sources":["../../../src/policies/decompressResponsePolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,4BAA4B,IAAI,+BAA+B,EAC/D,wBAAwB,IAAI,2BAA2B,GACxD,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,+BAA+B,CAAC;AAE5E;;;GAGG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,2BAA2B,EAAE,CAAC;AACvC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n decompressResponsePolicyName as tspDecompressResponsePolicyName,\n decompressResponsePolicy as tspDecompressResponsePolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * The programmatic identifier of the decompressResponsePolicy.\n */\nexport const decompressResponsePolicyName = tspDecompressResponsePolicyName;\n\n/**\n * A policy to enable response decompression according to Accept-Encoding header\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding\n */\nexport function decompressResponsePolicy(): PipelinePolicy {\n return tspDecompressResponsePolicy();\n}\n"]}

View File

@@ -0,0 +1,19 @@
import type { PipelineRetryOptions } from "../interfaces.js";
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of the {@link defaultRetryPolicy}
*/
export declare const defaultRetryPolicyName = "defaultRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface DefaultRetryPolicyOptions extends PipelineRetryOptions {
}
/**
* A policy that retries according to three strategies:
* - When the server sends a 429 response with a Retry-After header.
* - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
* - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
*/
export declare function defaultRetryPolicy(options?: DefaultRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=defaultRetryPolicy.d.ts.map

View File

@@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { defaultRetryPolicyName as tspDefaultRetryPolicyName, defaultRetryPolicy as tspDefaultRetryPolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* Name of the {@link defaultRetryPolicy}
*/
export const defaultRetryPolicyName = tspDefaultRetryPolicyName;
/**
* A policy that retries according to three strategies:
* - When the server sends a 429 response with a Retry-After header.
* - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
* - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
*/
export function defaultRetryPolicy(options = {}) {
return tspDefaultRetryPolicy(options);
}
//# sourceMappingURL=defaultRetryPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"defaultRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/defaultRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EACL,sBAAsB,IAAI,yBAAyB,EACnD,kBAAkB,IAAI,qBAAqB,GAC5C,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,yBAAyB,CAAC;AAOhE;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAqC,EAAE;IACxE,OAAO,qBAAqB,CAAC,OAAO,CAAC,CAAC;AACxC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRetryOptions } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n defaultRetryPolicyName as tspDefaultRetryPolicyName,\n defaultRetryPolicy as tspDefaultRetryPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * Name of the {@link defaultRetryPolicy}\n */\nexport const defaultRetryPolicyName = tspDefaultRetryPolicyName;\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface DefaultRetryPolicyOptions extends PipelineRetryOptions {}\n\n/**\n * A policy that retries according to three strategies:\n * - When the server sends a 429 response with a Retry-After header.\n * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).\n * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.\n */\nexport function defaultRetryPolicy(options: DefaultRetryPolicyOptions = {}): PipelinePolicy {\n return tspDefaultRetryPolicy(options);\n}\n"]}

View File

@@ -0,0 +1,31 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the exponentialRetryPolicy.
*/
export declare const exponentialRetryPolicyName = "exponentialRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface ExponentialRetryPolicyOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
/**
* The amount of delay in milliseconds between retry attempts. Defaults to 1000
* (1 second.) The delay increases exponentially with each retry up to a maximum
* specified by maxRetryDelayInMs.
*/
retryDelayInMs?: number;
/**
* The maximum delay in milliseconds allowed before retrying an operation. Defaults
* to 64000 (64 seconds).
*/
maxRetryDelayInMs?: number;
}
/**
* A policy that attempts to retry requests while introducing an exponentially increasing delay.
* @param options - Options that configure retry logic.
*/
export declare function exponentialRetryPolicy(options?: ExponentialRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=exponentialRetryPolicy.d.ts.map

View File

@@ -0,0 +1,15 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { exponentialRetryPolicyName as tspExponentialRetryPolicyName, exponentialRetryPolicy as tspExponentialRetryPolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* The programmatic identifier of the exponentialRetryPolicy.
*/
export const exponentialRetryPolicyName = tspExponentialRetryPolicyName;
/**
* A policy that attempts to retry requests while introducing an exponentially increasing delay.
* @param options - Options that configure retry logic.
*/
export function exponentialRetryPolicy(options = {}) {
return tspExponentialRetryPolicy(options);
}
//# sourceMappingURL=exponentialRetryPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"exponentialRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/exponentialRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,0BAA0B,IAAI,6BAA6B,EAC3D,sBAAsB,IAAI,yBAAyB,GACpD,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,6BAA6B,CAAC;AAyBxE;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACpC,UAAyC,EAAE;IAE3C,OAAO,yBAAyB,CAAC,OAAO,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n exponentialRetryPolicyName as tspExponentialRetryPolicyName,\n exponentialRetryPolicy as tspExponentialRetryPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * The programmatic identifier of the exponentialRetryPolicy.\n */\nexport const exponentialRetryPolicyName = tspExponentialRetryPolicyName;\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ExponentialRetryPolicyOptions {\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 * A policy that attempts to retry requests while introducing an exponentially increasing delay.\n * @param options - Options that configure retry logic.\n */\nexport function exponentialRetryPolicy(\n options: ExponentialRetryPolicyOptions = {},\n): PipelinePolicy {\n return tspExponentialRetryPolicy(options);\n}\n"]}

View File

@@ -0,0 +1,10 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the formDataPolicy.
*/
export declare const formDataPolicyName = "formDataPolicy";
/**
* A policy that encodes FormData on the request into the body.
*/
export declare function formDataPolicy(): PipelinePolicy;
//# sourceMappingURL=formDataPolicy.d.ts.map

View File

@@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { formDataPolicyName as tspFormDataPolicyName, formDataPolicy as tspFormDataPolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* The programmatic identifier of the formDataPolicy.
*/
export const formDataPolicyName = tspFormDataPolicyName;
/**
* A policy that encodes FormData on the request into the body.
*/
export function formDataPolicy() {
return tspFormDataPolicy();
}
//# sourceMappingURL=formDataPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"formDataPolicy.js","sourceRoot":"","sources":["../../../src/policies/formDataPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,kBAAkB,IAAI,qBAAqB,EAC3C,cAAc,IAAI,iBAAiB,GACpC,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,qBAAqB,CAAC;AAExD;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,OAAO,iBAAiB,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n formDataPolicyName as tspFormDataPolicyName,\n formDataPolicy as tspFormDataPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * The programmatic identifier of the formDataPolicy.\n */\nexport const formDataPolicyName = tspFormDataPolicyName;\n\n/**\n * A policy that encodes FormData on the request into the body.\n */\nexport function formDataPolicy(): PipelinePolicy {\n return tspFormDataPolicy();\n}\n"]}

View File

@@ -0,0 +1,35 @@
import type { Debugger } from "@azure/logger";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the logPolicy.
*/
export declare const logPolicyName = "logPolicy";
/**
* Options to configure the logPolicy.
*/
export interface LogPolicyOptions {
/**
* Header names whose values will be logged when logging is enabled.
* Defaults include a list of well-known safe headers. Any headers
* specified in this field will be added to that list. Any other values will
* be written to logs as "REDACTED".
*/
additionalAllowedHeaderNames?: string[];
/**
* Query string names whose values will be logged when logging is enabled. By default no
* query string values are logged.
*/
additionalAllowedQueryParameters?: string[];
/**
* The log function to use for writing pipeline logs.
* Defaults to core-http's built-in logger.
* Compatible with the `debug` library.
*/
logger?: Debugger;
}
/**
* A policy that logs all requests and responses.
* @param options - Options to configure logPolicy.
*/
export declare function logPolicy(options?: LogPolicyOptions): PipelinePolicy;
//# sourceMappingURL=logPolicy.d.ts.map

View File

@@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { logger as coreLogger } from "../log.js";
import { logPolicyName as tspLogPolicyName, logPolicy as tspLogPolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* The programmatic identifier of the logPolicy.
*/
export const logPolicyName = tspLogPolicyName;
/**
* A policy that logs all requests and responses.
* @param options - Options to configure logPolicy.
*/
export function logPolicy(options = {}) {
return tspLogPolicy({
logger: coreLogger.info,
...options,
});
}
//# sourceMappingURL=logPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"logPolicy.js","sourceRoot":"","sources":["../../../src/policies/logPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EACL,aAAa,IAAI,gBAAgB,EACjC,SAAS,IAAI,YAAY,GAC1B,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AA4B9C;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,UAA4B,EAAE;IACtD,OAAO,YAAY,CAAC;QAClB,MAAM,EAAE,UAAU,CAAC,IAAI;QACvB,GAAG,OAAO;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { Debugger } from \"@azure/logger\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { logger as coreLogger } from \"../log.js\";\nimport {\n logPolicyName as tspLogPolicyName,\n logPolicy as tspLogPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * The programmatic identifier of the logPolicy.\n */\nexport const logPolicyName = tspLogPolicyName;\n\n/**\n * Options to configure the logPolicy.\n */\nexport interface LogPolicyOptions {\n /**\n * Header names whose values will be logged when logging is enabled.\n * Defaults include a list of well-known safe headers. Any headers\n * specified in this field will be added to that list. Any other values will\n * be written to logs as \"REDACTED\".\n */\n additionalAllowedHeaderNames?: string[];\n\n /**\n * Query string names whose values will be logged when logging is enabled. By default no\n * query string values are logged.\n */\n additionalAllowedQueryParameters?: string[];\n\n /**\n * The log function to use for writing pipeline logs.\n * Defaults to core-http's built-in logger.\n * Compatible with the `debug` library.\n */\n logger?: Debugger;\n}\n\n/**\n * A policy that logs all requests and responses.\n * @param options - Options to configure logPolicy.\n */\nexport function logPolicy(options: LogPolicyOptions = {}): PipelinePolicy {\n return tspLogPolicy({\n logger: coreLogger.info,\n ...options,\n });\n}\n"]}

View File

@@ -0,0 +1,10 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of multipart policy
*/
export declare const multipartPolicyName = "multipartPolicy";
/**
* Pipeline policy for multipart requests
*/
export declare function multipartPolicy(): PipelinePolicy;
//# sourceMappingURL=multipartPolicy.d.ts.map

View File

@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { multipartPolicyName as tspMultipartPolicyName, multipartPolicy as tspMultipartPolicy, } from "@typespec/ts-http-runtime/internal/policies";
import { getRawContent, hasRawContent } from "../util/file.js";
/**
* Name of multipart policy
*/
export const multipartPolicyName = tspMultipartPolicyName;
/**
* Pipeline policy for multipart requests
*/
export function multipartPolicy() {
const tspPolicy = tspMultipartPolicy();
return {
name: multipartPolicyName,
sendRequest: async (request, next) => {
if (request.multipartBody) {
for (const part of request.multipartBody.parts) {
if (hasRawContent(part.body)) {
part.body = getRawContent(part.body);
}
}
}
return tspPolicy.sendRequest(request, next);
},
};
}
//# sourceMappingURL=multipartPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"multipartPolicy.js","sourceRoot":"","sources":["../../../src/policies/multipartPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,mBAAmB,IAAI,sBAAsB,EAC7C,eAAe,IAAI,kBAAkB,GACtC,MAAM,6CAA6C,CAAC;AAKrD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE/D;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,sBAAsB,CAAC;AAE1D;;GAEG;AACH,MAAM,UAAU,eAAe;IAC7B,MAAM,SAAS,GAAG,kBAAkB,EAAE,CAAC;IAEvC,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,WAAW,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;YACnC,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;gBAC1B,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;oBAC/C,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;wBAC7B,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;oBACvC,CAAC;gBACH,CAAC;YACH,CAAC;YAED,OAAO,SAAS,CAAC,WAAW,CAAC,OAA6B,EAAE,IAAsB,CAAC,CAAC;QACtF,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n multipartPolicyName as tspMultipartPolicyName,\n multipartPolicy as tspMultipartPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\nimport type {\n PipelineRequest as TspPipelineRequest,\n SendRequest as TspSendRequest,\n} from \"@typespec/ts-http-runtime\";\nimport { getRawContent, hasRawContent } from \"../util/file.js\";\n\n/**\n * Name of multipart policy\n */\nexport const multipartPolicyName = tspMultipartPolicyName;\n\n/**\n * Pipeline policy for multipart requests\n */\nexport function multipartPolicy(): PipelinePolicy {\n const tspPolicy = tspMultipartPolicy();\n\n return {\n name: multipartPolicyName,\n sendRequest: async (request, next) => {\n if (request.multipartBody) {\n for (const part of request.multipartBody.parts) {\n if (hasRawContent(part.body)) {\n part.body = getRawContent(part.body);\n }\n }\n }\n\n return tspPolicy.sendRequest(request as TspPipelineRequest, next as TspSendRequest);\n },\n };\n}\n"]}

View File

@@ -0,0 +1,10 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the ndJsonPolicy.
*/
export declare const ndJsonPolicyName = "ndJsonPolicy";
/**
* ndJsonPolicy is a policy used to control keep alive settings for every request.
*/
export declare function ndJsonPolicy(): PipelinePolicy;
//# sourceMappingURL=ndJsonPolicy.d.ts.map

View File

@@ -0,0 +1,25 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* The programmatic identifier of the ndJsonPolicy.
*/
export const ndJsonPolicyName = "ndJsonPolicy";
/**
* ndJsonPolicy is a policy used to control keep alive settings for every request.
*/
export function ndJsonPolicy() {
return {
name: ndJsonPolicyName,
async sendRequest(request, next) {
// There currently isn't a good way to bypass the serializer
if (typeof request.body === "string" && request.body.startsWith("[")) {
const body = JSON.parse(request.body);
if (Array.isArray(body)) {
request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
}
}
return next(request);
},
};
}
//# sourceMappingURL=ndJsonPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ndJsonPolicy.js","sourceRoot":"","sources":["../../../src/policies/ndJsonPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC;AAE/C;;GAEG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO;QACL,IAAI,EAAE,gBAAgB;QACtB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,4DAA4D;YAC5D,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;gBACrE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;gBACtC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;oBACxB,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAC1E,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\n/**\n * The programmatic identifier of the ndJsonPolicy.\n */\nexport const ndJsonPolicyName = \"ndJsonPolicy\";\n\n/**\n * ndJsonPolicy is a policy used to control keep alive settings for every request.\n */\nexport function ndJsonPolicy(): PipelinePolicy {\n return {\n name: ndJsonPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n // There currently isn't a good way to bypass the serializer\n if (typeof request.body === \"string\" && request.body.startsWith(\"[\")) {\n const body = JSON.parse(request.body);\n if (Array.isArray(body)) {\n request.body = body.map((item) => JSON.stringify(item) + \"\\n\").join(\"\");\n }\n }\n return next(request);\n },\n };\n}\n"]}

View File

@@ -0,0 +1,26 @@
import type { ProxySettings } from "../interfaces.js";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the proxyPolicy.
*/
export declare const proxyPolicyName = "proxyPolicy";
/**
* This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
* If no argument is given, it attempts to parse a proxy URL from the environment
* variables `HTTPS_PROXY` or `HTTP_PROXY`.
* @param proxyUrl - The url of the proxy to use. May contain authentication information.
* @deprecated - Internally this method is no longer necessary when setting proxy information.
*/
export declare function getDefaultProxySettings(proxyUrl?: string): ProxySettings | undefined;
/**
* A policy that allows one to apply proxy settings to all requests.
* If not passed static settings, they will be retrieved from the HTTPS_PROXY
* or HTTP_PROXY environment variables.
* @param proxySettings - ProxySettings to use on each request.
* @param options - additional settings, for example, custom NO_PROXY patterns
*/
export declare function proxyPolicy(proxySettings?: ProxySettings, options?: {
/** a list of patterns to override those loaded from NO_PROXY environment variable. */
customNoProxyList?: string[];
}): PipelinePolicy;
//# sourceMappingURL=proxyPolicy.d.ts.map

View File

@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { proxyPolicy as tspProxyPolicy, proxyPolicyName as tspProxyPolicyName, getDefaultProxySettings as tspGetDefaultProxySettings, } from "@typespec/ts-http-runtime/internal/policies";
/**
* The programmatic identifier of the proxyPolicy.
*/
export const proxyPolicyName = tspProxyPolicyName;
/**
* This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
* If no argument is given, it attempts to parse a proxy URL from the environment
* variables `HTTPS_PROXY` or `HTTP_PROXY`.
* @param proxyUrl - The url of the proxy to use. May contain authentication information.
* @deprecated - Internally this method is no longer necessary when setting proxy information.
*/
export function getDefaultProxySettings(proxyUrl) {
return tspGetDefaultProxySettings(proxyUrl);
}
/**
* A policy that allows one to apply proxy settings to all requests.
* If not passed static settings, they will be retrieved from the HTTPS_PROXY
* or HTTP_PROXY environment variables.
* @param proxySettings - ProxySettings to use on each request.
* @param options - additional settings, for example, custom NO_PROXY patterns
*/
export function proxyPolicy(proxySettings, options) {
return tspProxyPolicy(proxySettings, options);
}
//# sourceMappingURL=proxyPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"proxyPolicy.js","sourceRoot":"","sources":["../../../src/policies/proxyPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EACL,WAAW,IAAI,cAAc,EAC7B,eAAe,IAAI,kBAAkB,EACrC,uBAAuB,IAAI,0BAA0B,GACtD,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,kBAAkB,CAAC;AAElD;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CAAC,QAAiB;IACvD,OAAO,0BAA0B,CAAC,QAAQ,CAAC,CAAC;AAC9C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CACzB,aAA6B,EAC7B,OAGC;IAED,OAAO,cAAc,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAChD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { ProxySettings } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n proxyPolicy as tspProxyPolicy,\n proxyPolicyName as tspProxyPolicyName,\n getDefaultProxySettings as tspGetDefaultProxySettings,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * The programmatic identifier of the proxyPolicy.\n */\nexport const proxyPolicyName = tspProxyPolicyName;\n\n/**\n * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.\n * If no argument is given, it attempts to parse a proxy URL from the environment\n * variables `HTTPS_PROXY` or `HTTP_PROXY`.\n * @param proxyUrl - The url of the proxy to use. May contain authentication information.\n * @deprecated - Internally this method is no longer necessary when setting proxy information.\n */\nexport function getDefaultProxySettings(proxyUrl?: string): ProxySettings | undefined {\n return tspGetDefaultProxySettings(proxyUrl);\n}\n\n/**\n * A policy that allows one to apply proxy settings to all requests.\n * If not passed static settings, they will be retrieved from the HTTPS_PROXY\n * or HTTP_PROXY environment variables.\n * @param proxySettings - ProxySettings to use on each request.\n * @param options - additional settings, for example, custom NO_PROXY patterns\n */\nexport function proxyPolicy(\n proxySettings?: ProxySettings,\n options?: {\n /** a list of patterns to override those loaded from NO_PROXY environment variable. */\n customNoProxyList?: string[];\n },\n): PipelinePolicy {\n return tspProxyPolicy(proxySettings, options);\n}\n"]}

View File

@@ -0,0 +1,23 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the redirectPolicy.
*/
export declare const redirectPolicyName = "redirectPolicy";
/**
* Options for how redirect responses are handled.
*/
export interface RedirectPolicyOptions {
/**
* The maximum number of times the redirect URL will be tried before
* failing. Defaults to 20.
*/
maxRetries?: number;
}
/**
* A policy to follow Location headers from the server in order
* to support server-side redirection.
* In the browser, this policy is not used.
* @param options - Options to control policy behavior.
*/
export declare function redirectPolicy(options?: RedirectPolicyOptions): PipelinePolicy;
//# sourceMappingURL=redirectPolicy.d.ts.map

View File

@@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { redirectPolicyName as tspRedirectPolicyName, redirectPolicy as tspRedirectPolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* The programmatic identifier of the redirectPolicy.
*/
export const redirectPolicyName = tspRedirectPolicyName;
/**
* A policy to follow Location headers from the server in order
* to support server-side redirection.
* In the browser, this policy is not used.
* @param options - Options to control policy behavior.
*/
export function redirectPolicy(options = {}) {
return tspRedirectPolicy(options);
}
//# sourceMappingURL=redirectPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"redirectPolicy.js","sourceRoot":"","sources":["../../../src/policies/redirectPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,kBAAkB,IAAI,qBAAqB,EAC3C,cAAc,IAAI,iBAAiB,GACpC,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,qBAAqB,CAAC;AAaxD;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,UAAiC,EAAE;IAChE,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n redirectPolicyName as tspRedirectPolicyName,\n redirectPolicy as tspRedirectPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * The programmatic identifier of the redirectPolicy.\n */\nexport const redirectPolicyName = tspRedirectPolicyName;\n\n/**\n * Options for how redirect responses are handled.\n */\nexport interface RedirectPolicyOptions {\n /**\n * The maximum number of times the redirect URL will be tried before\n * failing. Defaults to 20.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy to follow Location headers from the server in order\n * to support server-side redirection.\n * In the browser, this policy is not used.\n * @param options - Options to control policy behavior.\n */\nexport function redirectPolicy(options: RedirectPolicyOptions = {}): PipelinePolicy {\n return tspRedirectPolicy(options);\n}\n"]}

View File

@@ -0,0 +1,79 @@
import type { PipelinePolicy } from "../pipeline.js";
import { type AzureLogger } from "@azure/logger";
import type { PipelineResponse } from "../interfaces.js";
import type { RestError } from "../restError.js";
/**
* Information provided to the retry strategy about the current progress of the retry policy.
*/
export interface RetryInformation {
/**
* A {@link PipelineResponse}, if the last retry attempt succeeded.
*/
response?: PipelineResponse;
/**
* A {@link RestError}, if the last retry attempt failed.
*/
responseError?: RestError;
/**
* Total number of retries so far.
*/
retryCount: number;
}
/**
* Properties that can modify the behavior of the retry policy.
*/
export interface RetryModifiers {
/**
* If true, allows skipping the current strategy from running on the retry policy.
*/
skipStrategy?: boolean;
/**
* Indicates to retry against this URL.
*/
redirectTo?: string;
/**
* Controls whether to retry in a given number of milliseconds.
* If provided, a new retry will be attempted.
*/
retryAfterInMs?: number;
/**
* Indicates to throw this error instead of retrying.
*/
errorToThrow?: RestError;
}
/**
* A retry strategy is intended to define whether to retry or not, and how to retry.
*/
export interface RetryStrategy {
/**
* Name of the retry strategy. Used for logging.
*/
name: string;
/**
* Logger. If it's not provided, a default logger for all retry strategies is used.
*/
logger?: AzureLogger;
/**
* Function that determines how to proceed with the subsequent requests.
* @param state - Retry state
*/
retry(state: RetryInformation): RetryModifiers;
}
/**
* Options to the {@link retryPolicy}
*/
export interface RetryPolicyOptions {
/**
* Maximum number of retries. If not specified, it will limit to 3 retries.
*/
maxRetries?: number;
/**
* Logger. If it's not provided, a default logger is used.
*/
logger?: AzureLogger;
}
/**
* retryPolicy is a generic policy to enable retrying requests when certain conditions are met
*/
export declare function retryPolicy(strategies: RetryStrategy[], options?: RetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=retryPolicy.d.ts.map

View File

@@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createClientLogger } from "@azure/logger";
import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js";
import { retryPolicy as tspRetryPolicy, } from "@typespec/ts-http-runtime/internal/policies";
const retryPolicyLogger = createClientLogger("core-rest-pipeline retryPolicy");
/**
* retryPolicy is a generic policy to enable retrying requests when certain conditions are met
*/
export function retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) {
// Cast is required since the TSP runtime retry strategy type is slightly different
// very deep down (using real AbortSignal vs. AbortSignalLike in RestError).
// In practice the difference doesn't actually matter.
return tspRetryPolicy(strategies, {
logger: retryPolicyLogger,
...options,
});
}
//# sourceMappingURL=retryPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"retryPolicy.js","sourceRoot":"","sources":["../../../src/policies/retryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAoB,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,OAAO,EACL,WAAW,IAAI,cAAc,GAE9B,MAAM,6CAA6C,CAAC;AAIrD,MAAM,iBAAiB,GAAG,kBAAkB,CAAC,gCAAgC,CAAC,CAAC;AA4E/E;;GAEG;AACH,MAAM,UAAU,WAAW,CACzB,UAA2B,EAC3B,UAA8B,EAAE,UAAU,EAAE,0BAA0B,EAAE;IAExE,mFAAmF;IACnF,4EAA4E;IAC5E,sDAAsD;IACtD,OAAO,cAAc,CAAC,UAAgC,EAAE;QACtD,MAAM,EAAE,iBAAiB;QACzB,GAAG,OAAO;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { type AzureLogger, createClientLogger } from \"@azure/logger\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants.js\";\n\nimport {\n retryPolicy as tspRetryPolicy,\n type RetryStrategy as TspRetryStrategy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\nimport type { PipelineResponse } from \"../interfaces.js\";\nimport type { RestError } from \"../restError.js\";\n\nconst retryPolicyLogger = createClientLogger(\"core-rest-pipeline retryPolicy\");\n\n/**\n * Information provided to the retry strategy about the current progress of the retry policy.\n */\nexport interface RetryInformation {\n /**\n * A {@link PipelineResponse}, if the last retry attempt succeeded.\n */\n response?: PipelineResponse;\n /**\n * A {@link RestError}, if the last retry attempt failed.\n */\n responseError?: RestError;\n /**\n * Total number of retries so far.\n */\n retryCount: number;\n}\n\n/**\n * Properties that can modify the behavior of the retry policy.\n */\nexport interface RetryModifiers {\n /**\n * If true, allows skipping the current strategy from running on the retry policy.\n */\n skipStrategy?: boolean;\n /**\n * Indicates to retry against this URL.\n */\n redirectTo?: string;\n /**\n * Controls whether to retry in a given number of milliseconds.\n * If provided, a new retry will be attempted.\n */\n retryAfterInMs?: number;\n /**\n * Indicates to throw this error instead of retrying.\n */\n errorToThrow?: RestError;\n}\n\n/**\n * A retry strategy is intended to define whether to retry or not, and how to retry.\n */\nexport interface RetryStrategy {\n /**\n * Name of the retry strategy. Used for logging.\n */\n name: string;\n /**\n * Logger. If it's not provided, a default logger for all retry strategies is used.\n */\n logger?: AzureLogger;\n /**\n * Function that determines how to proceed with the subsequent requests.\n * @param state - Retry state\n */\n retry(state: RetryInformation): RetryModifiers;\n}\n\n/**\n * Options to the {@link retryPolicy}\n */\nexport interface RetryPolicyOptions {\n /**\n * Maximum number of retries. If not specified, it will limit to 3 retries.\n */\n maxRetries?: number;\n /**\n * Logger. If it's not provided, a default logger is used.\n */\n logger?: AzureLogger;\n}\n\n/**\n * retryPolicy is a generic policy to enable retrying requests when certain conditions are met\n */\nexport function retryPolicy(\n strategies: RetryStrategy[],\n options: RetryPolicyOptions = { maxRetries: DEFAULT_RETRY_POLICY_COUNT },\n): PipelinePolicy {\n // Cast is required since the TSP runtime retry strategy type is slightly different\n // very deep down (using real AbortSignal vs. AbortSignalLike in RestError).\n // In practice the difference doesn't actually matter.\n return tspRetryPolicy(strategies as TspRetryStrategy[], {\n logger: retryPolicyLogger,\n ...options,\n });\n}\n"]}

View File

@@ -0,0 +1,13 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the setClientRequestIdPolicy.
*/
export declare const setClientRequestIdPolicyName = "setClientRequestIdPolicy";
/**
* Each PipelineRequest gets a unique id upon creation.
* This policy passes that unique id along via an HTTP header to enable better
* telemetry and tracing.
* @param requestIdHeaderName - The name of the header to pass the request ID to.
*/
export declare function setClientRequestIdPolicy(requestIdHeaderName?: string): PipelinePolicy;
//# sourceMappingURL=setClientRequestIdPolicy.d.ts.map

View File

@@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* The programmatic identifier of the setClientRequestIdPolicy.
*/
export const setClientRequestIdPolicyName = "setClientRequestIdPolicy";
/**
* Each PipelineRequest gets a unique id upon creation.
* This policy passes that unique id along via an HTTP header to enable better
* telemetry and tracing.
* @param requestIdHeaderName - The name of the header to pass the request ID to.
*/
export function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
return {
name: setClientRequestIdPolicyName,
async sendRequest(request, next) {
if (!request.headers.has(requestIdHeaderName)) {
request.headers.set(requestIdHeaderName, request.requestId);
}
return next(request);
},
};
}
//# sourceMappingURL=setClientRequestIdPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"setClientRequestIdPolicy.js","sourceRoot":"","sources":["../../../src/policies/setClientRequestIdPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AAEvE;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,mBAAmB,GAAG,wBAAwB;IAE9C,OAAO;QACL,IAAI,EAAE,4BAA4B;QAClC,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE,CAAC;gBAC9C,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;YAC9D,CAAC;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\n/**\n * The programmatic identifier of the setClientRequestIdPolicy.\n */\nexport const setClientRequestIdPolicyName = \"setClientRequestIdPolicy\";\n\n/**\n * Each PipelineRequest gets a unique id upon creation.\n * This policy passes that unique id along via an HTTP header to enable better\n * telemetry and tracing.\n * @param requestIdHeaderName - The name of the header to pass the request ID to.\n */\nexport function setClientRequestIdPolicy(\n requestIdHeaderName = \"x-ms-client-request-id\",\n): PipelinePolicy {\n return {\n name: setClientRequestIdPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.headers.has(requestIdHeaderName)) {\n request.headers.set(requestIdHeaderName, request.requestId);\n }\n return next(request);\n },\n };\n}\n"]}

View File

@@ -0,0 +1,33 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of the {@link systemErrorRetryPolicy}
*/
export declare const systemErrorRetryPolicyName = "systemErrorRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface SystemErrorRetryPolicyOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
/**
* The amount of delay in milliseconds between retry attempts. Defaults to 1000
* (1 second.) The delay increases exponentially with each retry up to a maximum
* specified by maxRetryDelayInMs.
*/
retryDelayInMs?: number;
/**
* The maximum delay in milliseconds allowed before retrying an operation. Defaults
* to 64000 (64 seconds).
*/
maxRetryDelayInMs?: number;
}
/**
* A retry policy that specifically seeks to handle errors in the
* underlying transport layer (e.g. DNS lookup failures) rather than
* retryable error codes from the server itself.
* @param options - Options that customize the policy.
*/
export declare function systemErrorRetryPolicy(options?: SystemErrorRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=systemErrorRetryPolicy.d.ts.map

View File

@@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { systemErrorRetryPolicy as tspSystemErrorRetryPolicy, systemErrorRetryPolicyName as tspSystemErrorRetryPolicyName, } from "@typespec/ts-http-runtime/internal/policies";
/**
* Name of the {@link systemErrorRetryPolicy}
*/
export const systemErrorRetryPolicyName = tspSystemErrorRetryPolicyName;
/**
* A retry policy that specifically seeks to handle errors in the
* underlying transport layer (e.g. DNS lookup failures) rather than
* retryable error codes from the server itself.
* @param options - Options that customize the policy.
*/
export function systemErrorRetryPolicy(options = {}) {
return tspSystemErrorRetryPolicy(options);
}
//# sourceMappingURL=systemErrorRetryPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"systemErrorRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/systemErrorRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,sBAAsB,IAAI,yBAAyB,EACnD,0BAA0B,IAAI,6BAA6B,GAC5D,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,6BAA6B,CAAC;AAyBxE;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,UAAyC,EAAE;IAE3C,OAAO,yBAAyB,CAAC,OAAO,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n systemErrorRetryPolicy as tspSystemErrorRetryPolicy,\n systemErrorRetryPolicyName as tspSystemErrorRetryPolicyName,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * Name of the {@link systemErrorRetryPolicy}\n */\nexport const systemErrorRetryPolicyName = tspSystemErrorRetryPolicyName;\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface SystemErrorRetryPolicyOptions {\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 * A retry policy that specifically seeks to handle errors in the\n * underlying transport layer (e.g. DNS lookup failures) rather than\n * retryable error codes from the server itself.\n * @param options - Options that customize the policy.\n */\nexport function systemErrorRetryPolicy(\n options: SystemErrorRetryPolicyOptions = {},\n): PipelinePolicy {\n return tspSystemErrorRetryPolicy(options);\n}\n"]}

View File

@@ -0,0 +1,26 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of the {@link throttlingRetryPolicy}
*/
export declare const throttlingRetryPolicyName = "throttlingRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface ThrottlingRetryPolicyOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
}
/**
* A policy that retries when the server sends a 429 response with a Retry-After header.
*
* To learn more, please refer to
* https://learn.microsoft.com/azure/azure-resource-manager/resource-manager-request-limits,
* https://learn.microsoft.com/azure/azure-subscription-service-limits and
* https://learn.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
*
* @param options - Options that configure retry logic.
*/
export declare function throttlingRetryPolicy(options?: ThrottlingRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=throttlingRetryPolicy.d.ts.map

View File

@@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { throttlingRetryPolicyName as tspThrottlingRetryPolicyName, throttlingRetryPolicy as tspThrottlingRetryPolicy, } from "@typespec/ts-http-runtime/internal/policies";
/**
* Name of the {@link throttlingRetryPolicy}
*/
export const throttlingRetryPolicyName = tspThrottlingRetryPolicyName;
/**
* A policy that retries when the server sends a 429 response with a Retry-After header.
*
* To learn more, please refer to
* https://learn.microsoft.com/azure/azure-resource-manager/resource-manager-request-limits,
* https://learn.microsoft.com/azure/azure-subscription-service-limits and
* https://learn.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
*
* @param options - Options that configure retry logic.
*/
export function throttlingRetryPolicy(options = {}) {
return tspThrottlingRetryPolicy(options);
}
//# sourceMappingURL=throttlingRetryPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"throttlingRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/throttlingRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,yBAAyB,IAAI,4BAA4B,EACzD,qBAAqB,IAAI,wBAAwB,GAClD,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,4BAA4B,CAAC;AAYtE;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,UAAwC,EAAE;IAC9E,OAAO,wBAAwB,CAAC,OAAO,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\nimport {\n throttlingRetryPolicyName as tspThrottlingRetryPolicyName,\n throttlingRetryPolicy as tspThrottlingRetryPolicy,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * Name of the {@link throttlingRetryPolicy}\n */\nexport const throttlingRetryPolicyName = tspThrottlingRetryPolicyName;\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ThrottlingRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy that retries when the server sends a 429 response with a Retry-After header.\n *\n * To learn more, please refer to\n * https://learn.microsoft.com/azure/azure-resource-manager/resource-manager-request-limits,\n * https://learn.microsoft.com/azure/azure-subscription-service-limits and\n * https://learn.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors\n *\n * @param options - Options that configure retry logic.\n */\nexport function throttlingRetryPolicy(options: ThrottlingRetryPolicyOptions = {}): PipelinePolicy {\n return tspThrottlingRetryPolicy(options);\n}\n"]}

View File

@@ -0,0 +1,11 @@
import type { PipelinePolicy } from "../pipeline.js";
import type { TlsSettings } from "../interfaces.js";
/**
* Name of the TLS Policy
*/
export declare const tlsPolicyName = "tlsPolicy";
/**
* Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
*/
export declare function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy;
//# sourceMappingURL=tlsPolicy.d.ts.map

View File

@@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { tlsPolicy as tspTlsPolicy, tlsPolicyName as tspTlsPolicyName, } from "@typespec/ts-http-runtime/internal/policies";
/**
* Name of the TLS Policy
*/
export const tlsPolicyName = tspTlsPolicyName;
/**
* Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
*/
export function tlsPolicy(tlsSettings) {
return tspTlsPolicy(tlsSettings);
}
//# sourceMappingURL=tlsPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"tlsPolicy.js","sourceRoot":"","sources":["../../../src/policies/tlsPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EACL,SAAS,IAAI,YAAY,EACzB,aAAa,IAAI,gBAAgB,GAClC,MAAM,6CAA6C,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAE9C;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,WAAyB;IACjD,OAAO,YAAY,CAAC,WAAW,CAAC,CAAC;AACnC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport type { TlsSettings } from \"../interfaces.js\";\n\nimport {\n tlsPolicy as tspTlsPolicy,\n tlsPolicyName as tspTlsPolicyName,\n} from \"@typespec/ts-http-runtime/internal/policies\";\n\n/**\n * Name of the TLS Policy\n */\nexport const tlsPolicyName = tspTlsPolicyName;\n\n/**\n * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.\n */\nexport function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy {\n return tspTlsPolicy(tlsSettings);\n}\n"]}

View File

@@ -0,0 +1,29 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the tracingPolicy.
*/
export declare const tracingPolicyName = "tracingPolicy";
/**
* Options to configure the tracing policy.
*/
export interface TracingPolicyOptions {
/**
* String prefix to add to the user agent logged as metadata
* on the generated Span.
* Defaults to an empty string.
*/
userAgentPrefix?: string;
/**
* Query string names whose values will be logged when logging is enabled. By default no
* query string values are logged.
*/
additionalAllowedQueryParameters?: string[];
}
/**
* A simple policy to create OpenTelemetry Spans for each request made by the pipeline
* that has SpanOptions with a parent.
* Requests made without a parent Span will not be recorded.
* @param options - Options to configure the telemetry logged by the tracing policy.
*/
export declare function tracingPolicy(options?: TracingPolicyOptions): PipelinePolicy;
//# sourceMappingURL=tracingPolicy.d.ts.map

View File

@@ -0,0 +1,131 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createTracingClient, } from "@azure/core-tracing";
import { SDK_VERSION } from "../constants.js";
import { getUserAgentValue } from "../util/userAgent.js";
import { logger } from "../log.js";
import { getErrorMessage, isError } from "@azure/core-util";
import { isRestError } from "../restError.js";
import { Sanitizer } from "@typespec/ts-http-runtime/internal/util";
/**
* The programmatic identifier of the tracingPolicy.
*/
export const tracingPolicyName = "tracingPolicy";
/**
* A simple policy to create OpenTelemetry Spans for each request made by the pipeline
* that has SpanOptions with a parent.
* Requests made without a parent Span will not be recorded.
* @param options - Options to configure the telemetry logged by the tracing policy.
*/
export function tracingPolicy(options = {}) {
const userAgentPromise = getUserAgentValue(options.userAgentPrefix);
const sanitizer = new Sanitizer({
additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
});
const tracingClient = tryCreateTracingClient();
return {
name: tracingPolicyName,
async sendRequest(request, next) {
if (!tracingClient) {
return next(request);
}
const userAgent = await userAgentPromise;
const spanAttributes = {
"http.url": sanitizer.sanitizeUrl(request.url),
"http.method": request.method,
"http.user_agent": userAgent,
requestId: request.requestId,
};
if (userAgent) {
spanAttributes["http.user_agent"] = userAgent;
}
const { span, tracingContext } = tryCreateSpan(tracingClient, request, spanAttributes) ?? {};
if (!span || !tracingContext) {
return next(request);
}
try {
const response = await tracingClient.withContext(tracingContext, next, request);
tryProcessResponse(span, response);
return response;
}
catch (err) {
tryProcessError(span, err);
throw err;
}
},
};
}
function tryCreateTracingClient() {
try {
return createTracingClient({
namespace: "",
packageName: "@azure/core-rest-pipeline",
packageVersion: SDK_VERSION,
});
}
catch (e) {
logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);
return undefined;
}
}
function tryCreateSpan(tracingClient, request, spanAttributes) {
try {
// As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
spanKind: "client",
spanAttributes,
});
// If the span is not recording, don't do any more work.
if (!span.isRecording()) {
span.end();
return undefined;
}
// set headers
const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
for (const [key, value] of Object.entries(headers)) {
request.headers.set(key, value);
}
return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
}
catch (e) {
logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);
return undefined;
}
}
function tryProcessError(span, error) {
try {
span.setStatus({
status: "error",
error: isError(error) ? error : undefined,
});
if (isRestError(error) && error.statusCode) {
span.setAttribute("http.status_code", error.statusCode);
}
span.end();
}
catch (e) {
logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
}
}
function tryProcessResponse(span, response) {
try {
span.setAttribute("http.status_code", response.status);
const serviceRequestId = response.headers.get("x-ms-request-id");
if (serviceRequestId) {
span.setAttribute("serviceRequestId", serviceRequestId);
}
// Per semantic conventions, only set the status to error if the status code is 4xx or 5xx.
// Otherwise, the status MUST remain unset.
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
if (response.status >= 400) {
span.setStatus({
status: "error",
});
}
span.end();
}
catch (e) {
logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
}
}
//# sourceMappingURL=tracingPolicy.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the userAgentPolicy.
*/
export declare const userAgentPolicyName = "userAgentPolicy";
/**
* Options for adding user agent details to outgoing requests.
*/
export interface UserAgentPolicyOptions {
/**
* String prefix to add to the user agent for outgoing requests.
* Defaults to an empty string.
*/
userAgentPrefix?: string;
}
/**
* A policy that sets the User-Agent header (or equivalent) to reflect
* the library version.
* @param options - Options to customize the user agent value.
*/
export declare function userAgentPolicy(options?: UserAgentPolicyOptions): PipelinePolicy;
//# sourceMappingURL=userAgentPolicy.d.ts.map

View File

@@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { getUserAgentHeaderName, getUserAgentValue } from "../util/userAgent.js";
const UserAgentHeaderName = getUserAgentHeaderName();
/**
* The programmatic identifier of the userAgentPolicy.
*/
export const userAgentPolicyName = "userAgentPolicy";
/**
* A policy that sets the User-Agent header (or equivalent) to reflect
* the library version.
* @param options - Options to customize the user agent value.
*/
export function userAgentPolicy(options = {}) {
const userAgentValue = getUserAgentValue(options.userAgentPrefix);
return {
name: userAgentPolicyName,
async sendRequest(request, next) {
if (!request.headers.has(UserAgentHeaderName)) {
request.headers.set(UserAgentHeaderName, await userAgentValue);
}
return next(request);
},
};
}
//# sourceMappingURL=userAgentPolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"userAgentPolicy.js","sourceRoot":"","sources":["../../../src/policies/userAgentPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEjF,MAAM,mBAAmB,GAAG,sBAAsB,EAAE,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,iBAAiB,CAAC;AAarD;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,UAAkC,EAAE;IAClE,MAAM,cAAc,GAAG,iBAAiB,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IAClE,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE,CAAC;gBAC9C,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,MAAM,cAAc,CAAC,CAAC;YACjE,CAAC;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { getUserAgentHeaderName, getUserAgentValue } from \"../util/userAgent.js\";\n\nconst UserAgentHeaderName = getUserAgentHeaderName();\n\n/**\n * The programmatic identifier of the userAgentPolicy.\n */\nexport const userAgentPolicyName = \"userAgentPolicy\";\n\n/**\n * Options for adding user agent details to outgoing requests.\n */\nexport interface UserAgentPolicyOptions {\n /**\n * String prefix to add to the user agent for outgoing requests.\n * Defaults to an empty string.\n */\n userAgentPrefix?: string;\n}\n\n/**\n * A policy that sets the User-Agent header (or equivalent) to reflect\n * the library version.\n * @param options - Options to customize the user agent value.\n */\nexport function userAgentPolicy(options: UserAgentPolicyOptions = {}): PipelinePolicy {\n const userAgentValue = getUserAgentValue(options.userAgentPrefix);\n return {\n name: userAgentPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.headers.has(UserAgentHeaderName)) {\n request.headers.set(UserAgentHeaderName, await userAgentValue);\n }\n return next(request);\n },\n };\n}\n"]}

View File

@@ -0,0 +1,10 @@
import { type PipelinePolicy } from "../pipeline.js";
export declare const wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy";
/**
* Policy that ensure that any AbortSignalLike is wrapped in a native AbortSignal for processing by the pipeline.
* Since the ts-http-runtime expects a native AbortSignal, this policy is used to ensure that any AbortSignalLike is wrapped in a native AbortSignal.
*
* @returns - created policy
*/
export declare function wrapAbortSignalLikePolicy(): PipelinePolicy;
//# sourceMappingURL=wrapAbortSignalLikePolicy.d.ts.map

View File

@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { wrapAbortSignalLike } from "../util/wrapAbortSignal.js";
export const wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy";
/**
* Policy that ensure that any AbortSignalLike is wrapped in a native AbortSignal for processing by the pipeline.
* Since the ts-http-runtime expects a native AbortSignal, this policy is used to ensure that any AbortSignalLike is wrapped in a native AbortSignal.
*
* @returns - created policy
*/
export function wrapAbortSignalLikePolicy() {
return {
name: wrapAbortSignalLikePolicyName,
sendRequest: async (request, next) => {
if (!request.abortSignal) {
return next(request);
}
const { abortSignal, cleanup } = wrapAbortSignalLike(request.abortSignal);
// eslint-disable-next-line no-param-reassign
request.abortSignal = abortSignal;
try {
return await next(request);
}
finally {
cleanup?.();
}
},
};
}
//# sourceMappingURL=wrapAbortSignalLikePolicy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"wrapAbortSignalLikePolicy.js","sourceRoot":"","sources":["../../../src/policies/wrapAbortSignalLikePolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,MAAM,CAAC,MAAM,6BAA6B,GAAG,2BAA2B,CAAC;AAEzE;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB;IACvC,OAAO;QACL,IAAI,EAAE,6BAA6B;QACnC,WAAW,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;YACnC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;gBACzB,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;YACvB,CAAC;YAED,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,mBAAmB,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;YAC1E,6CAA6C;YAC7C,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC;YAClC,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC;YAC7B,CAAC;oBAAS,CAAC;gBACT,OAAO,EAAE,EAAE,CAAC;YACd,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { type PipelinePolicy } from \"../pipeline.js\";\nimport { wrapAbortSignalLike } from \"../util/wrapAbortSignal.js\";\n\nexport const wrapAbortSignalLikePolicyName = \"wrapAbortSignalLikePolicy\";\n\n/**\n * Policy that ensure that any AbortSignalLike is wrapped in a native AbortSignal for processing by the pipeline.\n * Since the ts-http-runtime expects a native AbortSignal, this policy is used to ensure that any AbortSignalLike is wrapped in a native AbortSignal.\n *\n * @returns - created policy\n */\nexport function wrapAbortSignalLikePolicy(): PipelinePolicy {\n return {\n name: wrapAbortSignalLikePolicyName,\n sendRequest: async (request, next) => {\n if (!request.abortSignal) {\n return next(request);\n }\n\n const { abortSignal, cleanup } = wrapAbortSignalLike(request.abortSignal);\n // eslint-disable-next-line no-param-reassign\n request.abortSignal = abortSignal;\n try {\n return await next(request);\n } finally {\n cleanup?.();\n }\n },\n };\n}\n"]}

View File

@@ -0,0 +1,83 @@
import type { PipelineRequest, PipelineResponse } from "./interfaces.js";
/**
* The options supported by RestError.
*/
export interface RestErrorOptions {
/**
* The code of the error itself (use statics on RestError if possible.)
*/
code?: string;
/**
* The HTTP status code of the request (if applicable.)
*/
statusCode?: number;
/**
* The request that was made.
*/
request?: PipelineRequest;
/**
* The response received (if any.)
*/
response?: PipelineResponse;
}
/**
* A custom error type for failed pipeline requests.
*/
export interface RestErrorConstructor {
/**
* Something went wrong when making the request.
* This means the actual request failed for some reason,
* such as a DNS issue or the connection being lost.
*/
readonly REQUEST_SEND_ERROR: string;
/**
* This means that parsing the response from the server failed.
* It may have been malformed.
*/
readonly PARSE_ERROR: string;
/**
* Prototype of RestError
*/
readonly prototype: RestError;
/**
* Construct a new RestError.
*/
new (message: string, options?: RestErrorOptions): RestError;
}
/**
* A custom error type for failed pipeline requests.
*/
export interface RestError extends Error {
/**
* The code of the error itself (use statics on RestError if possible.)
*/
code?: string;
/**
* The HTTP status code of the request (if applicable.)
*/
statusCode?: number;
/**
* The request that was made.
* This property is non-enumerable.
*/
request?: PipelineRequest;
/**
* The response received (if any.)
* This property is non-enumerable.
*/
response?: PipelineResponse;
/**
* Bonus property set by the throw site.
*/
details?: unknown;
}
/**
* A custom error type for failed pipeline requests.
*/
export declare const RestError: RestErrorConstructor;
/**
* Typeguard for RestError
* @param e - Something caught by a catch clause.
*/
export declare function isRestError(e: unknown): e is RestError;
//# sourceMappingURL=restError.d.ts.map

View File

@@ -0,0 +1,16 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { RestError as TspRestError, isRestError as tspIsRestError, } from "@typespec/ts-http-runtime";
/**
* A custom error type for failed pipeline requests.
*/
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const RestError = TspRestError;
/**
* Typeguard for RestError
* @param e - Something caught by a catch clause.
*/
export function isRestError(e) {
return tspIsRestError(e);
}
//# sourceMappingURL=restError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"restError.js","sourceRoot":"","sources":["../../src/restError.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EACL,SAAS,IAAI,YAAY,EACzB,WAAW,IAAI,cAAc,GAC9B,MAAM,2BAA2B,CAAC;AA+EnC;;GAEG;AACH,2DAA2D;AAC3D,MAAM,CAAC,MAAM,SAAS,GAAyB,YAAoC,CAAC;AAEpF;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,CAAU;IACpC,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRequest, PipelineResponse } from \"./interfaces.js\";\n\nimport {\n RestError as TspRestError,\n isRestError as tspIsRestError,\n} from \"@typespec/ts-http-runtime\";\n\n/**\n * The options supported by RestError.\n */\nexport interface RestErrorOptions {\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n statusCode?: number;\n /**\n * The request that was made.\n */\n request?: PipelineRequest;\n /**\n * The response received (if any.)\n */\n response?: PipelineResponse;\n}\n\n/**\n * A custom error type for failed pipeline requests.\n */\nexport interface RestErrorConstructor {\n /**\n * Something went wrong when making the request.\n * This means the actual request failed for some reason,\n * such as a DNS issue or the connection being lost.\n */\n readonly REQUEST_SEND_ERROR: string;\n /**\n * This means that parsing the response from the server failed.\n * It may have been malformed.\n */\n readonly PARSE_ERROR: string;\n\n /**\n * Prototype of RestError\n */\n readonly prototype: RestError;\n\n /**\n * Construct a new RestError.\n */\n new (message: string, options?: RestErrorOptions): RestError;\n}\n\n/**\n * A custom error type for failed pipeline requests.\n */\nexport interface RestError extends Error {\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n statusCode?: number;\n /**\n * The request that was made.\n * This property is non-enumerable.\n */\n request?: PipelineRequest;\n /**\n * The response received (if any.)\n * This property is non-enumerable.\n */\n response?: PipelineResponse;\n /**\n * Bonus property set by the throw site.\n */\n details?: unknown;\n}\n\n/**\n * A custom error type for failed pipeline requests.\n */\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const RestError: RestErrorConstructor = TspRestError as RestErrorConstructor;\n\n/**\n * Typeguard for RestError\n * @param e - Something caught by a catch clause.\n */\nexport function isRestError(e: unknown): e is RestError {\n return tspIsRestError(e);\n}\n"]}

View File

@@ -0,0 +1,95 @@
/**
* Options passed into createFile specifying metadata about the file.
*/
export interface CreateFileOptions {
/**
* The MIME type of the file.
*/
type?: string;
/**
* Last modified time of the file as a UNIX timestamp.
* This will default to the current date.
*/
lastModified?: number;
/**
* relative path of this file when uploading a directory.
*/
webkitRelativePath?: string;
}
/**
* Extra options for createFile when a stream is being passed in.
*/
export interface CreateFileFromStreamOptions extends CreateFileOptions {
/**
* Size of the file represented by the stream in bytes.
*
* This will be used by the pipeline when calculating the Content-Length header
* for the overall request.
*/
size?: number;
}
/**
* Private symbol used as key on objects created using createFile containing the
* original source of the file object.
*
* This is used in Node to access the original Node stream without using Blob#stream, which
* returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
* Readable#to/fromWeb in Node versions we support:
* - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
* - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
*
* Once these versions are no longer supported, we may be able to stop doing this.
*
* @internal
*/
declare const rawContent: unique symbol;
/**
* Type signature of a blob-like object with a raw content property.
*/
export interface RawContent extends Blob {
[rawContent](): Uint8Array | NodeJS.ReadableStream | ReadableStream<Uint8Array>;
}
/**
* Type guard to check if a given object is a blob-like object with a raw content property.
*/
export declare function hasRawContent(x: unknown): x is RawContent;
/**
* Extract the raw content from a given blob-like object. If the input was created using createFile
* or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
* For true instances of Blob and File, returns the actual blob.
*
* @internal
*/
export declare function getRawContent(blob: Blob): Blob | NodeJS.ReadableStream | ReadableStream<Uint8Array> | Uint8Array;
/**
* Create an object that implements the File interface. This object is intended to be
* passed into RequestBodyType.formData, and is not guaranteed to work as expected in
* other situations.
*
* Use this function to:
* - Create a File object for use in RequestBodyType.formData in environments where the
* global File object is unavailable.
* - Create a File-like object from a readable stream without reading the stream into memory.
*
* @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
* passed in a request's form data map, the stream will not be read into memory
* and instead will be streamed when the request is made. In the event of a retry, the
* stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
* @param name - the name of the file.
* @param options - optional metadata about the file, e.g. file name, file size, MIME type.
*/
export declare function createFileFromStream(stream: () => ReadableStream<Uint8Array> | NodeJS.ReadableStream, name: string, options?: CreateFileFromStreamOptions): File;
/**
* Create an object that implements the File interface. This object is intended to be
* passed into RequestBodyType.formData, and is not guaranteed to work as expected in
* other situations.
*
* Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
*
* @param content - the content of the file as a Uint8Array in memory.
* @param name - the name of the file.
* @param options - optional metadata about the file, e.g. file name, file size, MIME type.
*/
export declare function createFile(content: Uint8Array, name: string, options?: CreateFileOptions): File;
export {};
//# sourceMappingURL=file.d.ts.map

View File

@@ -0,0 +1,121 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { isNodeLike } from "@azure/core-util";
function isNodeReadableStream(x) {
return Boolean(x && typeof x["pipe"] === "function");
}
const unimplementedMethods = {
arrayBuffer: () => {
throw new Error("Not implemented");
},
bytes: () => {
throw new Error("Not implemented");
},
slice: () => {
throw new Error("Not implemented");
},
text: () => {
throw new Error("Not implemented");
},
};
/**
* Private symbol used as key on objects created using createFile containing the
* original source of the file object.
*
* This is used in Node to access the original Node stream without using Blob#stream, which
* returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
* Readable#to/fromWeb in Node versions we support:
* - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
* - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
*
* Once these versions are no longer supported, we may be able to stop doing this.
*
* @internal
*/
const rawContent = Symbol("rawContent");
/**
* Type guard to check if a given object is a blob-like object with a raw content property.
*/
export function hasRawContent(x) {
return typeof x[rawContent] === "function";
}
/**
* Extract the raw content from a given blob-like object. If the input was created using createFile
* or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
* For true instances of Blob and File, returns the actual blob.
*
* @internal
*/
export function getRawContent(blob) {
if (hasRawContent(blob)) {
return blob[rawContent]();
}
else {
return blob;
}
}
/**
* Create an object that implements the File interface. This object is intended to be
* passed into RequestBodyType.formData, and is not guaranteed to work as expected in
* other situations.
*
* Use this function to:
* - Create a File object for use in RequestBodyType.formData in environments where the
* global File object is unavailable.
* - Create a File-like object from a readable stream without reading the stream into memory.
*
* @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
* passed in a request's form data map, the stream will not be read into memory
* and instead will be streamed when the request is made. In the event of a retry, the
* stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
* @param name - the name of the file.
* @param options - optional metadata about the file, e.g. file name, file size, MIME type.
*/
export function createFileFromStream(stream, name, options = {}) {
return {
...unimplementedMethods,
type: options.type ?? "",
lastModified: options.lastModified ?? new Date().getTime(),
webkitRelativePath: options.webkitRelativePath ?? "",
size: options.size ?? -1,
name,
stream: () => {
const s = stream();
if (isNodeReadableStream(s)) {
throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
}
return s;
},
[rawContent]: stream,
};
}
/**
* Create an object that implements the File interface. This object is intended to be
* passed into RequestBodyType.formData, and is not guaranteed to work as expected in
* other situations.
*
* Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
*
* @param content - the content of the file as a Uint8Array in memory.
* @param name - the name of the file.
* @param options - optional metadata about the file, e.g. file name, file size, MIME type.
*/
export function createFile(content, name, options = {}) {
if (isNodeLike) {
return {
...unimplementedMethods,
type: options.type ?? "",
lastModified: options.lastModified ?? new Date().getTime(),
webkitRelativePath: options.webkitRelativePath ?? "",
size: content.byteLength,
name,
arrayBuffer: async () => content.buffer,
stream: () => new Blob([content]).stream(),
[rawContent]: () => content,
};
}
else {
return new File([content], name, options);
}
}
//# sourceMappingURL=file.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,45 @@
import type { AccessToken, GetTokenOptions, TokenCredential } from "@azure/core-auth";
/**
* A function that gets a promise of an access token and allows providing
* options.
*
* @param options - the options to pass to the underlying token provider
*/
export type AccessTokenGetter = (scopes: string | string[], options: GetTokenOptions) => Promise<AccessToken>;
export interface TokenCyclerOptions {
/**
* The window of time before token expiration during which the token will be
* considered unusable due to risk of the token expiring before sending the
* request.
*
* This will only become meaningful if the refresh fails for over
* (refreshWindow - forcedRefreshWindow) milliseconds.
*/
forcedRefreshWindowInMs: number;
/**
* Interval in milliseconds to retry failed token refreshes.
*/
retryIntervalInMs: number;
/**
* The window of time before token expiration during which
* we will attempt to refresh the token.
*/
refreshWindowInMs: number;
}
export declare const DEFAULT_CYCLER_OPTIONS: TokenCyclerOptions;
/**
* Creates a token cycler from a credential, scopes, and optional settings.
*
* A token cycler represents a way to reliably retrieve a valid access token
* from a TokenCredential. It will handle initializing the token, refreshing it
* when it nears expiration, and synchronizes refresh attempts to avoid
* concurrency hazards.
*
* @param credential - the underlying TokenCredential that provides the access
* token
* @param tokenCyclerOptions - optionally override default settings for the cycler
*
* @returns - a function that reliably produces a valid access token
*/
export declare function createTokenCycler(credential: TokenCredential, tokenCyclerOptions?: Partial<TokenCyclerOptions>): AccessTokenGetter;
//# sourceMappingURL=tokenCycler.d.ts.map

View File

@@ -0,0 +1,163 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { delay } from "@azure/core-util";
// Default options for the cycler if none are provided
export const DEFAULT_CYCLER_OPTIONS = {
forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
retryIntervalInMs: 3000, // Allow refresh attempts every 3s
refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
};
/**
* Converts an an unreliable access token getter (which may resolve with null)
* into an AccessTokenGetter by retrying the unreliable getter in a regular
* interval.
*
* @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
* @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
* @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
* @returns - A promise that, if it resolves, will resolve with an access token.
*/
async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
// This wrapper handles exceptions gracefully as long as we haven't exceeded
// the timeout.
async function tryGetAccessToken() {
if (Date.now() < refreshTimeout) {
try {
return await getAccessToken();
}
catch {
return null;
}
}
else {
const finalToken = await getAccessToken();
// Timeout is up, so throw if it's still null
if (finalToken === null) {
throw new Error("Failed to refresh access token.");
}
return finalToken;
}
}
let token = await tryGetAccessToken();
while (token === null) {
await delay(retryIntervalInMs);
token = await tryGetAccessToken();
}
return token;
}
/**
* Creates a token cycler from a credential, scopes, and optional settings.
*
* A token cycler represents a way to reliably retrieve a valid access token
* from a TokenCredential. It will handle initializing the token, refreshing it
* when it nears expiration, and synchronizes refresh attempts to avoid
* concurrency hazards.
*
* @param credential - the underlying TokenCredential that provides the access
* token
* @param tokenCyclerOptions - optionally override default settings for the cycler
*
* @returns - a function that reliably produces a valid access token
*/
export function createTokenCycler(credential, tokenCyclerOptions) {
let refreshWorker = null;
let token = null;
let tenantId;
const options = {
...DEFAULT_CYCLER_OPTIONS,
...tokenCyclerOptions,
};
/**
* This little holder defines several predicates that we use to construct
* the rules of refreshing the token.
*/
const cycler = {
/**
* Produces true if a refresh job is currently in progress.
*/
get isRefreshing() {
return refreshWorker !== null;
},
/**
* Produces true if the cycler SHOULD refresh (we are within the refresh
* window and not already refreshing)
*/
get shouldRefresh() {
if (cycler.isRefreshing) {
return false;
}
if (token?.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) {
return true;
}
return (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now();
},
/**
* Produces true if the cycler MUST refresh (null or nearly-expired
* token).
*/
get mustRefresh() {
return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
},
};
/**
* Starts a refresh job or returns the existing job if one is already
* running.
*/
function refresh(scopes, getTokenOptions) {
if (!cycler.isRefreshing) {
// We bind `scopes` here to avoid passing it around a lot
const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
// Take advantage of promise chaining to insert an assignment to `token`
// before the refresh can be considered done.
refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs,
// If we don't have a token, then we should timeout immediately
token?.expiresOnTimestamp ?? Date.now())
.then((_token) => {
refreshWorker = null;
token = _token;
tenantId = getTokenOptions.tenantId;
return token;
})
.catch((reason) => {
// We also should reset the refresher if we enter a failed state. All
// existing awaiters will throw, but subsequent requests will start a
// new retry chain.
refreshWorker = null;
token = null;
tenantId = undefined;
throw reason;
});
}
return refreshWorker;
}
return async (scopes, tokenOptions) => {
//
// Simple rules:
// - If we MUST refresh, then return the refresh task, blocking
// the pipeline until a token is available.
// - If we SHOULD refresh, then run refresh but don't return it
// (we can still use the cached token).
// - Return the token, since it's fine if we didn't return in
// step 1.
//
const hasClaimChallenge = Boolean(tokenOptions.claims);
const tenantIdChanged = tenantId !== tokenOptions.tenantId;
if (hasClaimChallenge) {
// If we've received a claim, we know the existing token isn't valid
// We want to clear it so that that refresh worker won't use the old expiration time as a timeout
token = null;
}
// If the tenantId passed in token options is different to the one we have
// Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
// refresh the token with the new tenantId or token.
const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
if (mustRefresh) {
return refresh(scopes, tokenOptions);
}
if (cycler.shouldRefresh) {
refresh(scopes, tokenOptions);
}
return token;
};
}
//# sourceMappingURL=tokenCycler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
/**
* @internal
*/
export declare function getUserAgentHeaderName(): string;
/**
* @internal
*/
export declare function getUserAgentValue(prefix?: string): Promise<string>;
//# sourceMappingURL=userAgent.d.ts.map

View File

@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { getHeaderName, setPlatformSpecificData } from "./userAgentPlatform.js";
import { SDK_VERSION } from "../constants.js";
function getUserAgentString(telemetryInfo) {
const parts = [];
for (const [key, value] of telemetryInfo) {
const token = value ? `${key}/${value}` : key;
parts.push(token);
}
return parts.join(" ");
}
/**
* @internal
*/
export function getUserAgentHeaderName() {
return getHeaderName();
}
/**
* @internal
*/
export async function getUserAgentValue(prefix) {
const runtimeInfo = new Map();
runtimeInfo.set("core-rest-pipeline", SDK_VERSION);
await setPlatformSpecificData(runtimeInfo);
const defaultAgent = getUserAgentString(runtimeInfo);
const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
return userAgentValue;
}
//# sourceMappingURL=userAgent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"userAgent.js","sourceRoot":"","sources":["../../../src/util/userAgent.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,SAAS,kBAAkB,CAAC,aAAkC;IAC5D,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,aAAa,EAAE,CAAC;QACzC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,sBAAsB;IACpC,OAAO,aAAa,EAAE,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,MAAe;IACrD,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC9C,WAAW,CAAC,GAAG,CAAC,oBAAoB,EAAE,WAAW,CAAC,CAAC;IACnD,MAAM,uBAAuB,CAAC,WAAW,CAAC,CAAC;IAC3C,MAAM,YAAY,GAAG,kBAAkB,CAAC,WAAW,CAAC,CAAC;IACrD,MAAM,cAAc,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI,YAAY,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC;IAC3E,OAAO,cAAc,CAAC;AACxB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { getHeaderName, setPlatformSpecificData } from \"./userAgentPlatform.js\";\nimport { SDK_VERSION } from \"../constants.js\";\n\nfunction getUserAgentString(telemetryInfo: Map<string, string>): string {\n const parts: string[] = [];\n for (const [key, value] of telemetryInfo) {\n const token = value ? `${key}/${value}` : key;\n parts.push(token);\n }\n return parts.join(\" \");\n}\n\n/**\n * @internal\n */\nexport function getUserAgentHeaderName(): string {\n return getHeaderName();\n}\n\n/**\n * @internal\n */\nexport async function getUserAgentValue(prefix?: string): Promise<string> {\n const runtimeInfo = new Map<string, string>();\n runtimeInfo.set(\"core-rest-pipeline\", SDK_VERSION);\n await setPlatformSpecificData(runtimeInfo);\n const defaultAgent = getUserAgentString(runtimeInfo);\n const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;\n return userAgentValue;\n}\n"]}

Some files were not shown because too many files have changed in this diff Show More